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" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
5676
""" metareader(md::MatrixDescriptor, key::AbstractString) Return specific data files (matrix, rhs, solution, or other metadata). The `key` must be contained in data.metadata or an `DataError` is thrown. Hint: `md.A, md.b, md.x` also deliver the matrix, rhs, and solution. So this is needed specifically for other metadata. """ function metareader(mdesc::MatrixDescriptor{<:RemoteMatrixData}, name::AbstractString) name = metastring_reverse(mdesc.data, name) get!(mdesc.cache, name) do _metareader(mdesc.data, name) end end function metareader(mdesc::MatrixDescriptor{<:GeneratedMatrixData}, name::AbstractString) fillcache!(mdesc) dao = mdesc.cache[] if name == "A" && dao isa AbstractArray dao else try getproperty(dao, Symbol(name)) catch daterr("this instance of '$(typeof(dao))' has no property '$name'") end end end function _metareader(data::RemoteMatrixData, name::AbstractString) if name in data.metadata path = joinpath(dirname(matrixfile(data)), name) endswith(name, ".mtx") ? mmread(path) : read(path, String) else daterr("$(data.name) has no metadata $name") end end function fillcache!(mdesc::MatrixDescriptor{<:GeneratedMatrixData}) dao = mdesc.cache[] if dao === nothing dao = mdesc.cache[] = mdesc.data.func(mdesc.args...) dao !== nothing || daterr("function $(mdesc.data.func) returned `nothing`") end dao end # This a the preferred API to access metadata. import Base: getproperty, propertynames, getindex function getproperty(mdesc::MatrixDescriptor{T}, s::Symbol) where T s in (:data, :args, :cache) && return getfield(mdesc, s) s in metasymbols(mdesc) && return metareader(mdesc, string(s)) if T <: RemoteMatrixData s in (:m, :n, :nnz, :dnz) && return getfield(mdesc.data.header, s) else s == :m && return size(mdesc.A, 1) s == :n && return size(mdesc.A, 2) s == :nnz && return count(mdesc.A .!= 0) s == :dnz && return 0 end metareader(mdesc, string(s)) end function propertynames(mdesc::MatrixDescriptor{T}; private=false) where T props = Symbol[] append!(props, metasymbols(mdesc)) append!(props, [:m, :n, :nnz, :dnz]) private && append!(props, fieldnames(MatrixDescriptor)) props end function getproperty(data::RemoteMatrixData, s::Symbol) s in (:name, :id, :header, :properties, :metadata) && return getfield(data, s) s in fieldnames(MetaInfo) && return getfield(data.header, s) getfield(data, s) end function propertynames(data::RemoteMatrixData; private=false) props = [PROPS...] private && append!(props, fieldnames(RemoteMatrixData)) props end function propertynames(data::GeneratedMatrixData; private=false) private ? fieldnames(GeneratedMatrixData) : [:name, :id] end """ metasymbols(md::MatrixDescriptor) Return a vector of symbols, which point to metadata of the problem. These symbols `s` may be used to access the objects by `getproperty(md, s)` or by `getindex(md, s)`. The syntax `md.S` is preferred, if `S` is a constant `Julia` word. In any case `md[s]` is possible. Example: `md = mdopen("*/bfly"); A = md.A; co = md.coord; txt10 = md["Gname_10.txt"]` """ metasymbols(md::MatrixDescriptor{<:RemoteMatrixData}) = metasymbols(md.data) function metasymbols(data::RemoteMatrixData) Symbol.(metastring.(data.name, getmeta(data))) end function metasymbols(md::MatrixDescriptor{<:GeneratedMatrixData}) mdc = md.cache[] mdc isa Array || mdc === nothing ? [:A] : propertynames(mdc) end metasymbols(data::MatrixData) = [:A] function Base.getindex(mdesc::MatrixDescriptor, name::Union{Symbol,AbstractString}) metareader(mdesc, string(name)) end function (mdesc::MatrixDescriptor)(name::Union{Symbol,AbstractString}) metareader(mdesc, string(name)) end #internal helper to select special metadata (matrix, rhs, or solution) function metaname(data::RemoteMatrixData, exli::AbstractString...) base = rsplit(data.name, '/', limit=2)[end] meda = getmeta(data) for ext in exli f = metastring_reverse(data, ext) if f in meda return f end end daterr("unknown metadata extensions: $exli - available $(String.(data.metadata))") end """ metastring(name, metaname) In the standard cases convert full meta name to abbreviated form. + given `name = "abc"`, then + `"abc.mtx" => "A"` + `"abc_def.mtx" => "def"` + `"abc_def.txt" => "def.txt"` + `"abc-def.mtx" => "abc-def.mtx"` """ function metastring(name::AbstractString, metaname::AbstractString) MTX = ".mtx" base = split(name, '/')[end] meta = metaname if meta == string(base, MTX) meta = "A" elseif startswith(meta, string(base, '_')) meta = meta[sizeof(base)+2:end] end es = rsplit(meta, '.', limit=2) if endswith(meta, MTX) && meta != metaname meta = meta[1:end-sizeof(MTX)] end meta end """ metastring_reverse(data::MatrixData, abbreviation::String) Given a `MatrixData` object and an abbreviation, return a matching full metadata name for the abbreviation. If no full name is found, return the abbreviation unchanged. """ function metastring_reverse(data::RemoteMatrixData, metaabbr::AbstractString) MTX = ".mtx" base = split(data.name, '/')[end] metaabbr == "A" && return string(base, MTX) mdata = getmeta(data) meta = string(base, '_', metaabbr) meta in mdata && return meta meta = string(meta, MTX) meta in mdata && return meta metaabbr end metastring_reverse(::MatrixData, metaabbr::AbstractString) = metaabbr
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
9853
##################################################### # Download data from UF Sparse Matrix Collection ##################################################### using Base.Filesystem using ChannelBuffers # collect the keys from local database (MATRIXDICT or USERMATRIXDICT) # provide a numerical id counting from 1 for either database. function insertlocal(db::MatrixDatabase, T::Type{<:GeneratedMatrixData}, ldb::Dict{<:AbstractString,Function}) cnt = 0 ks = sort!(collect(keys(ldb))) for k in ks cnt += 1 push!(db, T(k, cnt, ldb[k])) end cnt end dbpath(db::MatrixDatabase) = abspath(data_dir(), "db.data") function readdb(db::MatrixDatabase) @info("reading database") cachedb = dbpath(db) open(cachedb, "r") do io dbx = deserialize(io) merge!(db.data, dbx.data) merge!(db.aliases, dbx.aliases) end end function writedb(db::MatrixDatabase) cachedb = dbpath(db) #Avoid serializing user matrices, since we don't know which ones will be loaded on deserialization. dbx_data = filter(((key, val),) -> !(val isa GeneratedMatrixData{:U}), db.data) dbx_aliases = filter(((_, key),) -> !(db.data[key] isa GeneratedMatrixData{:U}), db.aliases) dbx = MatrixDatabase(dbx_data, dbx_aliases) open(cachedb, "w") do io serialize(io, dbx) end end """ MatrixDepot.downloadindices(db) download index files and store matrix data in `db`. additionally generate aliases for local and loaded matrices. Serialize db object in file `db.data`. If a file `db.data` is present in the data directory, deserialize the data instead of downloading and collecting data. """ function downloadindices(db::MatrixDatabase; ignoredb=false) added = 0 if !ignoredb && isfile(dbpath(db)) try readdb(db) catch ex println(ex) @warn("recreating database file") _downloadindices(db) added = 1 end else @info("creating database file") _downloadindices(db) added = 1 end @info("adding metadata...") added += addmetadata!(db) @info("adding svd data...") added += addsvd!(db) added += insertlocal(db, GeneratedMatrixData{:B}, MATRIXDICT) added += insertlocal(db, GeneratedMatrixData{:U}, USERMATRIXDICT) if added > 0 @info("writing database") writedb(db) end nothing end function _downloadindices(db::MatrixDatabase) @info("reading index files") empty!(db) try readindex(preferred(SSRemoteType), db) readindex(preferred(MMRemoteType), db) finally for data in values(db.data) db.aliases[aliasname(data)] = data.name end end nothing end """ MatrixDepot.update() update database index from the websites """ function update(db::MatrixDatabase=MATRIX_DB) cachedb = abspath(data_dir(), "db.data") isfile(cachedb) && rm(cachedb) uf_matrices = localindex(preferred(SSRemoteType)) isfile(uf_matrices) && rm(uf_matrices) mm_matrices = localindex(preferred(MMRemoteType)) isfile(mm_matrices) && rm(mm_matrices) downloadindices(db, ignoredb=true) end """ loadmatrix(data::RemoteMatrixData) Download the files backing the data from a remote repository. That is currently the TAMU site for the UFl collection and the NIST site for the MatrixMarket collection. The files are uncompressed and un-tar-ed if necessary. The data files containing the matrix data have to be in MatrixMarket format in both cases. Note, that some of the files of the MM collection are not available in MatrixMarket format. An error message results, if tried to load them. """ function loadmatrix(data::RemoteMatrixData) file = matrixfile(data) if isfile(file) addmetadata!(data) return 0 end dir = dirname(localdir(data)) dirt = string(dir, ".tmp") rm(dirt, force=true, recursive=true) mkpath(dirt) url = redirect(dataurl(data)) isdir(dir) || mkpath(dir) wdir = pwd() try @info("downloading: $url") pipe = downloadpipeline(url, dirt) run(pipe) cd(dirt) for file in readdir(dirt) mv(file, joinpath(dir, file), force=true) end catch ex @warn("download of $url failed: $ex") finally cd(wdir) rm(dirt, force=true, recursive=true) end addmetadata!(data) 1 end loadmatrix(data::GeneratedMatrixData) = 0 """ loadinfo(data::RemoteDate) Download the first part of the data file. Stop reading, as soon as the initial comment and the size values of the main matrix have been finished. Store this in a file with extension `.info` in the same directory, where the `.mtx` file is. If the complete file is already available, the download is not performed, because the head of the `.mtx` file contains the same lines. """ function loadinfo(data::RemoteMatrixData) filemtx = matrixfile(data) file = matrixinfofile(data) if isfile(filemtx) || isfile(file) return 0 end url = redirect(dataurl(data)) io = open(downloadpipeline(url)) out = IOBuffer() s = try @info("downloading head of $url") skip = 0 while ( s = readline(io) ) != "" skip = s[1] == '%' || isempty(strip(s)) ? 0 : skip + 1 skip <= 1 && println(out, s) if skip == 1 && length(split(s)) == 3 break end end String(take!(out)) catch ex ex isa InterruptException && rethrow() String(take!(out)) finally close(io) end if !isempty(s) mkpath(dirname(file)) write(file, s) addmetadata!(data) 1 else 0 end end loadinfo(data::MatrixData) = 0 """ downloadpipeline(url, path=nothing) Set up a command pipeline (external processes to download and expand data) If a path name is given, extract tar file into the empty directory or, if not a tar file, write contents to file of that name. """ function downloadpipeline(url::AbstractString, dir::Union{Nothing,AbstractString}=nothing) urls = rsplit(url, '.', limit=3) cmd = Any[ChannelBuffers.curl(url)] if urls[end] == "gz" push!(cmd, gunzip()) resize!(urls, length(urls)-1) url = url[1:end-3] end if dir isa AbstractString if urls[end] == "tar" push!(cmd, tarx(dir)) else file = rsplit(url, '/', limit=2) push!(cmd, joinpath(dir, file[end])) end elseif dir === nothing && urls[end] == "tar" push!(cmd, tarxO()) end pipeline(cmd...) end function downloadcommand(url::AbstractString, filename::AbstractString="-") curl(url) → (filename == "-" ? stdout : filename) end function data_warn(data::RemoteMatrixData, dn, i1, i2) @warn "$(data.name): header $dn = '$i1' file $dn = '$i2' $(data.properties[])" i1 end function extremnnz(data::RemoteMatrixData, m, n, k) if issymmetric(data) || ishermitian(data) || isskew(data) if m != n @warn "$(data.name) needs to be quadratic but is ($mx$n)" end isskew(data) ? (2k, 2k) : (2k - max(m, n), 2k) else (k, k) end end function extremnnz(data::RemoteMatrixData) extremnnz(data, data.m, data.n, data.dnz) end function addmetadata!(db::MatrixDatabase) added = 0 for data in values(db.data) if isunloaded(data) addmetadata!(data) added += isloaded(data) end end added end addmetadata!(::MatrixData) = 0 function addmetadata!(data::RemoteMatrixData) file = matrixfile(data) dir = dirname(file) empty!(data.metadata) isdir(dir) || return 0 base = basename(file) name, ext = rsplit(base, '.', limit=2) filtop(x) = x == base || (startswith(x, string(name, '_')) && !endswith(x, "SVD.mat")) append!(data.metadata, filter(filtop, readdir(dir))) if !isfile(file) file = matrixinfofile(data) end if (finfo = mmreadheader(file)) !== nothing data.properties[] = MMProperties(MATRIX, finfo[:format], finfo[:field], finfo[:symmetry]) m, n, k = finfo[:m], finfo[:n], get(finfo, :nz, 0) n1, n2 = extremnnz(data, m, n, k) hdr = data.header hdr.m = hdr.m in (0, m) ? m : data_warn(data, "m", hdr.m, m) hdr.n = hdr.n in (0, n) ? n : data_warn(data, "n", hdr.n, n) hdr.nnz = hdr.nnz == 0 ? n2 : hdr.nnz <= n2 ? hdr.nnz : data_warn(data, "nnz", hdr.nnz, k) hdr.dnz = k date = get(finfo, :date, 0) hdr.date = hdr.date in (0, date) ? date : data_warn(data, "date", hdr.date, date) kind = get(finfo, :kind, "") if kind != "" if hdr.kind == "" || hdr.kind == "other problem" hdr.kind = kind else if standardkind(kind) != standardkind(hdr.kind) data_warn(data, "kind", hdr.kind, kind) end end end for s in (:title, :author, :ed, :fields, :notes) val = get(finfo, s, "") val != "" && setfield!(hdr, s, val) end end return 1 end standardkind(s::AbstractString) = lowercase(replace(s, '-' => ' ')) function addsvd!(db::MatrixDatabase) added = 0 for data in values(db.data) if data isa RemoteMatrixData && !issvdok(data) added += addsvd!(data) end end added end issvdok(data::RemoteMatrixData) = data.svdok issvdok(::MatrixData) = false """ downloadfile(url, out) Copy file from remote or local url. Works around julia Downloads #69 and #36 """ function downloadfile(url::AbstractString, out::AbstractString) run(downloadcommand(url, out)) nothing end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
4549
##################################################### # Download data from MatrixMarket Collection ##################################################### function readindex(remote::RemoteType, db::MatrixDatabase) file = downloadindex(remote) extract_names(db, file) end function parse_headerinfo(akku::Dict{AbstractString,AbstractString}, count::Integer) toint(id::String) = parse(Int, replace(get(akku, id, "0"), ','=>"")) id = toint("id") id == 0 && (id = count) m = toint("num_rows") n = toint("num_cols") nnz = toint("nonzeros") kind = get(akku, "kind", "") datestr = get(akku, "date", "0") date = match(r"^\d+$", datestr) !== nothing ? parse(Int, datestr) : 0 id, MetaInfo(m, n, nnz, 0, kind, date, "", "", "", "", "") end # extract loading url base and matrix names from index file function extract_names(db::MatrixDatabase, matrices::AbstractString) count = 0 remote = preferred(MMRemoteType) open(matrices) do f akku = Dict{AbstractString,AbstractString}() for line in readlines(f) _, grepex, spquote, ending, parts, regexinf = remote.params.scan m = regexinf === nothing ? nothing : match(regexinf, line) if m !== nothing pname = length(m.captures) == 2 ? m.captures[1] : "id" akku[pname] = m.captures[end] end if occursin(grepex, line) murl = split(line, '"')[spquote] if endswith(murl, ending) list = rsplit(murl[1:end-length(ending)], '/', limit=parts+1)[2:end] count += 1 name = join(list, '/') id, info = parse_headerinfo(akku, count) data = RemoteMatrixData{typeof(remote)}(name, id, info) addmetadata!(data) push!(db, data) count = id end end end end nothing end # read indexfile function downloadindex(remote::RemoteType) file = localindex(remote) url = redirect(indexurl(remote)) if !isfile(file) @info("downloading index file $url") downloadfile(url, file) end file end const NAME_NOT_TRANS = "" # name translations (most of the MM problems are found with similar name in SuiteSparse) function name2ss(mmname::AbstractString) s = split(mmname, '/') length(s) == 2 && return mmname length(s) == 3 || return NAME_NOT_TRANS s1, s2, s3 = s if s2 == "qcd" replace(s3, r"^([^.]*)\.(.)-00l(......)00$" => s"QCD/\1_\2-\3") elseif s2 == "tokamak" string("TOKAMAK/", s3) elseif s2 == "fidap" replace(s3, r"fidap0*([^0]*)" => s"FIDAP/ex\1") elseif s1 == "Harwell-Boeing" string("*/", replace(s3, r"_+" => "_")) elseif s1 == "NEP" if s2 == "crystal" string("*/", replace(s3, r"^(cry)(.*)$" => s"\1g\2")) elseif s3 == "rdb2048l" string("*/", "rdb2048") elseif s3 == "rdb2048" string("*/", "rdb2048_noL") else string("*/", replace(s3, r"^(bfw|mhd|rbs|odep)([\d]{2,3})([a-z])$" => s"\1\3\2")) end else string("*/", s3) end end function name2mm(ssname::AbstractString) s = split(ssname, '/') length(s) == 3 && return ssname length(s) == 2 || return NAME_NOT_TRANS s1, s2 = s if s1 == "QCD" replace(s2, r"^([^_]*)_(.)-(...)-(..)$" => s"misc/qcd/\1.\2-00l\3-\4") * "00" elseif s1 == "TOKAMAK" string("SPARSKIT/tokamak/", s2) elseif s1 == "FIDAP" x = replace(s2, r"^ex([0-9]*)$" => s"\1") x == s2 ? NAME_NOT_TRANS : "SPARSKIT/fidap/fidap$(printfint(parse(Int,x), 3))" elseif s1 == "HB" n = length(s2) N = startswith(s2, "watt_") || startswith(s2, "pores_") ? 7 : 8 y = if n >= N s2 else x = replace(s2, r"^(.*)(_+)(.*[0-9])$" => s"\1/\3") x == s2 ? s2 : replace(x, r"/" => "_" ^ (N + 1 - n)) end "Harwell-Boeing/*/" * y elseif s1 == "Bai" && startswith(s2, "cryg") replace(s2, r"^(cry)g(.*)$" => s"NEP/crystal/\1\2") elseif s1 == "Bai" x = (s2 == "rdb2048" ? "rdb2048l" : s2 == "rdb2048_noL" ? "rdb2048" : s2) x = replace(x, r"^(bfw|mhd|rbs|odep)([a-z])([\d]{2,3})" => s"\1\3\2") string("NEP/*/", x) else string("*/*/", s2) end end printfint(n::Integer, pad::Int) = String(reverse(digits(n, base=UInt8(10), pad=pad)) .+ '0')
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
16246
# # Download index and extra data specific from suite sparse at TAMU # using MAT using DataFrames: DataFrames, DataFrame, select! using Base.Filesystem #const SS_SITE = "https://sparse.tamu.edu" #const SS_FILES = "/files/ssstats.csv" #const SS_INDEX = "/files/ss_index.mat" #const SS_GRAPHICS = "/files/" # to be followed by /$Group/$(Name)$ending # where endings indicate graphics about the main matrix of different kinds # ".png"|"_thumb.png" - sparsity structure # "_graph.gif"|"_graph_thumb.gif" - iconnectivity graph # "_svd.png" - singular values plot const SS_SVDDIR = "/svd/" # to be followed by "$Group/$(Name)_SVD{.mat|_piroband.mat} # the files "$SS_SITE/$Group/$Name" contain html-formatted further information # the directories "/mat" "/MM" "/RB" # contain data files in $Group/$Name.mat or $Group/Name.tar.gz" in different formats # # the SVD-based statistics data are only available on the "further information html file" # They may be derived from the complete list of SVD values from "/SVD" if available # # file "/statistics" contains html with legend of data contained in "ss_index" # see also a copy at the end of this file # const MFIELDNAMES = [:Group, :Name, :nrows, :ncols, :nnz, :nzero, :nnzdiag, :pattern_symmetry, :numerical_symmetry, :isBinary, :isReal, :isND, :isGraph, :posdef, :cholcand, :amd_lnz, :amd_vnz, :amd_rnz,:amd_flops, :nblocks, :ncc, :sprank, :RBtype, :lowerbandwidth, :upperbandwidth, :rcm_lowerbandwidth, :rcm_upperbandwidth, :xmin, :xmax] const MFIELDTYPES = [String, String, Int, Int, Int, Int, Int, Float64, Float64, Bool, Bool, Bool, Bool, Bool, Bool, Int, Int, Int, Int, Int, Int, Int, String, Int, Int, Int, Int, ComplexF64, ComplexF64] const MFIELDNAMES2 =[:nnzdiag, :pattern_symmetry, :numerical_symmetry, :isND, :isGraph, :posdef, :cholcand, :amd_lnz, :amd_vnz, :amd_rnz,:amd_flops, :nblocks, :ncc, :sprank, :lowerbandwidth, :upperbandwidth, :rcm_lowerbandwidth, :rcm_upperbandwidth, :xmin, :xmax] const MFIELDTYPES2 = [Int, Float64, Float64, Bool, Bool, Bool, Bool, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, ComplexF64, ComplexF64] function readindex(remote::SSRemoteType, db::MatrixDatabase) df = read_ss_index() for id in axes(df, 1) mt = copy(df[id,:]) name = mt.name data = get!(db.data, name) do info = MetaInfo(mt.nrows, mt.ncols, mt.nnz, 0, "", 0, "", "", "", "", "") RemoteMatrixData{typeof(remote)}(name, id, info) end for (name, T) in zip(MFIELDNAMES2, MFIELDTYPES2) setproperty!(data.header, name, (getfield(mt, name))) end end end function MetaInfo(a::Int64, b::Int64, c::Int64, d::Int64, e::String, f::Int64, g::String, h::String, i::String, j::String, k::String) MetaInfo(a, b, c, d, e, f, g, h ,i, j, k, 0, 0.0, 0.0, false, false, false, false, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Complex(0.0), Complex(0.0), false, 0.0, 0.0, 0.0, 0, 0, 0.0, "", "", Float64[]) end function load_ss_index() file = localindex(preferred(SSRemoteType)) if !isfile(file) || Base.Filesystem.stat(file).size == 0 url = redirect(indexurl(SS_REMOTE)) @info("downloading: $url") downloadfile(url, file) end file end """ read_ss_index(d::DataFrame) Read file "ss_index.mat" from local data directory and add all fields to `d`. Read file "ssstats.csv" and add field "kinds" to `d`. As a result, all available metadata for all problems in `"SuiteSparseMatrixCollection"` as in the data frame `d`. """ function read_ss_index(d::DataFrame=DataFrame()) file = load_ss_index() m = matopen(file) do io read(io, "ss_index") end for (fn, T) in zip(MFIELDNAMES, MFIELDTYPES) a = m[string(fn)] b = vec([from_matdat(T, s) for s in a]) d[!,fn] = b end d[!,:nnz] += d[!,:nzero] jname(a::String, b::String) = a * '/' * b d[!,:name] = jname.(d[!,:Group],d[!,:Name]) select!(d, DataFrames.Not(:Group)) d end from_matdat(T::Type, s::Any) = T(s) from_matdat(::Type{String}, s::AbstractString) = s """ loadsvd(data::RemoteMatrixData) Download the extra information related to SVD from the backing repository. That is currently the TAMU site for the UFl collection. The files are in MAT format, and are uncompressed and un-tar-ed if necessary. """ function loadsvd(data::RemoteMatrixData{SSRemoteType}) file = svdfile(data) if isfile(file) return 0 end dir = dirname(localdir(data)) url = redirect(datasvdurl(data)) isdir(dir) || mkpath(dir) try @info("downloading: $url") downloadfile(url, file) addsvd!(data) 1 catch rm(file, force=true) write(file, "") 0 end end loadsvd(data::MatrixData) = 0 function addsvd!(data::RemoteMatrixData{SSRemoteType}) file = svdfile(data) if !isempty(file) && Filesystem.stat(file).size > 0 matopen(file) do io d = read(io, "S") pushsvd!(data, d["status"], d["how"], d["s"]) end else 0 end end addsvd!(::MatrixData) = 0 function datasvdurl(data::RemoteMatrixData) string(siteurl(data), '/', "svd", '/', data.name, "_SVD.mat") end function svdfile(data::RemoteMatrixData) abspath(localdir(data), string(basename(data.name), "_SVD.mat")) end function notesfile(data::RemoteMatrixData) abspath(localdir(data), string(basename(data.name), "_notes.txt")) end function pushsvd!(data::RemoteMatrixData, status::AbstractString, how::AbstractString, sv) info = data.header status = lowercase(status) sv = _vector(sv) res = info.svdstatus != status || info.svdhow != how || !isequal(info.sv, sv) info.svdok = status == "ok" info.svdstatus = status info.svdhow = how info.sv = sv st = svdstatistics(info.sv) info.norm = st.maxsv info.minsv = st.minsv info.cond = st.cond info.rank = st.rank info.nullspace = st.nsd info.svgap = st.gap res end _vector(sv::AbstractArray) = vec(sv) _vector(sv::Number) = [sv] datadetailsurl(data::RemoteMatrixData) = string(siteurl(data), '/', data.name) """ svdstatistics(svd::Vector{<:Real}) Return a names tuple containing several values derivable from the svd vector. The vector should be sorted in decreasing order. Return type: `NamedTuple{(:norm, :svdmin, :cond, :rank, :nsd, :gap)} * maxsv: maximal singular value * minsv: minimal singular value * cond: condition number = `maxsv / minsv` * rank: number of singular values > `tol = (length(sv)) * eps(norm)` * nsd: nullspace dimension ? `length(sv) - rank` * gap: relation between smallest `sv > tol` and greatest `sv <= tol` """ function svdstatistics(sv::Vector{T}) where T<:Real mn = length(sv) minsv, maxsv = mn > 0 ? extrema(sv) : (zero(T), zero(T)) norm = maxsv cond = (iszero(minsv) && mn > 0 ? one(T) : maxsv) / minsv tol = mn * eps(norm) rank = count(x -> x > tol, sv) nsd = mn - rank mint = maxsv maxt = zero(T) for s in sv if s > tol && s < mint mint = s elseif s < tol && s > maxt maxt = s end end gap = (iszero(maxt) && mn > 0 ? one(T) : mint) / maxt (maxsv = norm, minsv = minsv, cond = cond, rank = rank, nsd = nsd, gap = gap) end #= Statistics computed for the SuiteSparse Matrix Collection LastRevisionDate This is a single string kept in the UF_index MATLAB struct that states when the collection or the index was last modified. DownloadTimeStamp The date and time the index that you last downloaded the index. Group A cell array. Group{id} is the group name for the matrix whose serial number is 'id'. Each matrix has a unique id number in the range of 1 to the number of matrices in the collection. Once an id is assigned to a matrix, it never changes. Name Name{id} is the name of the matrix (excluding the Group). Name{id} is not unique. The full name of a matrix should always be given as Group/Name. nrows The number of rows in the matrix. ncols The number of columns in the matrix. nnz The number of numerically nonzero entries in the matrix, or nnz(Problem.A) in MATLAB, where Problem=UFget(id) is a struct containing the MATLAB format of the problem. This statistic can differ from the number of 'entries' explicitly stored in the matrix, however, since some of these entries may be numerically zero. In the MATLAB format, these explicit zero entries are stored in the binary Problem.Zeros matrix, since MATLAB drops all explicit zeros from its sparse matrix storage. The Problem.A matrix in MATLAB has nnz entries in it, with no explicit zeros. In the Matrix Market and Rutherford-Boeing format, a single file holds all entries, both nonzero and the explicit zero entries. nzero The number of explicit entries present in the matrix that are provided by the matrix author but which are numerically zero. nzero(id) is nnz(Problem.Zeros). pattern_symmetry Let S=spones(Problem.A) be the binary pattern of the explicit nonzeros in the matrix. Let pmatched be the number of matched offdiagonal entries, where both S(i,j) and S(j,i) are one, with i not equal to j. Let nzoffdiag be the number of offdiagonal entries in S. Then pattern_symmetry is the ratio of pmatched/nzoffdiag. Note that if S(i,j) and S(j,i) are both one, then this pair of entries is counted twice in both pmatched and nzoffdiag. If the matrix is rectangular, this statistic is zero. If there are no offdiagonal entries, the statistic is 1. numerical_symmetry Let xmatched be the number of matched offdiagonal entries, where A(i,j) is equal to the complex conjugate of A(j,i) and where i and j are not equal. Then numerical_symmetry is the ration xmatched / nzoffdiag (or 1 if nzoffdiag is zero). This statistic is zero for rectangular matrices. Note that this statistic measures how close a matrix is to being Hermitian (A=A' in MATLAB). For complex symmetric matrices (A=A.' in MATLAB), this ratio will be less than one (unless all offdiagonal entries are real). isBinary 1 if the matrix is binary (all entries are 0 or 1), 0 otherwise. isReal 1 if the matrix is real, 0 if complex. nnzdiag The number of numerically nonzero entries on the diagonal (nnz (diag (Problem.A)) in MATLAB notation). This statistic ignores explicit zero entries (Problem.Zeros in the MATLAB struct). posdef 1 if the matrix is known to be symmetric positive definite (or Hermitian positive definite for the complex case), 0 if it is known not to be, -1 if it is symmetric (or Hermitian) but with unknown positive-definiteness. If the statistic is unknown (-1) this may be revised in subsequent versions of the index. amd_lnz Let C=S+S' where S=spones(A) is the binary pattern of A. Then amd_lnz is number of nonzeros in the Cholesky factorization of the matrix C(p,p) (assuming C is positive definite) where p=amd(C) is the AMD fill-reducing ordering. This statistic is -2 for rectangular matrices or for graph problems. It is -1 if it is not computed. This figure gives an estimate of the memory requirements for x=A\b in MATLAB for square matrices. amd_flops The floating-point operation count for computing the Cholesky factorization of C(p,p) (see above). amd_vnz The number of entries in a Householder-vector representation of the Q factor of R (but not the QR in MATLAB), after a COLAMD fill-reducing ordering. This is an upper bound on L for the LU factorization of A. amd_rnz The number of entries in R for the QR factorization of A, after a COLAMD fill-reducing ordering. This is an upper bound on U for the LU factorization of A. nblocks The number of blocks from dmperm (see dmperm in MATLAB). sprank The structural rank of the matrix, which is the number of maximual number of nonzero entries that can be permuted to the diagonal (see dmperm, or sprank in MATLAB). This statistic is not computed for problems that represent graphs, since in those cases the diagonal of the matrix is often not relevant (self-edges are often ignored). RBtype The Rutherford Boeing type of the matrix (ignoring explicit zeros in Problem.Zeros). RBtype is a a 3-letter lower-case string. The first letter is: r if A is real but not binary p if A is binary c if A is complex i if A is integer The second letter: r if A is rectangular u if A is square and unsymmetric s if A is symmetric (nnz(A-A.') is zero in MATLAB) h if A is Hermitian (nnz(A-A') is zero in MATLAB) z if A is skew-symmetric (nnz(A+A.') is zero in MATLAB) The third letter is always 'a' (for 'assembled'). The RB format allows for unassembled finite-element matrices, but they are converted to assembled format for this collection. cholcand 1 if the matrix is symmetric (Hermitian if complex) and if all the diagonal entries are positive and real. Zero otherwise. If 1, the matrix is a candidate for a Cholesky factorization, which MATLAB will first try when computing x=A\b. ncc The number of of strongly-connected components in the graph of A (if A is square) or in the bipartite graph if A is rectangular. The diagonal is ignored. isND 1 if the problem comes from a 2D/3D discretization, zero otherwise. This determination is not a property of the matrix, but a qualitative assessment of the kind of problem the matrix represents. isGraph 1 if the problem is best considered as a graph rather than a system of equations, zero otherwise. This determination is not a property of the matrix, but a qualitative assessment of the kind of problem the matrix represents. UFstats.csv A CSV file is also available with some of this index information (UFstats.csv). The first line of the CSV file gives the number of matrices in the collection, and the second line gives the LastRevisionDate. Line k+2 in the file lists the following statistics for the matrix whose id number is k: Group, Name, nrows, ncols, nnz, isReal, isBinary, isND, posdef, pattern_symmetry, numerical_symmetry, and kind. SVD-based statistics The following statistics are not (yet) in the UFindex. They are currently available only on the web page for each matrix. You can also download the singular values at www.cise.ufl.edu/research/sparse/svd. These were typically calculated with s=svd(full(A)) in MATLAB, are are thus only available for modest-sized matrices. norm(A) The 2-norm of A (the largest singular value) min(svd(A)) The smallest singular value cond(A) The 2-norm condition number, which is the ratio of the largest over the smallest singular value. rank(A) The rank of the matrix, which is the number of singular values larger than the tolerance of max(m,n)*eps(norm(A)). This tolerance is plotted in green in the figure. sprank(A)-rank(A) sprank(A) (see above) is an upper bound on the rank of A. null space dimension The dimension of the null space (zero if it has full numerical rank). This is simply min(m,n)-rank(A). full numerical rank? 'yes' or 'no'. singular value gap If k=rank(A), and the matrix is rank deficient, then this is the ratio s(k)/s(k+1). A red line between the kth and (k+1)st singular value is drawn to illustrate this gap. singular values These can be downloaded as a MATLAB MAT-file. Each file contains a struct with the fields: s (a vector containing the singular values), how (a string stating how the SVD was computed), and status (a string that is either 'ok' or a warning). If the status shows that the SVD did not converge, the singular values are probably not computed accurately. =#
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
4967
# adjacency matrices # # The code is adapted from CONTEST(Controllable TEST matrices) # by Alan Taylor and Professor Des Higham # http://www.mathstat.strath.ac.uk/outreach/contest/ """ Erdos-Renyi Random Graph ====================== Generate an adjacency matrix of an Edros-Renyi random graph: an undirected graph is chosen uniformly at random from the set of all symmetric graphs with `n` nodes and `m` edges. *Input options:* + [type,] n, m: the dimension of the matrix is `n`. The number of 1's in the matrix is `2*m`. + [type,] n: m = ceil(Int, n*log(n)/2). *Groups:* ["sparse", "graph"] *References:* **P. Erdos and A. Renyi**, On Random Graphs, Publ. Math. Debrecen, 6, 1959, pp. 290-297 """ function erdrey(::Type{T}, n::Integer, m::Integer) where T nzeros = ceil.(Int, 0.5*n*(n-1)*rand(m)) v = zeros(Int, n) for count in 1:n v[count] = count*(count -one(Int))/2 end is = zeros(Int, m) js = zeros(Int, m) for count in 1:m i = minimum(findall(x -> x >=nzeros[count], v)) j = nzeros[count] - (i-1)*(i-2)/2 is[count] = i js[count] = j end A = sign.(sparse([is;js], [js;is], ones(T, m*2), n, n)) while nnz(A) != 2*m diff = round(Int, m - nnz(A)/2) is_new = zeros(Int, diff) js_new = zeros(Int, diff) for count = 1:diff idx = ceil(Int, 0.5*n*(n-1)*rand()) is_new[count] = minimum(findall(x -> x >= idx, v)) js_new[count] = idx - (is_new[count] - 1)*(is_new[count] - 2)/2 end append!(is, is_new) append!(js, js_new) s = ones(T, length(is)) A = sign.(sparse([is;js], [js;is], [s;s], n,n)) end A end erdrey(::Type{T}, n::Integer) where T = erdrey(T, n, ceil(Int, n*log(n)/2)) erdrey(n::Integer, arg...) = erdrey(Float64, n, arg...) """ Gilbert Random Graph ================== Generate an adjecency matrix of a Gilbert random graph: an undirected graph with pairs of nodes are connected with independent probability `p`. *Input options:* + [type,] n, p: the dimension of the matrix is `n` and the probability that any two nodes are connected is `p`. + [type,] n: p = log(n)/n. *Groups:* ["sparse", "graph"] *References:* **E.N. Gilbert**, Random Graphs, Ann. Math. Statist., 30, (1959) pp. 1141-1144. """ function gilbert(::Type{T}, n::Integer, p::AbstractFloat) where T v = zeros(Int, n) for k = 1:n v[k] = round(Int, k*(k-1)/2) end is = zeros(Int, 0) js = zeros(Int, 0) w = zero(Int) w += one(Int) + floor(Int, log(1 - rand()) / log(1 - p)) while w < n*(n-1)/2 i = minimum(findall(x -> x >= w, v)) j = w - round(Int, (i -1)*(i - 2)/2) push!(is, i) push!(js, j) w += one(Int) + floor(Int, log(1 - rand()) / log(1-p)) end s = ones(T, length(is)) return sparse([is;js], [js;is], [s;s], n, n) end function gilbert(::Type{T}, n::Integer) where T if n == 1 return gilbert(T, n, 0.2) else return gilbert(T, n, log(n)/n) end end gilbert(n::Integer, arg...) = gilbert(Float64, n, arg...) # utility function # shortcuts: randomly add entries (shortcuts) to a matrix. function shortcuts(A::SparseMatrixCSC{T}, p::Real) where T n, = size(A) Ihat = findall(x -> x <= p, rand(n)) Jhat = ceil.(Int, n*rand(Float64, size(Ihat))) Ehat = ones(T, size(Ihat)) # an edge for (i, ele) in enumerate(Ihat) if ele == Jhat[i] Ehat[i] = zero(T) end end is, js, es = findnz(A) return sparse([is; Ihat; Jhat], [js; Jhat; Ihat], [es; Ehat; Ehat], n, n) end """ Small World Network ================= Generate an adjacency matrix for a small world network. We model it by adding shortcuts to a kth nearest neighbour ring network (nodes i and j are connected iff |i -j| <= k or |n - |i -j|| <= k.) with n nodes. *Input options:* + [type,] n, k, p: the dimension of the matrix is `n`. The number of nearest-neighbours to connect is `k`. The probability of adding a shortcut in a given row is `p`. + [type,] n: `k = 2` and `p = 0.1`. *References:* **D. J. Watts and S. H. Strogatz**, Collective Dynamics of Small World Networks, Nature 393 (1998), pp. 440-442. """ function smallworld(::Type{T}, n::Integer, k::Integer, p::Real) where T twok = 2*k is = zeros(Int, 2*k*n) js = zeros(Int, 2*k*n) es = zeros(T, 2*k*n) for count = 1:n is[(count-1)*twok+1 : count*twok] = count*ones(Int, twok) js[(count-1)*twok+1 : count*twok] = mod.([count : count+k-1; n-k+count-1 : n+count-2], n) .+ 1 es[(count-1)*twok+1 : count*twok] = ones(T, twok) end A = sparse(is, js, es, n, n) return sign.(shortcuts(A, p)) end smallworld(::Type{T}, n::Integer) where T = smallworld(T, n, 2, 0.1) smallworld(n::Integer, arg...) = smallworld(Float64, n, arg...) function geo(n::Integer) end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
45766
# Higham Test Matrices """ Hilbert Matrix ============== The Hilbert matrix has `(i,j)` element `1/(i+j-1)`. It is notorious for being ill conditioned. It is symmetric positive definite and totally positive. *Input options:* + [type,] dim: the dimension of the matrix. + [type,] row_dim, col_dim: the row and column dimensions. *Groups:* ["inverse", "illcond", "symmetric", "posdef"] *References:* **M. D. Choi**, Tricks or treats with the Hilbert matrix, Amer. Math. Monthly, 90 (1983), pp. 301-312. **N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.1. """ function hilb(::Type{T}, m::Integer, n::Integer) where T # compute the Hilbert matrix H = zeros(T, m, n) for j = 1:n, i= 1:m @inbounds H[i,j] = one(T)/ (i + j - one(T)) end return H end hilb(::Type{T}, n::Integer) where T = hilb(T, n, n) hilb(args...) = hilb(Float64, args...) hilb(::Type, args...) = throw(MethodError(hilb, Tuple(args))) """ Inverse of the Hilbert Matrix ============================= *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "illcond", "symmetric","posdef"] *References:* **M. D. Choi**, Tricks or treats with the Hilbert matrix, Amer. Math. Monthly, 90 (1983), pp. 301-312. **N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.1. """ function invhilb(::Type{T}, n::Integer) where T # compute the inverse of Hilbert matrix # Type: data type # n: the dimension of the matrix Inv = zeros(T, n, n) for i = 1:n, j = 1:n Inv[i,j] = (-1)^(i+j)*(i+j-1)*binomial(n+i-1, n-j)* binomial(n+j-1,n-i)*binomial(i+j-2,i-1)^2 end return Inv end invhilb(n::Integer) = invhilb(Float64, n) """ Hadamard Matrix =============== The Hadamard matrix is a square matrix whose entries are 1 or -1. It was named after Jacques Hadamard. The rows of a Hadamard matrix are orthogonal. *Input options:* + [type,] dim: the dimension of the matrix, `dim` is a power of 2. *Groups:* ["inverse", "orthogonal", "eigen"] *References:* **S. W. Golomb and L. D. Baumert**, The search for Hadamard matrices, Amer. Math. Monthly, 70 (1963) pp. 12-17 """ function hadamard(::Type{T}, n::Integer) where T #Compute the hadamard matrix if n < 1 lgn = 0 else lgn = round(Integer, log2(n)) end 2^lgn != n && throw(ArgumentError("n must be positive integer and a power of 2.")) H = reshape(T[1], 1, 1) for i = 1:lgn H = [[H H]; [H -H]] end return H end hadamard(n::Integer) = hadamard(Float64, n) """ Cauchy Matrix ============= Given two vectors `x` and `y`, the `(i,j)` entry of the Cauchy matrix is `1/(x[i]+y[j])`. *Input options*: + [type,] x, y: two vectors. + [type,] x: a vector. `y` defaults to `x`. + [type,] dim: the dimension of the matrix. `x` and `y` default to `[1:dim;]`. *Groups:* ["inverse", "illcond", "symmetric", "posdef"] *References:* **N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.1 """ function cauchy(::Type{T}, x::Vector, y::Vector) where T # Compute the cauchy matrix m = size(x,1) n = size(y,1) C = zeros(T, m, n) [C[i,j]= one(T)/(x[i] + y[j]) for i = 1:m, j = 1:n] return C end cauchy(::Type{T}, x::Vector) where T = cauchy(T, x, x) cauchy(::Type{T}, k::Integer) where T = cauchy(T, [1:k;]) cauchy(arg...) = cauchy(Float64, arg...) cauchy(::Type, args...) = throw(MethodError(cauchy, Tuple(args))) """ Circulant Matrix ================ A circulant matrix has the property that each row is obtained by cyclically permuting the entries of the previous row one step forward. *Input options:* + [type,] vec, col_dim: a vector and the column dimension. + [type,] vec: a vector. + [type,] dim: the dimension of the matrix. *Groups:* ["symmetric", "posdef", "eigen"] *References:* **P. J. Davis**, Circulant Matrices, John Wiley, 1977. """ function circul(::Type{T}, v::Vector, w::Vector) where T # Compute the circul matrix # v: the first row of the matrix # w: the length of the vector is the dimension of the column m = length(v) n = length(w) C = zeros(T, m, n) [C[i,j] = v[1 + mod(j - i, n)] for i = 1:m, j = 1:n] return C end circul(::Type{T}, v::Vector, n::Integer) where T = circul(T, v, T[1:n;]) circul(::Type{T}, v::Vector) where T = circul(T, v, v) circul(::Type{T}, k::Integer) where T = circul(T, [1:k;]) circul(arg...) = circul(Float64, arg...) """ Dingdong Matrix =============== The Dingdong matrix is a symmetric Hankel matrix invented by DR. F. N. Ris of IBM, Thomas J Watson Research Centre. The eigenvalues cluster around `π/2` and `-π/2`. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["symmetric", "eigen"] *References:* **J. C. Nash**, Compact Numerical Methods for Computers: Linear Algebra and Function Minimisation, second edition, Adam Hilger, Bristol, 1990 (Appendix 1). """ function dingdong(::Type{T}, n::Integer) where T # Compute the dingdong matrix # type: data type # n: the dimension of the matrix D = zeros(T, n, n) [D[i,j] = one(T)/(2*(n-i-j+1.5)) for i = 1:n, j= 1:n] return D end dingdong(args...) = dingdong(Float64, args...) dingdong(::Type, args...) = throw(MethodError(dingdong, Tuple(args))) """ Frank Matrix ============ The Frank matrix is an upper Hessenberg matrix with determinant 1. The eigenvalues are real, positive and very ill conditioned. *Input options:* + [type,] dim, k: `dim` is the dimension of the matrix, `k = 0 or 1`. If `k = 1` the matrix reflect about the anti-diagonal. + [type,] dim: the dimension of the matrix. *Groups:* ["illcond", "eigen"] *References:* **W. L. Frank**, Computing eigenvalues of complex matrices by determinant evaluation and by methods of Danilewski and Wielandt, J. Soc. Indust. Appl. Math., 6 (1958), pp. 378-392 (see pp. 385, 388). """ function frank(::Type{T}, n::Integer, k::Integer) where T # Compute the frank matrix # type: data type # n: the dimension of the matrix # k = 0 or 1: k = 1 reflect about the anti-diagonal p = T[n:-1:1;]; F = triu(ones(T, n, 1)*p') + diagm(-1 => p[2:n]); k == 0 ? F : k == 1 ? F[n:-1:1,n:-1:1]' : error("k = 0 or 1, but get ", k) end frank(::Type{T}, n::Integer) where T = frank(T, n, 0) frank(args...) = frank(Float64, args...) frank(::Type, args...) = throw(MethodError(frank, Tuple(args))) # # Jordan block # function jordbloc( n::Integer, lambda::T) where T # Generate a n-by-n jordan block with eigenvalue # lambda J = lambda*Matrix{T}(I, n, n) + diagm(1 => ones(T, n-1, 1)[:,1]) return J end """ Forsythe Matrix =============== The Forsythe matrix is a n-by-n perturbed Jordan block. This generator is adapted from N. J. Higham's Test Matrix Toolbox. *Input options:* + [type,] dim, alpha, lambda: `dim` is the dimension of the matrix. `alpha` and `lambda` are scalars. + [type,] dim: `alpha = sqrt(eps(type))` and `lambda = 0`. *Groups:* ["inverse", "illcond", "eigen"] """ function forsythe(::Type{T}, n::Integer , alpha, lambda) where T # Generate the forsythe matrix alpha = convert(T, alpha) lambda = convert(T, lambda) F = jordbloc(n, lambda); F[n,1] = alpha; return F end forsythe(::Type{T}, n::Integer) where T = forsythe(T, n, sqrt(eps(T)), zero(T)) forsythe(args...) = forsythe(Float64, args...) forsythe(::Type, args...) = throw(MethodError(forsythe, Tuple(args))) function oddmagic(::Type{T}, n::Integer) where T # compute the magic square of odd orders A = zeros(T, n, n) i = 1 j = div(n+1, 2) for k = 1:n^2 is = i js = j A[i,j] = k i = n - rem(n+1-i,n) j = rem(j,n) + 1 if A[i,j] != 0 i = rem(is,n) + 1 j = js end end return A end """ Magic Square Matrix =================== The magic matrix is a matrix with integer entries such that the row elements, column elements, diagonal elements and anti-diagonal elements all add up to the same number. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["inverse"] """ function magic(::Type{T}, n::Integer) where T # Compute a magic square of order n # Learnt from Cleve Moler, Experiments with MATLAB, 2011 if mod(n, 2) == 1 # n is odd M = oddmagic(T, n) elseif mod(n, 4) == 0 # n is doubly even a = floor.(Integer, mod.([1:n;], 4)/2) B = broadcast(==, a', a) M = broadcast(+, T[1:n:n^2;]',T[0:n-1;]) for i = 1:n, j = 1:n B[i,j] == 1 ? M[i,j] = n^2 + one(T) - M[i,j] : M[i,j] end else # n is singly even p = div(n,2) M = oddmagic(T, p) M = [M M.+2*p^2; M.+3*p^2 M.+p^2] if n == 2 return M end i = [1:p;] k = div(n-2, 4) j = [[1:k;]; [(n-k+2) : n;]] M[[i;i.+p],j] = M[[i.+p;i],j] i = k+1 j = [1, i] M[[i;i+p],j] = M[[i+p;i],j] end return M end magic(n::Integer) = magic(Float64, n) """ Grcar Matrix ============ The Grcar matrix is a Toeplitz matrix with sensitive eigenvalues. *Input options:* + [type,] dim, k: `dim` is the dimension of the matrix and `k` is the number of superdiagonals. + [type,] dim: the dimension of the matrix. *Groups:* ["eigen"] *References:* **J. F. Grcar**, Operator coefficient methods for linear equations, Report SAND89-8691, Sandia National Laboratories, Albuquerque, New Mexico, 1989 (Appendix 2). """ function grcar(::Type{T}, n::Integer, k::Integer = 3) where T # Compute grcar matrix G = tril(triu(ones(T, n,n)), min(k, n-1)) - diagm(-1 => ones(T, n-1)) return G end grcar(args...) = grcar(Float64, args...) grcar(::Type, args...) = throw(MethodError(grcar, Tuple(args))) """ Triw Matrix =========== Upper triangular matrices discussed by Wilkinson and others. *Input options:* + [type,] row_dim, col_dim, α, k: `row_dim` and `col_dim` are row and column dimension of the matrix. `α` is a scalar representing the entries on the superdiagonals. `k` is the number of superdiagonals. + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "illcond"] *References:* **G. H. Golub and J. H. Wilkinson**, Ill-conditioned eigensystems and the computation of the Jordan canonical form, SIAM Review, 18(4), 1976, pp. 578-6 """ function triw(::Type{T}, m::Integer, n::Integer, alpha, k::Integer) where T alpha = convert(T, alpha) A = tril(Matrix{T}(I, m, n) + alpha * triu(ones(T, m,n), 1), min(k, n-1)) return A end triw(::Type{T}, n::Integer) where T = triw(T, n, n, -1, n-1) triw(args...) = triw(Float64, args...) triw(::Type, args...) = throw(MethodError(triw, Tuple(args))) """ Moler Matrix ============ The Moler matrix is a symmetric positive definite matrix. It has one small eigenvalue. *Input options:* + [type,] dim, alpha: `dim` is the dimension of the matrix, `alpha` is a scalar. + [type,] dim: `alpha = -1`. *Groups:* ["inverse", "illcond", "symmetric", "posdef"] *References:* **J.C. Nash**, Compact Numerical Methods for Computers: Linear Algebra and Function Minimisation, second edition, Adam Hilger, Bristol, 1990 (Appendix 1). """ function moler(::Type{T}, n::Integer, alpha = -1.) where T alpha = convert(T, alpha) M = triw(T, n, n, alpha, n - 1)' * triw(T, n, n, alpha, n -1 ) return M end moler(args...) = moler(Float64, args...) moler(::Type, args...) = throw(MethodError(moler, Tuple(args))) """ Pascal Matrix ============= The Pascal matrix’s anti-diagonals form the Pascal’s triangle. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "illcond", "symmetric", "posdef", "eigen"] *References:* **R. Brawer and M. Pirovino**, The linear algebra of the Pascal matrix, Linear Algebra and Appl., 174 (1992), pp. 13-23 (this paper gives a factorization of L = PASCAL(N,1) and a formula for the elements of L^k). **N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.4. """ function pascal(::Type{T}, n::Integer) where T P = zeros(T, n,n) for j = 1:n for i = 1:n try P[i,j] = binomial(i+j-2, j-1) catch P[i,j] = binomial(BigInt(i+j-2), j-1) end end end return P end pascal(n::Integer) = pascal(Float64, n) """ Kahan Matrix ============ The Kahan matrix is an upper trapezoidal matrix, i.e., the `(i,j)` element is equal to `0` if `i > j`. The useful range of `θ` is `0 < θ < π`. The diagonal is perturbed by `pert*eps()*diagm([n:-1:1;])`. *Input options:* + [type,] rowdim, coldim, θ, pert: `rowdim` and `coldim` are the row and column dimensions of the matrix. `θ` and `pert` are scalars. + [type,] dim, θ, pert: `dim` is the dimension of the matrix. + [type,] dim: `θ = 1.2`, `pert = 25`. *Groups:* ["inverse", "illcond"] *References:* **W. Kahan**, Numerical linear algebra, Canadian Math. Bulletin, 9 (1966), pp. 757-801. """ function kahan(::Type{T}, m::Integer, n::Integer, theta, pert) where T theta = convert(T, theta) pert = convert(T, pert) s = sin(theta) c = cos(theta) dim = min(m,n) A = zeros(T, m, n) for i = 1:m, j = 1:n i > dim ? A[i,j] = zero(T) : i > j ? A[i,j] = zero(T) : i==j ? A[i,j] = s^(i-1)+pert*eps(T)*(m-i+1) : A[i,j] = -c*s^(i-1) end return A end kahan(::Type{T}, n::Integer, theta, pert) where T = kahan(T, n, n, theta, pert) kahan(::Type{T}, n::Integer) where T = kahan(T, n, n, 1.2, 25.) kahan(args...) = kahan(Float64, args...) kahan(::Type, args...) = throw(MethodError(kahan, Tuple(args))) """ Pei Matrix ========== The Pei matrix is a symmetric matrix with known inversion. *Input options:* + [type,] dim, α: `dim` is the dimension of the matrix. `α` is a scalar. + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "illcond", "symmetric", "posdef"] *References:* **M. L. Pei**, A test matrix for inversion procedures, Comm. ACM, 5 (1962), p. 508. """ function pei(::Type{T}, n::Integer, alpha = 1) where T alpha = convert(T, alpha) return alpha*Matrix{T}(I, n, n) + ones(T, n, n) end pei(args...) = pei(Float64, args...) pei(::Type, args...) = throw(MethodError(pei, Tuple(args))) """ Vandermonde Matrix ================== The inverse and determinat are known explicitly. *Input options:* + [type,] vec, col_dim: `vec` is a vector, `col_dim` is the number of columns. + [type,] vec: `col_dim = length(vec)` + [type,] dim: `vec = [1:dim;]` *Groups:* ["inverse", "illcond"] *References:* **N. J. Higham**, Stability analysis of algorithms for solving confluent Vandermonde-like systems, SIAM J. Matrix Anal. Appl., 11 (1990), pp. 23-41. """ function vand(::Type{T}, p::Vector, n::Integer) where T # n: number of rows # p: a vector m = length(p) V = Array{T,2}(undef, m, n) for j = 1:m @inbounds V[j, 1] = 1 end for i = 2:n for j = 1:m @inbounds V[j,i] = p[j] * V[j,i-1] end end return V end vand(::Type{T}, n::Integer) where T = vand(T, [1:n;], n) vand(::Type{T}, p::Vector) where T = vand(T, p, length(p)) vand(args...) = vand(Float64, args...) vand(::Type, args...) = throw(MethodError(vand, Tuple(args))) """ Involutory Matrix ================= An involutory matrix is a matrix that is its own inverse. *Input options:* + [type,] dim: `dim` is the dimension of the matrix. *Groups:* ["inverse", "illcond", "eigen"] *References:* **A. S. Householder and J. A. Carpenter**, The singular values of involutory and of idempotent matrices, Numer. Math. 5 (1963), pp. 234-237. """ function invol(::Type{T}, n::Integer) where T A = hilb(T, n) d = -n A[:,1] = d*A[:, 1] for i = 1:n-1 d = -(n+i)*(n-i)*d/(i*i) A[i+1,:] = d*A[i+1,:] end return A end invol(n::Integer) = invol(Float64, n) """ Chebyshev Spectral Differentiation Matrix ========================================= If `k = 0`,the generated matrix is nilpotent and a vector with all one entries is a null vector. If `k = 1`, the generated matrix is nonsingular and well-conditioned. Its eigenvalues have negative real parts. *Input options:* + [type,] dim, k: `dim` is the dimension of the matrix and `k = 0 or 1`. + [type,] dim: `k=0`. *Groups:* ["eigen"] *References:* **L. N. Trefethen and M. R. Trummer**, An instability phenomenon in spectral methods, SIAM J. Numer. Anal., 24 (1987), pp. 1008-1023. """ function chebspec(::Type{T}, n::Integer, k::Integer = 0) where T # k = 0 or 1 if k == 1 n = n + 1 end c = ones(T, n) c[1] = 2 c[2:n-1] .= 1 c[n] = 2 x = ones(T, n) A = zeros(T, n, n) # Compute the chebyshev points for i = 1:n x[i] = cos(pi * (i - 1) / (n - 1)) end for j = 1:n, i = 1:n i != j ? A[i,j] = (-1)^(i+j) * c[i] / (c[j] * (x[i] - x[j])) : i == 1 ? A[i,i] = (2 * (n -1)^2 + 1) / 6 : i == n ? A[i,i] = - (2 * (n-1)^2 + 1) / 6 : A[i,i] = - 0.5 * x[i] / (1 - x[i]^2) end if k == 1 A = A[2:n, 2:n] end return A end chebspec(args...) = chebspec(Float64, args...) chebspec(::Type, args...) = throw(MethodError(chebspec, Tuple(args))) """ Lotkin Matrix ============= The Lotkin matrix is the Hilbert matrix with its first row altered to all ones. It is unsymmetric, illcond and has many negative eigenvalues of small magnitude. *Input options:* + [type,] dim: `dim` is the dimension of the matrix. *Groups:* ["inverse", "illcond", "eigen"] *References:* **M. Lotkin**, A set of test matrices, MTAC, 9 (1955), pp. 153-161. """ function lotkin(::Type{T}, n::Integer) where T A = hilb(T, n) A[1,:] = ones(T,n)' return A end lotkin(n::Integer) = lotkin(Float64, n) """ Clement Matrix ============== The Clement matrix is a tridiagonal matrix with zero diagonal entries. If k = 1, the matrix is symmetric. *Input options:* + [type,] dim, k: `dim` is the dimension of the matrix. If `k = 0`, the matrix is of type `Tridiagonal`. If `k = 1`, the matrix is of type `SymTridiagonal`. + [type,] dim: `k = 0`. *Groups:* ["inverse", "symmetric", "eigen"] *References:* **P. A. Clement**, A class of triple-diagonal matrices for test purposes, SIAM Review, 1 (1959), pp. 50-52. """ function clement(::Type{T}, n::Integer, k::Integer = 0) where T # construct Tridiagonal matrix # n is the dimension of the matrix # k = 0 or 1 if n == 1 # handle the 1-d case. return zeros(T, 1, 1) end n = n -1 x = T[n:-1:1;] z = T[1:n;] if k == 0 A = Tridiagonal(x,zeros(T,n+1),z) else y = sqrt.(x.*z) A = SymTridiagonal(zeros(T,n+1), y) end return A end clement(args...) = clement(Float64, args...) clement(::Type, args...) = throw(MethodError(clement, Tuple(args))) """ Fiedler Matrix ============== The Fiedler matrix is symmetric matrix with a dominant positive eigenvalue and all the other eigenvalues are negative. *Input options:* + [type,] vec: a vector. + [type,] dim: `dim` is the dimension of the matrix. `vec=[1:dim;]`. *Groups: *["inverse", "symmetric", "eigen"] *References:* **G. Szego**, Solution to problem 3705, Amer. Math. Monthly, 43 (1936), pp. 246-259. **J. Todd**, Basic Numerical Mathematics, Vol. 2: Numerical Algebra, Birkhauser, Basel, and Academic Press, New York, 1977, p. 159. """ function fiedler(::Type{T}, v::Vector) where T n = length(v) v = transpose(v[:]) A = ones(T, n) * v A = abs.(A - transpose(A)) # nonconjugate transpose end fiedler(::Type{T}, n::Integer) where T = fiedler(T, [1:n;]) fiedler(args...) = fiedler(Float64, args...) fiedler(::Type, args...) = throw(MethodError(fiedler, Tuple(args))) """ MIN[I,J] Matrix =============== A matrix with `(i,j)` entry `min(i,j)`. It is a symmetric positive definite matrix. The eigenvalues and eigenvectors are known explicitly. Its inverse is tridiagonal. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "symmetric", "posdef", "eigen"] *References:* **J. Fortiana and C. M. Cuadras**, A family of matrices, the discretized Brownian bridge, and distance-based regression, Linear Algebra Appl., 264 (1997), 173-188. (For the eigensystem of A.) """ function minij(::Type{T}, n::Integer) where T A = zeros(T, n, n) [A[i,j] = min(i,j) for i = 1:n, j = 1:n] return A end minij(n::Integer) = minij(Float64, n) """ Binomial Matrix =============== The matrix is a multiple of an involutory matrix. *Input options:* + [type,] dim: the dimension of the matrix. """ function binomialm(::Type{T}, n::Integer) where T # Mulitiple of involutory matrix L = Array{T,2}(undef, n, n) D = Diagonal((-2).^[0:n-1;]) [L[i,j] = binomial(i-1, j-1) for i = 1:n, j = 1:n] U = L[n:-1:1, n:-1:1] return L*D*U end binomialm(n::Integer) = binomialm(Float64, n) """ Tridiagonal Matrix ================== Construct a tridigonal matrix of type `Tridiagonal`. *Input options:* + [type,] v1, v2, v3: `v1` and `v3` are vectors of subdiagonal and superdiagonal elements, respectively, and `v2` is a vector of diagonal elements. + [type,] dim, x, y, z: `dim` is the dimension of the matrix, `x`, `y`, `z` are scalars. `x` and `z` are the subdiagonal and superdiagonal elements, respectively, and `y` is the diagonal elements. + [type,] dim: `x = -1, y = 2, z = -1`. This matrix is also known as the second difference matrix. *Groups:* ["inverse", "illcond", "posdef", "eigen"] *References:* **J. Todd**, Basic Numerical Mathematics, Vol. 2: Numerical Algebra, Birkhauser, Basel, and Academic Press, New York, 1977, p. 155. """ function tridiag(::Type{T}, x::AbstractVector, y::AbstractVector, z::AbstractVector) where T x = map((i)-> convert(T, i), x) y = map((i)-> convert(T, i), y) z = map((i)-> convert(T, i), z) return Tridiagonal(x,y,z) end # Toeplitz tridiagonal matrix tridiag(::Type{T}, n::Integer, x::Integer, y::Integer, z::Integer) where T = n == 1 ? y*ones(T,1,1) : tridiag(T, x*ones(T, n-1), y*ones(T, n), z*ones(T, n-1)) tridiag(::Type{T}, n::Integer) where T = tridiag(T, n, -1, 2, -1) tridiag(args...) = tridiag(Float64, args...) tridiag(::Type, args...) = throw(MethodError(tridiag, Tuple(args))) """ Lehmer Matrix ============= The Lehmer matrix is a symmetric positive definite matrix. It is totally nonnegative. The inverse is tridiagonal and explicitly known *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["inverse", "symmetric", "posdef"] *References:* **M. Newman and J. Todd**, The evaluation of matrix inversion programs, J. Soc. Indust. Appl. Math., 6 (1958), pp. 466-476. Solutions to problem E710 (proposed by D.H. Lehmer): The inverse of a matrix, Amer. Math. Monthly, 53 (1946), pp. 534-535. """ function lehmer(::Type{T}, n::Integer) where T A = Array{T,2}(undef, n, n) [A[i,j] = min(i,j) / max(i,j) for i = 1:n, j = 1:n] return A end lehmer(n::Integer) = lehmer(Float64, n) #= function lehmer(::Type{T}, n::Integer) where T A = Array{T,2}(n, n) [A[i,j] = min(i,j) / max(i,j) for i = 1:n, j = 1:n] return A end lehmer(n::Integer) = lehmer(Float64, n) =# """ Parter Matrix ============= The Parter matrix is a Toeplitz and Cauchy matrix with singular values near `π`. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["eigen"] *References:* The MathWorks Newsletter, Volume 1, Issue 1, March 1986, page 2. S. V. Parter, On the distribution of the singular values of Toeplitz matrices, Linear Algebra and Appl., 80 (1986), pp. 115-130. """ function parter(::Type{T}, n::Integer) where T A = Array{T,2}(undef, n, n) [A[i,j] = one(T) / (i - j + 0.5) for i = 1:n, j = 1:n] return A end parter(n::Integer) = parter(Float64, n) """ Chow Matrix =========== The Chow matrix is a singular Toeplitz lower Hessenberg matrix. *Input options:* + [type,] dim, alpha, delta: `dim` is dimension of the matrix. `alpha`, `delta` are scalars such that `A[i,i] = alpha + delta` and `A[i,j] = alpha^(i + 1 -j)` for `j + 1 <= i`. + [type,] dim: `alpha = 1`, `delta = 0`. *Groups:* ["eigen"] *References:* **T. S. Chow**, A class of Hessenberg matrices with known eigenvalues and inverses, SIAM Review, 11 (1969), pp. 391-395. """ function chow(::Type{T}, n::Integer, alpha, delta) where T A = zeros(T, n, n) alpha = convert(T, alpha) delta = convert(T, delta) for i = 1:n, j = 1:n if i == j - 1 A[i,j] = one(T) elseif i == j A[i,j] = alpha + delta elseif j + 1 <= i A[i,j] = alpha^(i + 1 - j) end end return A end chow(::Type{T}, n::Integer) where T = chow(T, n, 1, 0) chow(args...) = chow(Float64, args...) chow(::Type, args...) = throw(MethodError(chow, Tuple(args))) # # newsign: newsign(0) = 1 # function newsign(x) x == 0 ? y = 1 : y = sign(x) return y end """ Random Correlation Matrix ========================= A random correlation matrix is a symmetric positive semidefinite matrix with 1s on the diagonal. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["symmetric", 'pos-semidef', "random"] """ function randcorr(::Type{T}, n::Integer) where T x = rand(T,n) # x is the vector of random eigenvalues from a uniform distribution. x = n * x / sum(x) # x has nonnegtive elements. A = diagm(0 => x) F = qr(randn(n,n)); Q = F.Q*diagm(0 => sign.(diag(F.R))) # form a random orthogonal matrix. copyto!(A, Q*A*Q') a = diag(A) l = findall(a .< 1) g = findall(a .> 1) # Apply Given rotation to set A[i,i] = 1 while length(l) > 0 && length(g) > 0 k = ceil(Integer, rand()*length(l)) h = ceil(Integer, rand()*length(g)) i = l[k] j = g[h] if i > j i,j = j,i end alpha = sqrt(A[i,j]^2 - (a[i] - 1)*(a[j] - 1)) # take sign to avoid cancellation. t = (A[i,j] + newsign(A[i,j]) * alpha) / (a[j] - 1) c = 1/ sqrt(1 + t^2) s = t*c A[:, [i,j]] = A[:, [i,j]] * [c s; -s c] A[[i,j], :] = [c -s; s c] * A[[i,j], :] A[i,i] = 1 a = diag(A) l = findall(a.<1) g = findall(a.>1) end [A[i,i] = 1 for i = 1:n] return (A + A')/2 end randcorr(args...) = randcorr(Float64, args...) randcorr(::Type, args...) = throw(MethodError(randcorr, Tuple(args))) """ Poisson Matrix ============== A block tridiagonal matrix from Poisson’s equation. This matrix is sparse, symmetric positive definite and has known eigenvalues. The result is of type `SparseMatrixCSC`. *Input options:* + [type,] dim: the dimension of the matrix is `dim^2`. *Groups:* ["inverse", "symmetric", "posdef", "eigen", "sparse"] *References:* **G. H. Golub and C. F. Van Loan**, Matrix Computations, second edition, Johns Hopkins University Press, Baltimore, Maryland, 1989 (Section 4.5.4). """ function poisson(::Type{T}, n::Integer) where T S = Array(tridiag(T, n)) A = sparse(T(1)I, n, n) return kron(A,S) + kron(S,A) end poisson(n::Integer) = poisson(Float64, n) """ Toeplitz Matrix =============== A Toeplitz matrix is a matrix in which each descending diagonal from left to right is constant. *Input options:* + [type,] vc, vr: `vc` and `vr` are the first column and row of the matrix. + [type,] v: symmatric case, i.e., `vc = vr = v`. + [type,] dim: `dim` is the dimension of the matrix. `v = [1:dim;]` is the first row and column vector. """ function toeplitz(::Type{T}, vc::Vector, vr::Vector) where T n = length(vc) length(vr) == n || throw(DimensionMismatch("")) vc[1] == vr[1] || error("The first element of the vectors must be the same.") A = Array{T,2}(undef, n, n) [i>=j ? A[i,j] = vc[i-j+1] : A[i,j] = vr[j-i+1] for i=1:n, j=1:n] A end toeplitz(::Type{T}, v::Vector) where T = toeplitz(T, v, v) toeplitz(::Type{T}, n::Integer) where T = toeplitz(T, [1:n;]) toeplitz(args...) = toeplitz(Float64, args...) toeplitz(::Type, args...) = throw(MethodError(toeplitz, Tuple(args))) """ Hankel Matrix ============= A Hankel matrix is a matrix that is symmetric and constant across the anti-diagonals. *Input options:* + [type,] vc, vr: `vc` and `vc` are the first column and last row of the matrix. If the last element of `vc` differs from the first element of `vr`, the last element of `rc` prevails. + [type,] v: `vc = vr = v`. + [type,] dim: `dim` is the dimension of the matrix. `v = [1:dim;]`. """ function hankel(::Type{T}, vc::Vector, vr::Vector) where T p = [vc; vr[2:end]] m = length(vc) n = length(vr) H = Array{T,2}(undef, m, n) [H[i,j] = p[i+j-1] for i=1:m, j=1:n] H end hankel(::Type{T}, v::Vector) where T = hankel(T, v, v) hankel(::Type{T}, n::Integer) where T = hankel(T, [1:n;]) hankel(args...) = hankel(Float64, args...) hankel(::Type, args...) = throw(MethodError(hankel, Tuple(args))) """ Prolate Matrix ============== A prolate matrix is a symmetirc, ill-conditioned Toeplitz matrix. *Input options:* + [type,] dim, w: `dim` is the dimension of the matrix. `w` is a real scalar. + [type,] dim: the case when `w = 0.25`. *References:* **J. M. Varah**. The Prolate Matrix. Linear Algebra and Appl. 187:267--278, 1993. """ function prolate(::Type{T}, n::Integer, w::Real) where T v = Array{T,1}(undef, n) v[1] = 2*w [v[i] = sin(2*pi*w*i)/pi*i for i = 2:n] return toeplitz(T, v) end prolate(::Type{T}, n::Integer) where T = prolate(T, n, 0.25) prolate(args...) = prolate(Float64, args...) prolate(::Type, args...) = throw(MethodError(prolate, Tuple(args))) """ Neumann Matrix ============== A singular matrix from the discrete Neumann problem. The matrix is sparse and the null space is formed by a vector of ones *Input options:* + [type,] dim: the dimension of the matrix is `dim^2`. *Groups:* ["eigen", "sparse"] *References:* **R. J. Plemmons**, Regular splittings and the discrete Neumann problem, Numer. Math., 25 (1976), pp. 153-161. """ function neumann(::Type{T}, n::Integer) where T if n == 1 return 4 * ones(T, 1,1) #handle 1-d case. end S = Matrix(tridiag(T, n)) S[1,2] = -2 S[n, n-1] = -2 A = sparse(T(1)I, n, n) return kron(S,A) + kron(A,S) end neumann(n::Integer) = neumann(Float64, n) # # Sylvester's orthogonal matrix # See Rosser matrix References 2. # # for a = d = 2, b = c = 1, P_block' * P_block = 10 * Identity # P_block(::Type{T}, a, b, c, d) where T = reshape(T[a, b, c, d, b, -a, -d, c, c, d, -a, -b, d, -c, b, -a], 4,4) """ Rosser Matrix ============= The Rosser matrix’s eigenvalues are very close together so it is a challenging matrix for many eigenvalue algorithms. *Input options:* + [type,] dim, a, b: `dim` is the dimension of the matrix. `dim` must be a power of 2. `a` and `b` are scalars. For `dim = 8, a = 2` and `b = 1`, the generated matrix is the test matrix used by Rosser. + [type,] dim: `a = rand(1:5), b = rand(1:5)`. *Groups:* ["eigen", "illcond", "random"] *References:* **J. B. Rosser, C. Lanczos, M. R. Hestenes, W. Karush**, Separation of close eigenvalues of a real symmetric matrix, Journal of Research of the National Bureau of Standards, v(47) (1951) """ function rosser(::Type{T}, n::Integer, a, b) where T if n < 1 lgn = 0 else lgn = round(Integer, log2(n)) end 2^lgn != n && throw(ArgumentError("n must be positive integer and a power of 2.")) if n == 1 # handle 1-d case return 611 * ones(T, 1, 1) end if n == 2 #eigenvalues are 500, 510 B = T[101 1; 1 101] P = T[2 1;1 -2] A = P'*B*P elseif n == 4 # eigenvalues are 0.1, 1019.9, 1020, 1020 for a = 2 and b = 1 B = zeros(T, n, n) B[1,1], B[1,4], B[4,1], B[4,4] = 101, 1, 1, 101; B[2,2], B[2,3], B[3,2], B[3,3] = 1, 10, 10, 101; P = P_block(T, a, b, b, a) A = P' * B * P elseif n == 8 # eigenvalues are 1020, 1020, 1000, 1000, 0.098, 0, -1020 B = zeros(T, n, n) B[1,1], B[6,1], B[2,2], B[8,2] = 102, 1, 101, 1; B[3,3], B[7,3] = 98, 14; B[4,4], B[5,4], B[4,5], B[5,5] = 1, 10, 10, 101; B[1,6], B[6,6], B[3,7],B[7,7], B[2,8], B[8,8] = 1, -102, 14, 2, 1, 101; P = [P_block(T, a, b, b, a)' zeros(T, 4,4); zeros(T, 4,4) P_block(T, b, -b, -a, a)] A = P' * B * P else lgn = lgn - 2 halfn = round(Integer, n/2) # using Sylvester's method P = P_block(T, a, b, b, a) m = 4 for i in 1:lgn P = [P zeros(T, m, m); zeros(T, m, m) P] m = m * 2 end # mix 4 2-by-2 matrices (with close eigenvalues) into a large nxn matrix. B_list = T[102, 1, 1, - 102, 101, 1, 1, 101, 1, 10, 10, 101, 98, 14, 14, 2] B = zeros(T, n, n) j, k = 1, 5 for i in 1:(halfn + 1) indexend = halfn -1 + i list_start = k list_end = k + 3 if list_start > 16 || list_end > 16 k = 1 list_start = 1 list_end = 4 end B[j,j], B[j,indexend], B[indexend, j], B[indexend, indexend] = B_list[list_start:list_end] j = j + 1 k = k + 4 end A = P' * B * P end return A end rosser(::Type{T}, n::Integer) where T = rosser(T, n, rand(1:5), rand(1:5)) rosser(args...) = rosser(Float64, args...) rosser(::Type, args...) = throw(MethodError(rosser, Tuple(args))) """ Matrix with Application in Sampling Theory ========================================== A nonsymmetric matrix with eigenvalues 0, 1, 2, ... n-1. *Input options:* + [type,] vec: `vec` is a vector with no repeated elements. + [type,] dim: `dim` is the dimension of the matrix. `vec = [1:dim;]/dim`. *Groups:* ["eigen"] *References:* **L. Bondesson and I. Traat**, A nonsymmetric matrix with integer eigenvalues, linear and multilinear algebra, 55(3) (2007), pp. 239-247 """ function sampling(::Type{T}, x::Vector) where T n = length(x) A = zeros(T, n, n) for j = 1:n, i = 1:n if i != j A[i,j] = x[i] / (x[i] - x[j]) end end d = sum(A, dims=2) A = A + diagm(0 => d[:]) return A end # # special probability case # see: # L. Bondesson and I. Traat, A Nonsymmetric Matrix with Integer # Eigenvalues, Linear and Multilinear Algebra, 55(3)(2007), pp. 239-247. # function sampling(::Type{T}, n::Integer) where T p = T[1:n;] / n return sampling(T, p) end sampling(args...) = sampling(Float64, args...) sampling(::Type, args...) = throw(MethodError(sampling, Tuple(args))) """ Wilkinson Matrix ================ The Wilkinson matrix is a symmetric tridiagonal matrix with pairs of nearly equal eigenvalues. The most frequently used case is `matrixdepot("wilkinson", 21)`. The result is of type `Tridiagonal`. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["symmetric", "eigen"] *References:* **J. H. Wilkinson**, Error analysis of direct methods of matrix inversion, J. Assoc. Comput. Mach., 8 (1961), pp. 281-330. """ function wilkinson(::Type{T}, n::Integer) where T if n == 1 # handle 1-d case return ones(T, 1, 1) end m = (n-1)/2 A = Tridiagonal(ones(T,n-1), abs.(T[-m:m;]), ones(T, n-1)) return A end wilkinson(n::Integer) = wilkinson(Float64, n) """ Random Matrix with Element -1, 0, 1 =================================== *Input options:* + [type,] row_dim, col_dim, k: `row_dim` and `col_dim` are row and column dimensions, `k = 1`: entries are 0 or 1. `k = 2`: entries are -1 or 1. `k = 3`: entries are -1, 0 or 1. + [type,] dim, k: `row_dim = col_dim = dim`. + [type,] dim: `k = 1`. *Groups:* ["random"] """ function rando(::Type{T}, m::Integer, n::Integer, k::Integer) where T A = Array{T,2}(undef, m, n) if k == 1 copyto!(A, floor.(rand(m,n) .+ .5)) elseif k == 2 copyto!(A, 2 * floor.(rand(m,n) .+ .5) .- one(T)) elseif k == 3 copyto!(A, round.(3 * rand(m,n) .- 1.5)) else throw(ArgumentError("invalid k value.")) end return A end rando(::Type{T}, n::Integer, k::Integer) where T = rando(T, n, n, k) rando(::Type{T}, n::Integer) where T = rando(T, n, n, 1) rando(args...) = rando(Float64, args...) rando(::Type, args...) = throw(MethodError(rando, Tuple(args))) # # Pre-multiply by random orthogonal matrix # function qmult!(A::Matrix{T}) where T n, m = size(A) d = zeros(T, n) for k = n-1:-1:1 # generate random Householder transformation x = randn(n-k+1) s = norm(x) sgn = sign(x[1]) + (x[1]==0) s = sgn * s d[k] = -sgn x[1] = x[1] + s beta = s * x[1] # apply the transformation to A y = x'*A[k:n, :]; A[k:n, :] = A[k:n, :] - x * (y /beta) end # tidy up signs for i=1:n-1 A[i, :] = d[i] * A[i, :] end A[n, :] = A[n, :] * sign(randn()) return A end """ Random Matrix with Pre-assigned Singular Values =============================================== *Input options:* + [type,] row_dim, col_dim, kappa, mode: `row_dim` and `col_dim` are the row and column dimensions. `kappa` is the condition number of the matrix. `mode = 1`: one large singular value. `mode = 2`: one small singular value. `mode = 3`: geometrically distributed singular values. `mode = 4`: arithmetrically distributed singular values. `mode = 5`: random singular values with unif. dist. logarithm. + [type,] dim, kappa, mode: `row_dim = col_dim = dim`. + [type,] dim, kappa: `mode = 3`. + [type,] dim: `kappa = sqrt(1/eps())`, `mode = 3`. *Groups:* ["illcond", "random"] *References:* **N. J. Higham**, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.3. """ function randsvd(::Type{T}, m::Integer, n::Integer, kappa, mode::Integer) where T kappa >= 1 || throw(ArgumentError("Condition number must be at least 1.")) kappa = convert(T, kappa) p = min(m,n) if p == 1 # handle 1-d case return ones(T, 1, 1)*kappa end if mode == 3 factor = kappa^(-1/(p-1)) sigma = factor.^[0:p-1;] elseif mode == 4 sigma = ones(T, p) - T[0:p-1;]/(p-1)*(1 - 1/kappa) elseif mode == 5 sigma = exp.(-rand(p) * log(kappa)) elseif mode == 2 sigma = ones(T, p) sigma[p] = one(T)/kappa elseif mode == 1 sigma = ones(p)./kappa sigma[1] = one(T) else throw(ArgumentError("invalid mode value.")) end A = zeros(T, m, n) A[1:p, 1:p] = diagm(0 => sigma) A = qmult!(copy(A')) A = qmult!(copy(A')) return A end randsvd(::Type{T}, n::Integer, kappa, mode) where T = randsvd(T, n, n, kappa, mode) randsvd(::Type{T}, n::Integer, kappa) where T= randsvd(T, n, kappa, 3) randsvd(::Type{T}, n::Integer) where T = randsvd(T, n, sqrt(1/eps(T))) randsvd(args...) = randsvd(Float64, args...) randsvd(::Type, args...) = throw(MethodError(randsvd, Tuple(args))) """ Random Orthogonal Upper Hessenberg Matrix ========================================= The matrix is constructed via a product of Givens rotations. *Input options:* + [type,] dim: the dimension of the matrix. *Groups:* ["random"] *References:* **W. B. Gragg**, The QR algorithm for unitary Hessenberg matrices, J. Comp. Appl. Math., 16 (1986), pp. 1-8. """ function rohess(::Type{T}, n::Integer) where T x = rand(n-1)*2*pi H = Matrix{T}(I, n, n) H[n,n] = sign(randn()) for i = n:-1:2 theta = x[i-1] c = convert(T, cos(theta)) s = convert(T, sin(theta)) H[[i-1; i], :] = [c*H[i-1, :][:]' + s*H[i, :][:]'; -s*H[i-1, :][:]' + c*H[i, :][:]'] end return H end rohess(n::Integer) = rohess(Float64, n) """ Kac-Murdock-Szego Toeplitz matrix ================================= *Input options:* + [type,] dim, rho: `dim` is the dimension of the matrix, `rho` is a scalar such that `A[i,j] = rho^(abs(i-j))`. + [type,] dim: `rho = 0.5`. *Groups:* ["inverse", "illcond", "symmetric", "posdef"] *References:* **W. F. Trench**, Numerical solution of the eigenvalue problem for Hermitian Toeplitz matrices, SIAM J. Matrix Analysis and Appl., 10 (1989), pp. 135-146 (and see the references therein). """ function kms(::Type{T}, n::Integer, rho::Number) where T A = typeof(rho) <: Complex ? Array{typeof(rho)}(undef, n, n) : Array{T,2}(undef, n, n) [A[i,j] = rho^(abs(i-j)) for i = 1:n, j = 1:n] if typeof(rho) <: Complex A = conj(tril(A, -1)) + triu(A) end return A end kms(::Type{T}, n::Integer) where T = kms(T, n, convert(T, 0.5)) kms(args...) = kms(Float64, args...) kms(::Type, args...) = throw(MethodError(kms, Tuple(args))) """ Wathen Matrix ============= Wathen Matrix is a sparse, symmetric positive, random matrix arose from the finite element method. The generated matrix is the consistent mass matrix for a regular nx-by-ny grid of 8-nodes. *Input options:* + [type,] nx, ny: the dimension of the matrix is equal to `3 * nx * ny + 2 * nx * ny + 1`. + [type,] n: `nx = ny = n`. *Groups:* ["symmetric", "posdef", "eigen", "random", "sparse"] *References:* **A. J. Wathen**, Realistic eigenvalue bounds for the Galerkin mass matrix, IMA J. Numer. Anal., 7 (1987), pp. 449-457. """ function wathen(::Type{T}, nx::Integer, ny::Integer) where T e1 = T[6 -6 2 -8;-6 32 -6 20;2 -6 6 -6;-8 20 -6 32] e2 = T[3 -8 2 -6;-8 16 -8 20;2 -8 3 -8;-6 20 -8 16] e3 = [e1 e2; e2' e1]/45 n = 3 * nx * ny + 2 * nx + 2 * ny + 1 ntriplets = nx * ny * 64 Irow = zeros(Int, ntriplets) Jrow = zeros(Int, ntriplets) Xrow = zeros(T, ntriplets) ntriplets = 0 rho = 100 * rand(nx, ny) node = zeros(T, 8) for j = 1:ny for i = 1:nx node[1] = 3 * j * nx + 2 * i + 2 * j + 1 node[2] = node[1] - 1 node[3] = node[2] - 1 node[4] = (3 * j - 1) * nx + 2 * j + i - 1 node[5] = (3 * j - 3) * nx + 2 * j + 2 * i - 3 node[6] = node[5] + 1 node[7] = node[5] + 2 node[8] = node[4] + 1 em = convert(T, rho[i,j]) * e3 for krow = 1:8 for kcol = 1:8 ntriplets += 1 Irow[ntriplets] = node[krow] Jrow[ntriplets] = node[kcol] Xrow[ntriplets] = em[krow, kcol] end end end end return sparse(Irow, Jrow, Xrow, n, n) end wathen(::Type{T}, n::Integer) where T = wathen(T, n, n) wathen(args...) = wathen(Float64, args...) wathen(::Type, args...) = throw(MethodError(wathen, Tuple(args))) """ Golub Matrix ============ Golub matrix is the product of two random unit lower and upper triangular matrices respectively. LU factorization without pivoting fails to reveal that such matrices are badly conditioned. *Input options:* + [type,] dim: the dimension of the matrix. *References:* **D. Viswanath and N. Trefethen**. Condition Numbers of Random Triangular Matrices, SIAM J. Matrix Anal. Appl. 19, 564-581, 1998. """ function golub(::Type{T}, n::Integer) where T s = 10 L = Array{T,2}(undef, n, n) U = Array{T,2}(undef, n, n) if T <: Integer [L[i,j] = round_matlab(T, s*randn()) for j = 1:n, i = 1:n] [U[i,j] = round_matlab(T, s*randn()) for j = 1:n, i = 1:n] else [L[i,j] = s*randn() for j = 1:n, i = 1:n] [U[i,j] = s*randn() for j = 1:n, i = 1:n] end L = tril(L, -1) + Matrix{T}(I, n, n) U = triu(U, 1) + Matrix{T}(I, n, n) return L*U end golub(n::Integer) = golub(Float64, n) """ Companion Matrix ================ The companion matrix to a monic polynomial `a(x) = a_0 + a_1x + ... + a_{n-1}x^{n-1} + x^n` is the n-by-n matrix with ones on the subdiagonal and the last column given by the coefficients of `a(x)`. *Input options:* + [type,] vec: `vec` is a vector of coefficients. + [type,] dim: `vec = [1:dim;]`. `dim` is the dimension of the matrix. """ function companion(::Type{T}, v::AbstractVector) where T n = length(v) A = zeros(T, n, n) A[:, end] = v for i = 1:n-1 A[i+1, i] = one(T) end A end companion(::Type{T}, n::Integer) where T = companion(T, [1:n;]) companion(args...) = companion(Float64, args...) companion(::Type, args...) = throw(MethodError(companion, Tuple(args)))
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
10675
# functions related to the logical operations on patterns # and predicate functions. # """ Pattern syntactic sugar the logical operators `|`, `&`, and `~` may be applied to all kind of `Pattern`s with the usual meaning. + `~` : unary negation operator - pattern does not match (highest priority) + `&` : binary logical and - both patterns match + `|` : binary logical or - any of the pattern match (lowest priority) + parentheses can be used to overrule operator precedence. + `[p...]` is the same as `p[1] | p[2] ...` + `(p...)` is the same as `p[1] & p[2] ...` + `~(p...) === ~((p...))` - that is `~(p[1] & p[2] ...)` + Precedence of '*' is higher that `~` for character and string objects: so `~ "a" * "b" === ~("a" * "b") === ~"ab"` also `~'a'^2*"b" === ~"aab"` """ function logical end import Base: ~ import LinearAlgebra: isposdef (&)(p::Tuple, q::Tuple) = tuple(p..., q...) (&)(p::Tuple, q::Pattern...) = tuple(p..., q...) (&)(p::Pattern, q::Tuple) = tuple(p, q...) (&)(p::Pattern, q::Pattern...) = tuple(p, q...) (|)(p::Pattern, q::Pattern...) = vcat(p, q...) (~)(c::AbstractChar) = Not(string(c)) (*)(a::Not{<:AbstractString}, b::Union{AbstractString,AbstractChar}) = Not(a.pattern * b) (~)(p::Not) = p.pattern Not(p::Not) = p.pattern (~)(p::Pattern...) = Not(tuple(p...)) (~)(p::Pattern) = p == EMPTY_PATTERN ? ALL_PATTERN : p == ALL_PATTERN ? EMPTY_PATTERN : Not(p) (~)() = EMPTY_PATTERN (~)(p::Vector{<:Pattern}) = length(p) == 0 ? ALL_PATTERN : length(p) == 1 ? Not(p[1]) : Not(p) const EMPTY_PATTERN = Pattern[] const ALL_PATTERN = () ### # simplification of patterns ### is_pure_string(p::AbstractString) = !occursin(r"[]*?]", p) is_pure_string(p::Pattern) = false is_pure_vector(p::Vector) = all(is_pure_string.(p)) is_pure_vector(p::Pattern) = false ### # Alias resolution ### function aliasresolve(db::MatrixDatabase, k::AbstractString) haskey(db.aliases, k) ? [db.aliases[k]] : String[] end function aliasresolve(db::MatrixDatabase, a::Alias{T,<:Integer}) where T aliasresolve(db, aliasname(a)) end function aliasresolve(db::MatrixDatabase, a::Alias{T,<:AbstractVector}) where T collect(Iterators.flatten(aliasresolve.(Ref(db), aliasname(a)))) end aliasresolve(db::MatrixDatabase, a::Alias{RemoteMatrixData{SSRemoteType},Colon}, ) = "*/*" aliasresolve(db::MatrixDatabase, a::Alias{RemoteMatrixData{MMRemoteType},Colon}) = "*/*/*" aliasresolve(::MatrixDatabase, ::Alias{GeneratedMatrixData{:B},Colon}) = :builtin aliasresolve(::MatrixDatabase, ::Alias{GeneratedMatrixData{:U},Colon}) = :user ### # Predefined predicates for MatrixData ### builtin(p...) = Alias{GeneratedMatrixData{:B}}(p...) user(p...) = Alias{GeneratedMatrixData{:U}}(p...) sp1(p...) = Alias{RemoteMatrixData{SSRemoteType}}(p...) mm1(p...) = Alias{RemoteMatrixData{MMRemoteType}}(p...) sp(p...) = sp1(p...) mm(p...) = mm1(p...) """ sp(i, j:k, ...) sp(pattern) The first form with integer and integer range arguments is a pattern selecting by the id number in the Suite Sparse collection. The second form is a pattern, which selects a matrix in the Suite Sparse collection, which corresponds to the pattern by name, even if the name is from the Matrix Market collection. example: mdlist(sp("*/*/1138_bus")) == ["HB/1138_bus"] """ sp(p::P) where P<:Pattern = is_ivec(p) ? sp1(p) : Alternate{SSRemoteType,P}(p) """ mm(i, j:k, ...) mm(pattern) The first form with integer and integer range arguments is a pattern selecting by the id number in the Matrix Market collection. The second form is a pattern, which selects a matrix in the Matrix Market collection, which corresponds to the pattern by name, even if the name is from the Suite Sparse collection. example: mdlist(mm("*/1138_bus")) == ["Harwell-Boeing/psadmit/1138_bus"] """ mm(p::P) where P<:Pattern = is_ivec(p) ? mm1(p) : Alternate{MMRemoteType,P}(p) is_ivec(::Integer) = true is_ivec(::AbstractVector{<:Integer}) = true is_ivec(p::AbstractVector) = all(is_ivec.(p)) is_ivec(::typeof(:)) = true is_ivec(::Any) = false function _issymmetry(data::RemoteMatrixData, T::Type{<:MMSymmetry}) data.properties[] !== nothing && data.properties[].symmetry isa T end function _isfield(data::RemoteMatrixData, T::Type{<:MMField}) data.properties[] !== nothing && data.properties[].field isa T end isgeneral(data::RemoteMatrixData) = _issymmetry(data, MMSymmetryGeneral) issymmetric(data::RemoteMatrixData) = _issymmetry(data, MMSymmetrySymmetric) isskew(data::RemoteMatrixData) = _issymmetry(data, MMSymmetrySkewSymmetric) ishermitian(data::RemoteMatrixData) = _issymmetry(data, MMSymmetryHermitian) isgeneral(data::MatrixData) = !issymmetric(data) && !isskew(data) && !ishermitian(data) issymmetric(data::MatrixData) = data.name in mdlist(:symmetric) isskew(data::MatrixData) = false ishermitian(data::MatrixData) = false issparse(data::RemoteMatrixData) = true issparse(data::MatrixData) = data.name in mdlist(:sparse) isposdef(data::RemoteMatrixData) = hasinfo(data) && data.posdef isposdef(data::MatrixData) = data.name in mdlist(:posdef) iscomplex(data::RemoteMatrixData) = _isfield(data, MMFieldComplex) isreal(data::RemoteMatrixData) = _isfield(data, MMFieldReal) isinteger(data::RemoteMatrixData) = _isfield(data, MMFieldInteger) isboolean(data::RemoteMatrixData) = _isfield(data, MMFieldPattern) iscomplex(data::MatrixData) = false isreal(data::MatrixData) = false isinteger(data::MatrixData) = false isboolean(data::MatrixData) = false hasinfo(data::RemoteMatrixData) = data.header.m > 0 && data.header.n > 0 # isassigned(data.properties) && data.properties[] !== nothing hasinfo(data::MatrixData) = false isremote(data::RemoteMatrixData) = true isremote(data::MatrixData) = false isloaded(data::RemoteMatrixData) = hasinfo(data) && !isempty(data.metadata) isloaded(data::MatrixData) = false isunloaded(data::RemoteMatrixData) = !isloaded(data) isunloaded(data::MatrixData) = false isuser(data::GeneratedMatrixData{:U}) = true isuser(data::MatrixData) = false isbuiltin(data::GeneratedMatrixData{:B}) = true isbuiltin(data::MatrixData) = false islocal(data::GeneratedMatrixData) = true islocal(data::MatrixData) = false """ pred_macro(f::Function, s::Symbol...) Return a predicate function, which assigns to a each `data::MatrixData` iff * `hasdata(data)` and * all symbols `s` are property names of `data` and * `f` applied to the tuple of values of those properties returns `true` """ function pred_macro(f::Function, s::Symbol...) data::MatrixData -> hasinfo(data) && s ⊆ propertynames(data) && f(getproperty.(Ref(data), s)...) end """ prednzdev(deviation) Test predicate - does number of stored (structural) values deviate from nnz by more than `deviation`. That would indicate a data error or high number of stored zeros. The number of stored values is in `dnz`. It has to be approximately doubled for symmetric matrices to be comparable to `nnz``. """ function prednzdev(dev::AbstractFloat=0.1) function f(data::RemoteMatrixData) n1, n2 = extremnnz(data) n1 -= Int(floor(n1 * dev)) n2 += Int(floor(n2 * dev)) isloaded(data) && ! ( n1 <= data.nnz <= n2 ) end f(::MatrixData) = false f end """ keyword(word::Union{AbstractString,Tuple,Vector}) Predicate function checks, if `word` is contained in on to the textual metadata fields `[:notes, :title, :kind, :author]`. Tuples and Vectors are interpreted as `AND` resp. `OR`. """ function keyword(s::AbstractString) function f(data::RemoteMatrixData) text = join([data.notes, data.title, data.author, data.kind], ' ') match(Regex("\\b$s\\b", "i"), text) !== nothing end f(::MatrixData) = false f end # this is to translate `keyword("a" & "b")` to `keyword("a") & keyword("b")` keyword(t::Tuple) = Tuple(keyword.(t)) keyword(t::AbstractVector{<:AbstractString}) = [keyword(x) for x in t] """ hasdata(meta::Union{Symbol,Tuple,Vector}) Predicate function checks, if matrix data have metadata symbol `meta`. Tuples and Vectors are interpreted as `AND` resp. `OR`. """ function hasdata(s::Symbol, s2::Symbol...) function f(data::MatrixData) ms = metasymbols(data) s in ms && issubset(s2, metasymbols(data)) end f end hasdata(t::NTuple{N,Symbol} where N) = hasdata(t...) hasdata(t::Tuple) = Tuple(hasdata.(t)) hasdata(t::AbstractVector) = [hasdata(x) for x in t] """ check_symbols(p::Pattern) throw `ArgumentError` if pattern uses unknown symbol as a group name. """ function check_symbols(p::Pattern) s = setdiff(filter(x->x isa Symbol, flatten_pattern(p)), listgroups()) isempty(s) || argerr("The following symbols are no group names: $s") end ############################ # Predicate generating macro ############################ # extract all symbols from an expression function extract_symbols(ex) s = Set{Symbol}() append_symbols!(::Any) = s append_symbols!(ex::Symbol) = push!(s, ex) function append_symbols!(ex::Expr) append_symbols!(ex.head) append_symbols!.(ex.args) s end collect(append_symbols!(ex)) end # construct a function definition from a list of symbols and expression # `make_func([:a, :b], expr)` returns `:( (a, b) -> expr )` function make_func(sli::AbstractVector{Symbol}, ex) res = :( () -> $ex ) append!(res.args[1].args, sli) res end """ PROPS The symbols, which are naming properties of `MatrixData` """ const PROPS = (:name, :id, :metadata, fieldnames(MetaInfo)...) function make_pred(ex) syms = extract_symbols(ex) ∩ PROPS :(MatrixDepot.pred_macro($(make_func(syms, ex)), $(QuoteNode.(syms)...))) end """ @pred(expression) Generate a predicate function using the expression as function body. Variable names within the expression, which are properties of `RemoteMatrixData` (e.g. `title`, `m`, `nnz`) are used to access `data.title` etc. Other variable names, are used from the outer scope. example: `maxnnz = 1_000; listnames(@pred(n <= maxnnz))` would produce a list of all data with less than `maxnnz` structural non-zeros. """ macro pred(ex) esc(make_pred(ex)) end """ charfun(p::Pattern) Return the characteristic function corresponding to the set-defining pattern `p`. This function can be applied to objects `data::MatrixData` and strings, the canonical names of those objects. """ function charfun(p::Pattern) f(d::MatrixData) = !isempty(list!(MATRIX_DB, [d.name], p)) # equivalent to: `d.name ∈ mdlist(p)` f(s::AbstractString) = haskey(MATRIX_DB.data, s) && f(MATRIX_DB.data[s]) f end # make `:` an ordinary pattern (so it can be applied to MatrixData) import Base: (:) (:)(d::MatrixData) = true
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
4113
using Markdown "return information about all matrices selected by pattern" mdinfo(p::Pattern) = mdinfo(MATRIX_DB, p) function mdinfo(db::MatrixDatabase, p::Pattern) check_symbols(p) mdbuffer = Markdown.MD([]) md = mdbuffer for name in mdlist(p) try md = mdinfo(db.data[name]) catch ex ex isa InterruptException && rethrow() md = Markdown.parse("# $name\nno info available") finally append!(mdbuffer.content, md.content) end end mdbuffer end mdinfo(md::MatrixDescriptor) = mdinfo(md.data) _mdheader(md::Markdown.MD, p, o) = isempty(md.content) ? (nothing, o) : _mdheader(md.content[1], md, o) _mdheader(md::Markdown.Header, p, o) = (md, p) _mdheader(md, p, o) = (nothing, o) function mdinfo(data::GeneratedMatrixData) md = Docs.doc(data.func) # As md is cached internally, need to make copies mdh, md = _mdheader(md, nothing, md) if mdh !== nothing mdh, md = Markdown.Header(copy(mdh.text)), copy(md) push!(mdh.text, " ($(data.name))") md.content[1] = mdh end md end _repl(a::AbstractString) = a _repl(a::AbstractString, p::Pair, q::Pair...) = _repl(replace(a, p), q...) function mdinfo(data::RemoteMatrixData) file = verify_loadinfo(data) txt = mmreadcomment(file) txt = _repl(txt, r"^%-+$"m => "---", r"^%%" => "###### ", r"%+" => "* ") md = Markdown.parse(txt) insert!(md.content, 1, Markdown.Header{1}([data.name])) md end """ format output list to multi- column table form adapted to display width. """ function buildnametable(hdr, name::AbstractVector, maxrow::Integer=0) maxrow = maxrow <= 0 ? displaysize(stdout)[2] + maxrow : maxrow maxrow = clamp(maxrow, 20, 1000) hdr isa Vector || ( hdr = [hdr] ) n = length(name) name = string.(name) cols = 1 while sumwidth(name, cols+1) <= maxrow - 1 * cols && cols < n cols += 1 end rows = (length(name) + cols - 1) ÷ cols n = length(name) while n < rows * cols push!(name, "") n += 1 end name = reshape(name, rows, cols) name = vecvec(name) insert!(name, 1, [string.(hdr)..., tab("", cols-length(hdr))...]) Markdown.Table(name, tab(:l, cols)) end function sumwidth(name::AbstractVector, cols::Integer) n = length(name) rows = (n + cols - 1) ÷ cols wi = 0 for k = 1:cols r = (k-1)*rows+1:1:min(k*rows,n) if !isempty(r) wi += maximum(length.(name[r])) end end wi end vecvec(tab::Matrix) = [ tab[i,:] for i in 1:size(tab,1)] tab(a, cols::Integer) = [a for i in 1:cols] function buildnametable1(db::MatrixDatabase, hdr, p::Pattern, maxrow::Integer=0) dali = mdata.(Ref(db), mdlist(db, p)) lt(a, b) = a.id < b.id sort!(dali, lt=lt) item(data::MatrixData) = string(data.id, " ", data.name) MD(buildnametable(hdr, item.(dali), maxrow)) end MD(a...) = Markdown.MD([a...]) listnames(p::Pattern) = listnames(MATRIX_DB, p) function listnames(db::MatrixDatabase, p::Pattern) li = mdlist(db, p) MD(buildnametable("list($(length(li)))", li)) end ############################## # display database information ############################## """ overview([db]) return formatted overview about matrices and groups in the collection. """ function overview(db::MatrixDatabase) # Print information strings LMARG = -10 hdr_mat = Markdown.Header{3}("Currently loaded Matrices") dli(p) = mdata.(Ref(db), mdlist(db, p)) ldall(p) = [length(mdlist(p & isloaded)), length(mdlist(p))] bmat = buildnametable1(db, "builtin(#)", :builtin, LMARG) umat = buildnametable1(db, "user(#)", :user, LMARG) spdir = buildnametable(["Suite Sparse", "of"], ldall(sp(:))) mmdir = buildnametable(["MatrixMarket", "of"], ldall(mm(:))) hdr_groups = Markdown.Header{3}("Groups:") groups = buildnametable("Groups", listgroups(), LMARG) MD(([hdr_mat, bmat, umat, groups, spdir, mmdir])) end """ mdinfo() Overview about matrices. """ mdinfo(db::MatrixDatabase=MATRIX_DB) = overview(db)
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
13179
""" mmread(filename|io) Read `Matrixmarket` format file (extension `.mtx`) and return sparse or dense matrix. Symmetric and Hermitian matrices use the corresponding wrapper types. Patterns result in sparse matrics with element type `Bool`. They may be converted to numerical types by multiplying with a number. """ function mmread(filename::AbstractString) open(filename, "r") do file if stat(file).size == 0 throw(DataError("matrix file $filename is empty")) end mmread(file) end end using Mmap const COORD = "coordinate" const ARRAY = "array" const MATRIX = "matrix" const MATRIXM = "%%matrixmarket" const COMPLEX = "complex" const REAL = "real" const INTEGER = "integer" const PATTERN = "pattern" const GENERAL = "general" const SYMMETRIC = "symmetric" const HERMITIAN = "hermitian" const SKEW_SYMMETRIC = "skew-symmetric" function mmread(file::IO) line = lowercase(readline(file)) tokens = split(line) if length(tokens) < 2 || tokens[1] != MATRIXM parserr(string("Matrixmarket: invalid header:", line)) end line = readline(file) while length(strip(line)) == 0 || line[1] == '%' line = readline(file) end if tokens[2] == MATRIX mmread_matrix(file, line, tokens[3:end]...) else parserr(string("Matrixmarket: unsupported type: ", line)) end end # mmap for regular files - else read function getbytes(io::IOStream) isfile(io) ? Mmap.mmap(io, grow=false, shared=false) : read(io) end getbytes(io::IO) = read(io) function mmread_matrix(file::IO, line, form, field, symm) FMAP = Dict(REAL => (3, Float64), COMPLEX => (4, ComplexF64), INTEGER => (3, Int64), PATTERN => (2, Bool)) ty, T = get(FMAP, field) do parserr("Matrixmarket: unsupported field $field (only real/complex/pattern)") end SMAP = Dict(GENERAL => (1, 0, Any), SYMMETRIC => (0, 1, Symmetric), SKEW_SYMMETRIC => (1, 1, Array), HERMITIAN => (0, 1, Hermitian)) p1, pc, wrapper = get(SMAP, symm) do parserr("Matrixmarket: unsupported symmetry $symm (general/symmetric/hermitian,skew-symmetric)") end if form == COORD m, n, nz = parseint(line) b = getbytes(file) rv = Vector{Int}(undef, nz) cv = Vector{Int}(undef, nz) vv = Vector{T}(undef, nz) parseloop!(Val(ty), b, rv, cv, vv) result = mksparse!(m, n, rv, cv, vv) elseif form == ARRAY m, n = parseint(line) b = getbytes(file) p = 1 result = zeros(T, m, n) for c = 1:n for r = (pc*c+p1):m p, v = parsenext(T, b, p) result[r,c] = v end end else parserr("Matrixmarket: unsupported format '$form'") end wrap(result, wrapper) end wrap(result, ::Type{T}) where T<:Union{Symmetric,Hermitian} = T(result, :L) wrap(result, ::Type{Array}) = result - mtranspose(result) wrap(result, ::Type{Any}) = result function parseloop!(::Val{4}, c::Vector{UInt8}, rv, cv, vv::Vector{T}) where T<:Complex nz = length(rv) R = real(T) p = 1 for i = 1:nz p, rv[i] = parsenext(Int, c, p) p, cv[i] = parsenext(Int, c, p) p, r = parsenext(R, c, p) p, s = parsenext(R, c, p) vv[i] = r + s*im end end function parseloop!(::Val{3}, c::Vector{UInt8}, rv, cv, vv::Vector{T}) where T <:Real nz = length(rv) p = 1 for i = 1:nz p, rv[i] = parsenext(Int, c, p) p, cv[i] = parsenext(Int, c, p) p, vv[i] = parsenext(T, c, p) end end function parseloop!(::Val{2}, c::Vector{UInt8}, rv, cv, vv::Vector{T}) where T<:Number nz = length(rv) p = 1 for i = 1:nz p, rv[i] = parsenext(Int, c, p) p, cv[i] = parsenext(Int, c, p) end fill!(vv, T(1)) end function parseint(line::AbstractString) tokens = split(line) parse.(Int, tokens) end """ mksparse(m, n, rowval, colval, nzval) mksparse!(m, n, rowval, colval, nzval) Construct a `SparseMatrixCSC` of dimensions `(m,n)` from the data given in the three input vectors of equal lengths. `mksparse!` destroys the content of `colval`. `A[rowval[i],colval[i]] == nzval[i] for i ∈ 1:length(nzval)`. All other entries are zero. """ mksparse(m, n, rv, cv, vv) = mksparse!(m, n, rv, copy(cv), vv) function mksparse!(m::Integer, n::Integer, rv::AbstractVector{Ti}, cv::AbstractVector{Ti}, vv::AbstractVector{Tv}) where {Ti<:Integer,Tv<:Number} nz = length(rv) length(cv) == nz == length(vv) || argerr("all vectors need same length") micv, mcv = extrema(cv) mirv, mrv = extrema(rv) micv > 0 && mcv <= n || daterr("all column indices must be >= 1 and <= $n") mirv > 0 && mrv <= m || daterr("all row indices must be >= 1 and <= $m") sizeof(Ti) <= 8 || argerr("Index type greater 64 bits not supported") sr = count_ones(Ti(nextpow(2, mrv + 1) - 1)) sh = count_zeros(Ti(nextpow(2, mcv + 1) - 1)) sr < sh || argerr("combined size of column and row indices exceeds $Ti size") # Ti must be able to keep (nz + 1) (nz + 1) % Ti != nz + 1 && argerr("Ti($Ti) cannot store nz($nz)") # compress row, col into Ti # t = UInt64[] # push!(t, time_ns()) colptr = zeros(Ti, n+1) colptr[1] = 1 # push!(t, time_ns()) @inbounds for i = 1:nz cvi = cv[i] cv[i] = cvi << sr | rv[i] colptr[cvi+1] += 1 end # push!(t, time_ns()) cumsum!(colptr, colptr) # push!(t, time_ns()) p = specialsort(cv, sr) # push!(t, time_ns()) # println("times: $(diff(t) ./ 1e6) ms") SparseMatrixCSC{Tv,Ti}(m, n, colptr, rv[p], vv[p]) end function specialsort(cv::Vector{Int}, sr::Int) nz = length(cv) if nz > 10000 x = isqrt(nz) << sr p = sortperm(cv .÷ x) sortperm!(p, cv, initialized=true) else sortperm(cv) end end """ colval(A) reconstruct column-indices from colptr of `SparseMatrixCSC`. """ function colval(A::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} nz = nnz(A) cv = Vector{Ti}(undef, nz) colptr = A.colptr for j = 1:A.n for i = colptr[j]:colptr[j+1]-1 cv[i] = j end end cv end """ mtranspose(A) Materialized transpose of a matrix """ mtranspose(A::SparseMatrixCSC) = mksparse!(A.n, A.m, colval(A), copy(A.rowval), copy(A.nzval)) mtranspose(A::Matrix) = Matrix(transpose(A)) mtranspose(A) = transpose(A) """ madjoint(A) Materialized adjoint of sparse Matrix """ madjoint(A) = conj!(mtranspose(A)) """ mmreadcomment(filename) return info comment strings for MatrixMarket format files """ function mmreadcomment(filename::AbstractString) io = IOBuffer() mark(io) open(filename,"r") do mmfile skip = 0 while !eof(mmfile) s = readline(mmfile) skip = isempty(strip(s)) || s[1] == '%' ? 0 : skip + 1 skip <= 1 && println(io, s) if skip == 1 length(split(s)) == 3 && break reset(io) mark(io) end end end String(take!(io)) end """ mmreadheader(filename) Read header information from mtx file. """ function mmreadheader(file::AbstractString) if isfile(file) open(file) do io if stat(io).size == 0 return nothing end line = lowercase(readline(io)) while true token = split(line) if length(token) >= 4 && token[1] == MATRIXM && token[2] == MATRIX && token[3] in [COORD, ARRAY] hdr = Dict{Symbol,Any}() field = :none while startswith(line, '%') || isempty(strip(line)) field = push_hdr!(hdr, line, field) line = readline(io) end res = try parseint(line) catch; [] end if length(res) != (token[3] == COORD ? 3 : 2) daterr("MatrixMarket file '$file' invalid sizes: '$line'") end hdr[:m] = res[1] hdr[:n] = res[2] length(res) >= 3 && (hdr[:nz] = res[3]) hdr[:format] = token[3] hdr[:field] = token[4] hdr[:symmetry] = token[5] if haskey(hdr, :notes) hdr[:notes] = join(wordlist(String(take!(hdr[:notes]))), ' ') end if haskey(hdr, :date) val = hdr[:date] hdr[:date] = isempty(val) ? 0 : parse(Int, hdr[:date]) end if length(hdr) >= 6 && get(hdr, :nz, 0) > 0 return hdr else while !eof(io) && !startswith(line, '%') line = readline(io) end if eof(io) return hdr end line = lowercase(line) end else daterr("file '$file' is not a MatrixMarket file") end end end else nothing end end """ wordlist(string) Separate words is string by spaces and delimiters. Return list of unique words, which can be used as keywords. """ function wordlist(s::AbstractString) list = unique!(split(s, r"[][\s(){}`\"'*]", keepempty = false)) list = replace.(list, Ref(r"[.:,;']$" => "")) # remove all lowercase words with less than ... chars list = filter!(x->!(length(x)<4 && all(islowercase.(collect(x))) || length(x) < 2), list) unique!(list) end function push_hdr!(hdr, line::AbstractString, field::Symbol) isempty(strip(line)) && return field if field == :notes if !startswith(line, "%---") println(get!(hdr, field) do; IOBuffer() end, strip(line[2:end])) end return field end reg = r"^% *([^:[]+): *(.*)$" regtitle = r"^% *\[([^]]*)]" if (m = match(reg, line)) !== nothing s = Symbol(m[1]) if s in (:name, :kind, :ed, :fields, :author, :date) field = s value = strip(m[2]) hdr[field] = value elseif s == :notes field = s end elseif (m = match(regtitle, line)) !== nothing field = :title value = m[1] hdr[field] = value end field end ### parsing decimal integers and floats function _parsenext(v::Vector{UInt8}, p1::Int) iaccu = Unsigned(0) daccu = Unsigned(0) eaccu = 0 df = 0 sig = 0 esig = 0 i = p1 n = length(v) c = v[i] while c == 0x20 || c == 0x0a || c == 0x0d || c == 0x09 c = v[i += 1] end n0 = i if c == UInt8('+') sig = 1 c = v[i += 1] elseif c == UInt8('-') sig = -1 c = v[i += 1] end ne = i di = 0 while 0x30 <= c <= 0x39 c -= 0x30 di += di > 0 || c > 0 iaccu = iaccu * 10 + c c = v[i += 1] end if c == UInt8('.') c = v[i += 1] d0 = i while 0x30 <= c <= 0x39 c -= 0x30 di += di > 0 || c > 0 daccu = daccu * 10 + c c = v[i += 1] end df = i - d0 ne += 1 end i > ne || parserr("Invalid decimal number: '$(String(v[n0:min(end,n0+5)]))'") if i > ne && ( c == UInt8('e') || c == UInt8('E') ) c = v[i += 1] if c == UInt8('+') esig = 1 c = v[i += 1] elseif c == UInt8('-') esig = -1 c = v[i += 1] end while 0x30 <= c <= 0x39 eaccu = eaccu * 10 + c - 0x30 c = v[i += 1] end if esig < 0 eaccu = -eaccu end end i == n0 && parserr("No decimal number found: '$(String(v[n0:min(end,n0+5)]))'") i, iaccu, daccu, eaccu, sig, df, di end function parsenext(T::Type{<:Signed}, v::Vector{UInt8}, p1::Int) i, iaccu, daccu, eaccu, sig, df = _parsenext(v, p1) daccu == 0 && eaccu == 0 && df == 0 || error("1") i, T(iaccu) * ifelse(sig < 0, T(-1), T(1)) end function parsenext(T::Type{<:Unsigned}, v::Vector{UInt8}, p1::Int) i, iaccu, daccu, eaccu, sig, df = _parsenext(v, p1) daccu == 0 && eaccu == 0 && sig >= 0 && df == 0 || error("2") i, T(iaccu) end function parsenext(T::Type{<:AbstractFloat}, v::Vector{UInt8}, p1::Int) i, iaccu, daccu, eaccu, sig, df, di = _parsenext(v, p1) eaccu -= df if di <= 16 && iaccu != 0 daccu += 10^df * iaccu end f = if di <= 16 && daccu < UInt(1)<<53 if 0 <= eaccu < 23 T(daccu) * exp10(eaccu) elseif 0 < -eaccu < 23 T(daccu) / exp10(-eaccu) else parse(T, String(view(v, p1:i-1))) end else parse(T, String(view(v, p1:i-1))) end i, (sig < 0 ? -f : f) end function parsenext(T::Type{<:Complex}, c, p) R = real(T) p, r = parsenext(R, c, p) p, s = parsenext(R, c, p) p, r + s*im end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
28820
# Test matrices for regularization methods from Hansen's # Regularization toolbox """ Oscillating Matrix ================== A matrix `A` is called oscillating if `A` is totally nonnegative and if there exists an integer `q > 0` such that `A^q` is totally positive. *Input options:* + [type,] Σ: the singular value spectrum of the matrix. + [type,] dim, mode: `dim` is the dimension of the matrix. `mode = 1`: geometrically distributed singular values. `mode = 2`: arithmetrically distributed singular values. + [type,] dim: `mode = 1`. *Groups:* ['symmetric','posdef', 'random', 'eigen'] *References:* **Per Christian Hansen**, Test matrices for regularization methods. SIAM J. SCI. COMPUT Vol 16, No2, pp 506-512 (1995). """ function oscillate(Σ::Vector{T}) where T n = length(Σ) dv = rand(T, 1, n)[:] .+ eps(T) ev = rand(T, 1, n-1)[:] .+ eps(T) B = Bidiagonal(dv, ev, :U) U, S, V = svd(B) return U*Diagonal(Σ)*U' end function oscillate(::Type{T}, n::Integer, mode::Integer) where T κ = sqrt(1/eps(T)) if mode == 1 factor = κ^(-1/(n-1)) Σ = factor.^[0:n-1;] elseif mode == 2 Σ = ones(T, n) - T[0:n-1;]/(n-1)*(1 - 1/κ) else throw(ArgumentError("invalid mode value.")) end return oscillate(Σ) end oscillate(::Type{T}, n::Integer) where T = oscillate(T, n, 2) oscillate(args...) = oscillate(Float64, args...) oscillate(::Type, args...) = throw(MethodError(oscillate, Tuple(args))) struct RegProb{T} A::AbstractMatrix{T} # matrix of interest b::AbstractVector{T} # right-hand side x::AbstractVector{T} # the solution to Ax = b end struct RegProbNoSolution{T} A::AbstractMatrix{T} # matrix of interest b::AbstractVector{T} # right-hand side end function show(io::IO, p::RegProb) println(io, "Test problems for Regularization Methods") println(io, "A:") display(p.A) println(io, "b:") display(p.b) println(io, "x:") display(p.x) end function show(io::IO, p::RegProbNoSolution) println(io, "Test problems for Regularization Methods with No Solution") println(io, "A:") display(p.A) println(io, "b:") display(p.b) end # The following test problems are derived from Per Christian Hansen's # Regularization tools for MATLAB. # http://www.imm.dtu.dk/~pcha/Regutools/ # # BSD License # Copyright (c) 2015, Per Christian Hansen # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the distribution # * Neither the name of the DTU Compute nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Computation of the Second Derivative ==================================== A classical test problem for regularization algorithms: This is a mildly ill-posed problem. It is a discretization of a first kind Fredholm integral equation whose kernel K is the Green's function for the second derivative. *Input options:* + [type,] dim, example, [matrixonly]: the dimension of the matrix is `dim`. One choose between between the following right-hand g and solution f: example = 1 gives g(s) = (s^3 - s)/6, f(t) = t. example = 2 gives g(s) = exp(s) + (1 -e)s - 1, f(t) = exp(t) example = 3 gives g(s) = | (4s^3 - 3s)/24, s < 0.5 | (-4s^3 + 12s^2 - 9s + 1)/24, s>= 0.5 f(t) = | t, t < 0.5 f(t) = | 1- t, t >= 0.5. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). + [type,] dim, [matrixonly]: `example = 1`. *Groups:* ["regprob"] *References:* **P. C. Hansen**, Regularization tools: A MATLAB package for analysis and solution of discrete ill-posed problems. Numerical Algorithms, 6(1994), pp.1-35 """ function deriv2(::Type{T}, n::Integer, example::Integer, matrixonly::Bool = true) where T h = convert(T, one(T)/n); sqh = sqrt(h) h32 = h*sqh; h2 = h^2; sqhi = one(T)/sqh t = 2/3; A = zeros(T, n, n) # compute A for i = 1:n A[i,i] = h2*((i^2 - i + 0.25)*h - (i - t)) for j = 1:i-1 A[i,j] = h2*(j - 0.5)*((i - 0.5)*h - 1) end end A = A + tril(A, -1)' if matrixonly return A else b = zeros(T, n) x = zeros(T, n) if example == 1 # compute b [b[i] = h32*(i - 0.5)*((i^2 + (i-1)^2)*h2/2 - 1)/6 for i = 1:n] # compute x [x[i] = h32*(i - 0.5) for i = 1:n] elseif example == 2 ee = one(T) - exp(one(T)) [b[i] = sqhi*(exp(i*h) - exp((i-1)*h) + ee*(i-0.5)*h2 - h) for i = 1:n] [x[i] = sqhi*(exp(i*h) - exp((i-1)*h)) for i = 1:n] elseif example == 3 mod(n, 2) == 0 || error("The order n must be even.") for i = 1:div(n,2) s12 = (i*h)^2; s22 = ((i-1)*h)^2 b[i] = sqhi*(s12 + s22 - 1.5)*(s12 - s22)/24 end for i = div(n, 2)+1:n s1 = i*h; s12 = s1^2; s2 = (i-1)*h; s22 = s2^2 b[i] = sqhi*(-(s12 + s22)*(s12 - s22) + 4*(s1^3 - s2^3) - 4.5*(s12 - s22) + h)/24 end [x[i] = sqhi*((i*h)^2 - ((i-1)*h)^2)/2 for i = 1:div(n, 2)] [x[i] = sqhi*(h - ((i*h)^2 - ((i-1)*h)^2)/2) for i = div(n, 2)+1:n] else throw(ArgumentError("Illegal value of example.")) end return RegProb(A, b, x) end end deriv2(::Type{T}, n::Integer, matrixonly::Bool = true) where T = deriv2(T, n, 1, matrixonly) deriv2(args...) = deriv2(Float64, args...) deriv2(::Type, args...) = throw(MethodError(deriv2, Tuple(args))) """ One-Dimensional Image Restoration Model ======================================= This test problem uses a first-kind Fredholm integral equation to model a one-dimensional image restoration situation. *Input options:* + [type,] dim, [matrixonly]: the dimesion of the matrix `dim` must be even. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **C. B. Shaw, Jr.**, Improvements of the resolution of an instrument by numerical solution of an integral equation. J. Math. Ana. Appl. 37 (1972), 83-112. """ function shaw(::Type{T}, n::Integer, matrixonly::Bool = true) where T mod(n, 2) == 0 || error("The dimension of the matrix must be even.") h = π/n; A = zeros(T, n, n) # compute A co = cos.(-π/2 .+ T[.5:n-.5;] .* h) psi = π .* sin.(-π/2 .+ T[.5:n-.5;] .* h) for i in 1:div(n,2) for j in i:n-i ss = psi[i] +psi[j] A[i,j] = ((co[i] + co[j])*sin(ss)/ss)^2 A[n-j+1, n-i+1] = A[i,j] end A[i, n-i+1] = (2*co[i])^2 end A = A + triu(A, 1)'; A = A*h if matrixonly return A else # compute x and b a1 = 2 c1 = 6 t1 = .8 a2 = 1 c2 = 2 t2 = -.5 x = a1 .* exp.(-c1 .* (-π/2 .+ T[.5:n-.5;] .* h .- t1).^2) .+ a2 .* exp.(-c2 .* (-π/2 .+ T[.5:n-.5;] .* h .- t2).^2) b = A*x return RegProb(A, b, x) end end shaw(args...) = shaw(Float64, args...) shaw(::Type, args...) = throw(MethodError(shaw, Tuple(args))) """ A Problem with a Discontinuous Solution ======================================= *Input options:* + [type,] dim, t1, t2, [matrixonly]: the dimension of matrix is `dim`. `t1` and `t2` are two real scalars such that `0 < t1 < t2 < 1`. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). + [type,] n, [matrixonly]: `t1 = 1/3` and `t2 = 2/3`. *Groups:* ["regprob"] *References:* **G. M. Wing**, A Primer on Integral Equations of the First Kind, Society for Industrial and Applied Mathematics, 1991, p. 109. """ function wing(::Type{T}, n::Integer, t1::Real, t2::Real, matrixonly = true) where T t1 < t2 || error("t1 must be smaller than t2") A = zeros(T, n, n) h = T(1/n) # compute A sti = (T[1:n;] .- 0.5) * h for i in 1:n A[i,:] .= h .* sti .* exp.(-sti[i] .* sti.^2) end if matrixonly return A else # compute b b = sqrt(h) .* 0.5 .* (exp.(-sti .* t1^2) .- exp.(-sti .* t2^2))./sti # compute x indices = [findfirst(t1 .< sti):findlast(t2 .> sti);] x = zeros(T,n); x[indices] = sqrt(h)*ones(length(indices)) return RegProb(A, b, x) end end wing(::Type{T}, n::Integer, matrixonly = true) where T = wing(T, n, 1/3, 2/3, matrixonly) wing(args...) = wing(Float64, args...) wing(::Type, args...) = throw(MethodError(wing, Tuple(args))) """ Severely Ill-posed Problem Suggested by Fox & Goodwin ===================================================== This is a model problem discretized by simple quadrature, which does not satifiy the discrete Picard condition for the small singular values. *Input options:* + [type,] dim, [matrixonly]: `dim` is the dimension of the matrix. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **C. T. H. Baker**, The Numerical Treatment of Integral Equations, Clarendon Press, Oxford, 1977, p. 665. """ function foxgood(::Type{T}, n::Integer, matrixonly = true) where T h = T(1/n) t = h*(T[1:n;] .- one(T)/2) A = h*sqrt.((t.^2)*ones(T,n)' + ones(T, n) * (t.^2)') if matrixonly return A else x = t b = zeros(T, n) for i in 1:n b[i] = ((one(T) + t[i]^2)^T(1.5) - t[i]^3)/3 end return RegProb(A, b, x) end end foxgood(args...) = foxgood(Float64, args...) foxgood(::Type, args...) = throw(MethodError(foxgood, Tuple(args))) """ Inverse Heat Equation ===================== *Input options:* + [type,] dim, κ, [matrixonly]: `dim` is the dimension of the matrix and `dim` must be even. `κ` controls the ill-conditioning of the matrix. (`κ = 5` gives a well-conditioned problem and `κ = 1` gives an ill conditoned problem). If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). + [type,] n, [matrixonly]: `κ = 1`. *Groups:* ["regprob"] *References:* **A. S. Carasso**, Determining surface temperatures from interior observations, SIAM J. Appl. Math. 42 (1982), 558-574. """ function heat(::Type{T}, n::Integer, κ::Real, matrixonly::Bool = true) where T mod(n, 2) == 0 || error("The dimension of the matrix must be even.") h = one(T)/n; t = T[h/2:h:1;] c = h/(2*κ*sqrt(π)) d = one(T)/(4*κ^2) # compute the matrix A m = length(t); k = zeros(T, m) [k[i] = c*t[i]^(-1.5)*exp(-d/t[i]) for i in 1:m] r = zeros(T, m); r[1] = k[1] A = toeplitz(T, k, r) if matrixonly return A else # compute the vectors x and b x = zeros(T, n) for i = 1:div(n,2) ti = i*20/n if ti < 2 x[i] = 0.75*ti^2/4 elseif ti < 3 x[i] = 0.75 + (ti - 2)*(3 - ti) else x[i] = 0.75*exp(-(ti - 3)*2) end end x[div(n,2)+1:n] = zeros(T, div(n, 2)) b = A*x return RegProb(A, b, x) end end heat(::Type{T}, n::Integer, matrixonly::Bool = true) where T = heat(T, n, 1, matrixonly) heat(args...) = heat(Float64, args...) heat(::Type, args...) = throw(MethodError(heat, Tuple(args))) """ Fredholm Integral Equation of the First Kind ============================================ *Input options:* + [type,] dim, [matrixonly]: the dimension of the matrix is `dim`. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **M. L. Baart**, The use of auto-correlation for pesudo-rank determination in noisy ill-conditioned linear-squares problems, IMA, J. Numer. Anal. 2 (1982), 241-247. """ function baart(::Type{T}, n::Integer, matrixonly::Bool = true) where T mod(n, 2) == 0 || error("The dimension of the matrix must be even.") hs = T(π/(2*n)) ht = T(π/n) c = one(T)/(3*sqrt(2)) A = zeros(T, n, n) ihs = T[0:n;]*hs n1 = n + 1 nh = div(n,2) f3 = exp.(ihs[2:n1]) .- exp.(ihs[1:n]) # compute A for j = 1:n f1 = f3 co2 = cos((j - one(T)/2)*ht) co3 = cos(j*ht) f2 = (exp.(ihs[2:n1].*co2) .- exp.(ihs[1:n].*co2))./co2 if j == nh f3 = hs*ones(T, n) else f3 = (exp.(ihs[2:n1].*co3) .- exp.(ihs[1:n].*co3))./co3 end A[:,j] .= c.*(f1 .+ 4 .* f2 .+ f3) end if matrixonly return A else # compute vector b si = T[.5:.5:n;] .* hs si = sinh.(si) ./ si b = zeros(T, n) b[1] = 1 + 4 * si[1] + si[2] b[2:n] .= si[2:2:2*n-2] .+ 4 .* si[3:2:2*n-1] .+ si[4:2:2*n] b .= b .* sqrt(hs) ./ 3 # compute vector x x = -diff(cos.(T[0:n;] .* ht)) ./ sqrt(ht) return RegProb(A, b, x) end end baart(args...) = baart(Float64, args...) baart(::Type, args...) = throw(MethodError(baart, Tuple(args))) """ Phillips's \"Famous\" Problem ============================= *Input options:* + [type,] dim, [matrixonly]: the dimension of the matrix is `dim`. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **D. L. Phillips**, A technique for the numerical solution of certain integral equations of the first kind, J. ACM 9 (1962), 84-97. """ function phillips(::Type{T}, n::Integer, matrixonly::Bool = true) where T mod(n, 4) == 0 || error("The dimension of the matrix must be a multiple of 4.") # compute A h = 12/n n4 = div(n, 4) r1 = zeros(T,n) c = cos.(T[-1:n4; ] * 4 * π/n) for i in 1:n4 r1[i] = h + 9 / (h * π^2) * (2 * c[i + 1] - c[i] - c[i + 2]) end r1[n4 + 1] = h / 2 + 9 / (h * π^2) * (cos(4 * π / n) - 1) A = toeplitz(T, r1) if matrixonly return A else # compute the vector b b = zeros(T, n) c = π/3 for i = (div(n,2) + 1):n t1 = -6 + i*h t2 = t1 - h b[i] = t1*(6-abs(t1)/2) + ((3 - abs(t1)/2)*sin(c*t1) - 2/c*(cos(c*t1) - one(T)))/c - t2*(6 - abs(t2)/2) - ((3 - abs(t2)/2)*sin(c*t2) - 2/c*(cos(c*t2) - one(T)))/c b[n - i + 1] = b[i] end b ./= sqrt(h) # compute x x = zeros(T, n) x[2n4+1:3n4] = (h .+ diff(sin.(T[0:h:(3 + 10 * eps(T));] * c)) / c) / sqrt(h) x[n4+1:2*n4] = x[3*n4:-1:2*n4+1] return RegProb(A, b, x) end end phillips(args...) = phillips(Float64, args...) phillips(::Type, args...) = throw(MethodError(phillips, Tuple(args))) # replicates the grid vectors xgv and ygv to produce a full grid. function meshgrid(xgv, ygv) X = [i for j in ygv, i in xgv] Y = [j for j in ygv, i in xgv] return X, Y end # MATLAB rounding behavior # This is equivalent to RoundNearestTiesAway # and it can be used for both Julia v0.3, v0.4 function round_matlab(x::AbstractFloat) y = trunc(x) ifelse(x==y,y,trunc(2*x-y)) end round_matlab(::Type{T}, x::AbstractFloat) where T<:Integer = trunc(T,round_matlab(x)) """ One-dimensional Gravity Surverying Problem ========================================== Discretization of a 1-D model problem in gravity surveying, in which a mass distribution f(t) is located at depth d, while the vertical component of the gravity field g(s) is measured at the surface. *Input options:* + [type,] dim, example, a, b, d, [matrixonly]: `dim` is the dimension of the matrix. Three examples are implemented. (a) example = 1 gives f(t) = sin(π*t) + 0.5*sin(2*π*t). (b) example = 2 gives f(t) = piecewise linear function. (c) example = 3 gives f(t) = piecewise constant function. The t integration interval is fixed to [0, 1], while the s integration interval [a, b] can be specified by the user. The parameter d is the depth at which the magnetic deposit is located. The larger the d, the faster the decay of the singular values. If matrixonly = false, the matrix A and vectors b and x in the linear system Ax = b will be generated (matrixonly = true by default). + [type,] dim, example, [matrixonly]: `a = 0, b = 1, d = 0.25`; + [type,] dim, [matrixonly]: `example = 1, a = 0, b = 1, d = 0.25`. *Groups:* ["regprob"] *References:* **G. M. Wing and J. D. Zahrt**, A Primer on Integral Equations of the First Kind, Society for Industrial and Applied Mathematics, Philadelphia, 1991, p. 17. """ function gravity(::Type{T}, n::Integer, example::Integer, a::Number, b::Number, d::Number, matrixonly::Bool = true) where T dt = one(T)/n a = T(a) b = T(b) d = T(d) ds = (b - a)/n tv = dt .* (T[1:n;] .- one(T) ./ 2) sv = a .+ ds .* (T[1:n;] .- one(T) ./ 2) Tm, Sm = meshgrid(tv, sv) A = dt .* d .* ones(T, n, n) ./ (d^2 .+ (Sm .- Tm).^2).^T(3/2) if matrixonly return A else x = ones(T, n) nt = round_matlab(Int, n/3) nn = round_matlab(Int, n*7/8) if example == 1 x .= sin.(π .* tv) .+ sin.(2 .* π .* tv) ./ 2 elseif example == 2 x[1:nt] .= 2 ./ nt .* [1:nt;] x[(nt + 1):nn] .= ((2 .* nn .- nt) .- [(nt .+ 1):nn;]) ./ (nn .- nt) x[(nn + 1):n] .= (n .- [(nn .+ 1):n;]) ./ (n .- nn) elseif example == 3 x[1:nt] .= 2 else error("Illegal value of example") end b = A*x return RegProb(A, b, x) end end gravity(::Type{T}, n::Integer, example::Integer, matrixonly::Bool = true) where T = gravity(T, n, example, 0, 1, 0.25, matrixonly) gravity(::Type{T}, n::Integer, matrixonly::Bool = true) where T = gravity(T, n, 1, 0, 1, 0.25, matrixonly) gravity(args...) = gravity(Float64, args...) gravity(::Type, args...) = throw(MethodError(gravity, Tuple(args))) """ Image Deblurring Test Problem ============================= The generated matrix A is an `n*n-by-n*n` sparse, symmetric, doubly block Toeplitz matrix that models blurring of an n-by-n image by a Gaussian point spread function. *Input options:* + [type,] dim, band, σ, [matrixonly]: the dimension of the matrix is `dim^2`. `band` is the half-bandwidth, only matrix elements within a distance `band-1` from the diagonal are nonzero. `σ` controls the width of the Gaussin point spread function. The larger the `σ`, the wider the function and the more ill posed the problem. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). + [type,] dim, [matrixonly]: `band = 3, σ = 0.7`. *Groups:* ["regprob", "sparse"] """ function blur(::Type{T}, n::Integer, band::Integer, σ::Number, matrixonly::Bool = true) where T σ = T(σ) z = [exp.(-(T[0:band-1;].^2) / (2 * σ^2)); zeros(T, n - band)] A = toeplitz(T, z) A = sparse(A) A = (1 / T(2 * π * σ^2)) * kron(A, A) if matrixonly return A else # start with an image of all zeros n2 = round_matlab(Int, n/2) n3 = round_matlab(Int, n/3) n6 = round_matlab(Int, n/6) n12 = round_matlab(Int, n/12) m = max(n, 2 * n6 + 1 + n2 + n12) x = zeros(T, m, m) # add a large ellipse Te = zeros(T, n6, n3) for i = 1:n6 for j = 1:n3 if (i / n6)^2 + (j / n3)^2 < 1 Te[i,j] = 1 end end end Te = [reverse(Te, dims=2) Te;] Te = [reverse(Te, dims=1); Te] x[2 .+ [1:2n6;], n3 - 1 .+ [1:2n3;]] = Te # add a smaller ellipse Te = zeros(T, n6, n3) for i = 1:n6 for j = 1:n3 if (i / n6)^2 + (j / n3)^2 < 0.6 Te[i,j] = 1 end end end Te = [reverse(Te, dims=2) Te;] Te = [reverse(Te, dims=1); Te] x[n6 .+ [1:2n6;], n3 - 1 .+ [1:2n3;]] = x[n6 .+ [1:2n6;], n3 - 1 .+ [1:2n3;]] .+ 2Te x[findall((i) -> i==3, x)] .= 2 # Add a triangle Te = triu(ones(T, n3, n3)) mT, nT = size(Te) x[n3 + n12 .+ [1:nT;], 1 .+ [1:mT;]] = 3Te # add a cross Te = zeros(T, 2 * n6 + 1, 2 * n6 + 1) mT, nT = size(Te) Te[n6+1, 1:nT] = ones(T, nT) Te[1:mT, n6+1] = ones(T, mT) x[n2 + n12 .+ [1:mT;], n2 .+ [1:nT;]] = 4Te x = reshape(x[1:n, 1:n], n^2) b = A * x return RegProb(A, b, x) end end blur(::Type{T}, n::Integer, matrixonly::Bool = true) where T = blur(T, n, 3, 0.7, matrixonly) blur(args...) = blur(Float64, args...) blur(::Type, args...) = throw(MethodError(blur, Tuple(args))) """ Inverse Laplace Transformation """ function ilaplace(::Type{T}, n::Integer) where T end """ Stellar Parallax Problem with 26 Fixed, Real Observations ========================================================= The underlying problem is a Fredholm integral equation of the first kind with kernel `K(s,t) = (1/(σ√(2π)))*exp(-0.5*((s-t)/σ)^2)`, with `σ = 0.014234`, and it is dscretized by means of a Galerkin method with `n` orthonormal basis functions. The right-hand side `b` consists of a measured distribution function of stellar parallaxes, and its length is fixed at `26`, i.e, the matrix `A` is `26×n`. The exact solution, which represents the true distribution of stellar parallaxes, is unknown. *Input options:* + [type,] dim, [matrixonly]: the generated matrix is `26×dim`. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **W. M. Smart**, Stellar Dynamics, Cambridge University Press, Cambridge, (1938), p. 30. """ function parallax(::Type{T}, n::Integer, matrixonly::Bool=true) where T # Initialization a = zero(T) b = T(0.1) m = 26 σ = T(0.014234) hs = T(0.130/m) hx = (b-a)/n hsh = hs/2 hxh = hx/2 ss = (-T(0.03) .+ T[0:m-1;] * hs) * ones(T, n)' xx = ones(T, m) * (a .+ T[0:n-1;]' * hx) # compute matrix A A = 16exp.(-T(0.5).*((ss .+ hsh .- xx .- hxh)./σ).^2) A .+= 4(exp.(-T(0.5).*((ss .+ hsh .- xx)./σ).^2) .+ exp.(-T(0.5).*((ss .+ hsh .- xx .- hx)./σ).^2) .+ exp.(-T(0.5).*((ss .- xx .- hxh)./σ).^2) .+ exp.(-T(0.5).*((ss .+ hs .- xx .- hxh)./σ).^2)) A .+= (exp.(-T(0.5).*((ss .- xx)./σ).^2) .+ exp.(-T(0.5).*((ss .+ hs .- xx)./σ).^2) .+ exp.(-T(0.5).*((ss .- xx .- hx)./σ).^2) .+ exp.(-T(0.5).*((ss .+ hs .- xx .- hx)./σ).^2)) A = T(sqrt(hs*hx)/(36*σ*sqrt(2*π)))*A if matrixonly return A else # compute b b = T[3;7;7;17;27;39;46;51;56;50;43;45;43;32;33;29; 21;12;17;13;15;12;6;6;5;5]/T(sqrt(hs)*640) return RegProbNoSolution(A,b) end end parallax(args...) = parallax(Float64, args...) parallax(::Type, args...) = throw(MethodError(parallax, Tuple(args))) """ Test Problem with \"Spike\" Solution ==================================== Artificially generated discrete ill-posed problem. *Input options:* + [type,] dim, t_max, [matrixonly]: `dim` is the dimension of the matrix. `t_max` controls the length of the pulse train. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will be generated (`matrixonly = true` by default). The solution x consists a unit step at t = .5 and a pulse train of spike of decreasing magnitude at t = .5, 1.5, 2.5, .... + [type,] dim, [matrixonly]: `t_max = 5`. *Groups:* ["regprob"] """ function spikes(::Type{T}, n::Integer, t_max::Integer, matrixonly::Bool = true) where T del = convert(T, t_max/n) # compute A t, sigma = meshgrid(T[del:del:t_max;], T[del:del:t_max;]) A = sigma ./ (2 .* sqrt.(π .* t.^3)) .* exp.(-(sigma.^2) ./ (4 .* t)) if matrixonly return A else # compute b and x heights = 2*ones(T, t_max); heights[1] = 25 heights[2] = 9; heights[3] = 5; heights[4] = 4; heights[5] = 3 x = zeros(T, n); n_h = one(Integer) peak = convert(T, 0.5/t_max); peak_dist = one(T)/ t_max if peak < 1 n_peak = round_matlab(Integer, peak*n) x[n_peak] = heights[n_h] x[n_peak+1:n] = ones(T, n-n_peak) peak = peak + peak_dist; n_h = n_h + one(Integer) end while peak < 1 n_peak = round_matlab(Integer, peak*n) x[n_peak] = heights[n_h] peak = peak + peak_dist; n_h = n_h + 1 end b = A*x return RegProb(A, b, x) end end spikes(::Type{T}, n::Integer, matrixonly::Bool = true) where T = spikes(T, n, 5, matrixonly) spikes(args...) = spikes(Float64, args...) spikes(::Type, args...) = throw(MethodError(spikes, Tuple(args))) # # Two-dimensional tomography problem with sparse matrix # function tomo(::Type{T}, n::Integer) where T end """ Integral Equation with No square Integrable Solution ==================================================== Discretization of a first kind Fredholm integral equation with kernel `K` and right-hand side `g` given by `K(s,t) = 1/(s+t+1), g(s) = 1`, where both integration intervals are `[0, 1]`. The matrix `A` is a Hankel matrix. *Input options:* + [type,] dim, [matrixonly]: `dim` is the dimension of the matrix. If `matrixonly = false`, the matrix A and vectors b and x in the linear system Ax = b will also be generated (`matrixonly = true` by default). *Groups:* ["regprob"] *References:* **F. Ursell**, Introduction to the theory of linear integral equations., Chapter 1 in L. M. Delves & J. Walsh, Numerical Solution of Integral Equations, Clarendon Press, 1974. """ function ursell(::Type{T}, n::Integer, matrixonly::Bool = true) where T r = zeros(T, n); c = copy(r) for k = 1:n d1 = one(T) + (one(T) + k)/n d2 = one(T) + k/n d3 = one(T) + (k - one(T))/n c[k] = n*(d1*log(d1) + d3*log(d3) - 2*d2*log(d2)) e1 = one(T) + (n+k)/n e2 = one(T) + (n+k-one(T))/n e3 = one(T) + (n+k-2)/n r[k] = n*(e1*log(e1) + e3*log(e3) - 2*e2*log(e2)) end A = hankel(T, c, r) if matrixonly return A else # compute the right-hand side b b = ones(T,n)/convert(T, sqrt(n)) return RegProbNoSolution(A, b) end end ursell(args...) = ursell(Float64, args...) ursell(::Type, args...) = throw(MethodError(ursell, Tuple(args)))
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
12435
# Exception struct DataError <:Exception msg::String end ## MatrixMarket header abstract type MMProperty end abstract type MMObject <: MMProperty end struct MMObjectMatrix <: MMObject end abstract type MMFormat <: MMProperty end struct MMFormatCoordinate <: MMFormat end struct MMFormatArray <: MMFormat end abstract type MMField <:MMProperty end struct MMFieldReal <: MMField end struct MMFieldComplex <: MMField end struct MMFieldInteger <: MMField end struct MMFieldPattern <: MMField end abstract type MMSymmetry <: MMProperty end struct MMSymmetryGeneral <: MMSymmetry end struct MMSymmetrySymmetric <: MMSymmetry end struct MMSymmetrySkewSymmetric <: MMSymmetry end struct MMSymmetryHermitian <: MMSymmetry end struct MMProperties object::MMObject format::MMFormat field::MMField symmetry::MMSymmetry end mutable struct MetaInfo m::Int # number of rows n::Int # number of columns nnz::Int # number of nonzeros in sparse matrix dnz::Int # number of nonzero data items in file (half of nnz for symmetric) kind::String # category of problem date::Int # the Julian year number e.g. 2018 title::AbstractString # author::AbstractString # ed::AbstractString # editor fields::AbstractString # names of metadata and files like :A, :b, :x notes::AbstractString # list of relevant words in notes # the following data are obtained from suite sparse index file ss_index.mat nnzdiag::Int # number of zeros in diagonal pattern_symmetry::Float64 # [0..1] symmetry of non-zero element patterns numerical_symmetry::Float64 # [0..1] symmetry regarding A[i,j] == A[j,i] posdef::Bool # Matrix is positive definite 1 (and symmetric/hermitian) isND::Bool # problem comes form 2D/3D discretization isGraph::Bool # problem is best considered as a graph than a system of equations cholcand::Bool # matrix is symmetric (Hermitian if complex) and diagonal is positive amd_lnz::Int # -2 if not square, -1 if not computed, else estimation for factorization amd_vnz::Int # upper bound on the number of entries in L of LU factorization amd_rnz::Int # upper bound on the number of entries in U in LU factorization amd_flops::Int # floating operation count for Cholesky factorization of symm. pattern ncc::Int # number of strongly connected components of graph/bipartite graph of A nblocks::Int # number of blocks in dmperm (MATLAB) sprank::Int # structural rank of A, max number of nonzero entries which can be # permuted to diagonal (dmperm) # the following block of data is not well documented but delivered by suite sparse lowerbandwidth::Int upperbandwidth::Int rcm_lowerbandwidth::Int rcm_upperbandwidth::Int xmin::ComplexF64 xmax::ComplexF64 # the following data are derived from the singular value decomposition of A svdok::Bool # singular value decomposition was successful - data available norm::Float64 # maximal SV minsv::Float64 # minimal positive SV cond::Float64 # condition number in 2-norm (norm/minsv) rank::Int # numerical rank (num. of SV > tol = max(m,n) * eps(norm) nullspace::Int # dimension of null space of A = min(m,n) - rank svgap::Float64 # SV[rank]/SV[rank+1] if length(sv), else Inf svdstatus::String # "" if no SV data available, "OK" if converged, or a warning text svdhow::String # "text describing how svd values was calculated" sv::Vector{Float64} # singular values > 0 end ## Matrix objects struct RemoteParameters site::String dataurl::String indexurl::String indexgrep::String scan::Tuple extension::String end struct RemoteParametersNew site::String dataurl::String indexurl::String statsdb::String extension::String end abstract type RemoteType end struct SSRemoteType <: RemoteType params::RemoteParametersNew end struct MMRemoteType <: RemoteType params::RemoteParameters end abstract type MatrixData end struct RemoteMatrixData{T<:RemoteType} <:MatrixData name::AbstractString id::Int header::MetaInfo properties::Ref{Union{<:MMProperties,Nothing}} metadata::Vector{AbstractString} function RemoteMatrixData{T}(name, id::Integer, hdr::MetaInfo) where T properties = Ref{Union{<:MMProperties,Nothing}}(nothing) new(name, id, hdr, properties, AbstractString[]) end end struct GeneratedMatrixData{N} <:MatrixData name::AbstractString id::Int func::Function end struct MatrixDatabase data::Dict{AbstractString,MatrixData} aliases::Dict{AbstractString,AbstractString} MatrixDatabase() = new(Dict{AbstractString,MatrixData}(), Dict{AbstractString,AbstractString}()) MatrixDatabase(data, aliases) = new(data, aliases) end Base.show(io::IO, db::MatrixDatabase) = print(io, "MatrixDatabase(", length(db.data), ")") # Patterns const IntOrVec = Union{Integer,AbstractVector{<:Integer}} const AliasArgs = Union{Integer,Colon,AbstractVector{<:Union{Integer,AbstractRange{<:Integer}}}} struct Alias{T,D} data::D Alias{T}(d::D) where {T<:MatrixData,D} = new{T,D}(d) function Alias{T}(d...) where {T<:MatrixData} v = getindex.(convertalias(collect(d))) # strip Ref wrap if necessary Alias{T}(besttype(v)) end end convertalias(a::Integer) = a convertalias(a::Colon) = Ref(a) convertalias(a::AbstractRange{<:Integer}) = Ref(a) convertalias(a::AbstractVector) = begin x = (vcat(convertalias.(a)...)); length(x) == 1 ? x[1] : x end besttype(a::AbstractVector{T}) where T<:Integer = a besttype(a::AbstractVector{T}) where T<:AbstractRange = a besttype(a::AbstractVector{Any}) = (:) in a ? (:) : Vector{Union{Integer,AbstractRange}}(a) struct Alternate{T<:RemoteType,P} pattern::P end abstract type AbstractNot end const Pattern = Union{Function,AbstractString,Regex,Symbol,Alias, Alternate,AbstractVector,Tuple,AbstractNot} struct Not{T<:Pattern} <:AbstractNot pattern::T end """ MatrixDescriptor{T<:MatrixData} Access object which is created by a call to `mdopen(::Pattern)`. Several user functions allow to access data according to the unique pattern. Keeps data cache for exactly the same calling arguments (in the case of generated objects). For remote objects the data cache keeps all available metadata. """ struct MatrixDescriptor{T<:MatrixData} data::T args::Tuple cache::Union{Ref,Dict} end function MatrixDescriptor(data::T) where T<:RemoteMatrixData MatrixDescriptor{T}(data, (), Dict()) end function MatrixDescriptor(data::T, args...) where T<:GeneratedMatrixData MatrixDescriptor{T}(data, deepcopy(args), Ref{Any}(nothing)) end struct Auxiliary{T<:MatrixDescriptor} md::T end # essential functions of the types function Base.show(io::IO, data::RemoteMatrixData) hd = data.header prop = data.properties[] print(io, "(") print(io, prop === nothing ? "" : string(prop, " ") ) print(io, "$(data.name)($(aliasname(data))) ") nnz = hd.nnz == hd.dnz ? "$(hd.nnz)" : "$(hd.nnz)/$(hd.dnz)" print(io, " $(hd.m)x$(hd.n)($nnz) ") print(io, data.date != 0 ? data.date : "") meta = join(metastring.(data.name, getmeta(data)), ", ") n = length(meta) if n > 40 meta = string(meta[1:17], " ... ", meta[end-17:end]) end print(io, " [", meta, "]") print(io, " '", data.kind, "'") print(io, " [", data.title, "]") print(io, ")") end function Base.show(io::IO, mdesc::MatrixDescriptor) show(io, mdesc.data) show(io, mdesc.args) end function Base.push!(db::MatrixDatabase, data::MatrixData) key = data.name db.data[data.name] = data db.aliases[aliasname(data)] = key end """ aliasname(data::MatrixData) aliasname(Type{<:MatrixData, id::Integer) return alias name derived from integer id """ aliasname(::Type{RemoteMatrixData{SSRemoteType}}, i::Integer) = string('#', i) aliasname(::Type{RemoteMatrixData{MMRemoteType}}, i::Integer) = string('#', 'M', i) aliasname(::Type{GeneratedMatrixData{N}}, i::Integer) where N = string('#', N, i) function aliasname(T::Type{<:MatrixData}, r::AbstractVector) aliasname.(T, [ x for x in Iterators.flatten(r) if x > 0]) end aliasname(T::Type{<:MatrixData}, ::Colon) = aliasname(T, 0) aliasname(data::MatrixData) = aliasname(typeof(data), data.id) aliasname(ali::Alias{T,D}) where {T,D} = aliasname(T, ali.data) Base.show(io::IO, a::Alias) = print(io, aliasname(a)) import Base: == ==(a::S, b::T) where {R,S<:Alias{R},T<:Alias{R}} = aliasname(a) == aliasname(b) Base.empty!(db::MatrixDatabase) = (empty!(db.aliases); empty!(db.data)) localindex(::SSRemoteType) = abspath(data_dir(), "ss_index.mat") localindex(::MMRemoteType) = abspath(data_dir(), "mm_matrices.html") function sitename(s::AbstractString, t::AbstractString) p = split(s, '/') string((length(p) >= 3 ? p[3] : s), " with ", t, " index") end remote_name(s::SSRemoteType) = sitename(s.params.site, "MAT") remote_name(s::MMRemoteType) = sitename(s.params.site, "HTML") localbase(::Type{SSRemoteType}) = abspath(data_dir(), "uf") localbase(::Type{MMRemoteType}) = abspath(data_dir(), "mm") localdir(data::RemoteMatrixData{T}) where T = abspath(localbase(T), filename(data)) localdir(data::MatrixData) = nothing indexurl(remote::RemoteType) = remote.params.indexurl dataurl(remote::RemoteType) = remote.params.dataurl dataurl(::Type{T}) where T<:RemoteType = dataurl(preferred(T)) extension(::Type{T}) where T<:RemoteType = extension(preferred(T)) extension(remote::RemoteType) = remote.params.extension dataurl(data::RemoteMatrixData{T}) where T = join((dataurl(T), data.name), '/') * extension(T) siteurl(data::RemoteMatrixData{T}) where T = preferred(T).params.site filename(data::RemoteMatrixData) = joinpath(split(data.name, '/')...) localfile(data::RemoteMatrixData{<:SSRemoteType}) = localdir(data) * ".tar.gz" localfile(data::RemoteMatrixData{MMRemoteType}) = localdir(data) * ".mtx.gz" function matrixfile(data::RemoteMatrixData{<:SSRemoteType}) joinpath(localdir(data), rsplit(data.name, '/', limit=2)[end] * ".mtx") end matrixfile(data::RemoteMatrixData{MMRemoteType}) = localdir(data) * ".mtx" function matrixinfofile(data::RemoteMatrixData) string(rsplit(matrixfile(data), '.', limit=2)[1], ".info") end ## MatrixMarket header mm_property_name(::MMObjectMatrix) = "matrix" mm_property_name(::MMFormatCoordinate) = "coordinate" mm_property_name(::MMFormatArray) = "array" mm_property_name(::MMFieldReal) = "real" mm_property_name(::MMFieldComplex) = "complex" mm_property_name(::MMFieldInteger) = "integer" mm_property_name(::MMFieldPattern) = "pattern" mm_property_name(::MMSymmetryGeneral) = "general" mm_property_name(::MMSymmetrySymmetric) = "symmetric" mm_property_name(::MMSymmetrySkewSymmetric) = "skew-symmetric" mm_property_name(::MMSymmetryHermitian) = "hermitian" mm_property_type(::MMFieldReal) = Float64 mm_property_type(::MMFieldComplex) = ComplexF64 mm_property_type(::MMFieldInteger) = Integer mm_property_type(::MMFieldPattern) = Bool MM_NAME_TO_PROP = Dict{String,MMProperty}(mm_property_name(x) => x for x in ( MMObjectMatrix(), MMFormatCoordinate(), MMFormatArray(), MMFieldReal(), MMFieldComplex(), MMFieldInteger(), MMFieldPattern(), MMSymmetryGeneral(), MMSymmetrySymmetric(), MMSymmetrySkewSymmetric(), MMSymmetryHermitian()) ) MMProperties() = MMProperties("matrix", "coordinate", "real", "general") function MMProperties(args::AbstractString...) prop(x) = MM_NAME_TO_PROP[lowercase(x)] MMProperties(prop.(args)...) end Base.show(io::IO, pr::MMProperty) = print(io, mm_property_name(pr)) function Base.show(io::IO, mp::MMProperties) mms(pr::MMProperty) = mm_short_name(pr) print(io, #= mms(mp.object), mms(mp.format),=# mms(mp.field), mms(mp.symmetry)) end mm_short_name(pr::MMSymmetrySkewSymmetric) = "K" mm_short_name(pr::MMProperty) = uppercase(first(mm_property_name(pr))) """ flattenPattern(p::Pattern) return the vector of all elementary patterns, contained in the pattern. """ flatten_pattern(p::Pattern) = collect(Set(_flatten_pattern(p))) _flatten_pattern(::Tuple{}) = [] _flatten_pattern(p::Union{AbstractVector,Tuple}) = Iterators.flatten(_flatten_pattern.(p)) _flatten_pattern(p::Not) = [p.pattern] _flatten_pattern(p::Pattern) = [p]
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
1129
# setup clean and empty directories function save_target(path::AbstractString) base = basename(path) dir = dirname(path) target = abspath(dir, string(base, ".saved")) while isdir(target) target = abspath(target, string(base, ".saved")) end if isdir(path) mv(path, target) end if basename(path) == "data" mkpath(path) cp_if("uf_matrices.html", target, path) cp_if("mm_matrices.html", target, path) cp_if("ss_index.mat", target, path) end target end function cp_if(name::AbstractString, from::AbstractString, to::AbstractString) fromname = abspath(from, name) toname = abspath(to, name) if isfile(fromname) && !MatrixDepot.URL_REDIRECT[] cp(fromname, toname) end end function revert_target(saved::AbstractString, orig::AbstractString) savetest = abspath(dirname(orig), string(basename(orig), ".test")) if isdir(orig) if isdir(savetest) mv(savetest, joinpath(orig, basename(savetest))) end mv(orig, savetest) end if isdir(saved) mv(saved, orig) end end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
7896
@test mdinfo() !== nothing groups = ["symmetric", "inverse", "illcond", "posdef", "eigen","sparse", "random", "regprob", "all"] for group in groups @test !isempty(listnames(Symbol(group))) end @test_throws DataError matrixdepot("something") n = rand(1:55) name = mdlist(builtin(n)) @test mdinfo(name) !== nothing nlist = mdlist(builtin([1, 3]) | builtin(4:20)) m = length(mdlist("**")) @test isempty(mdinfo(builtin(m+1))) setgroup!(:newlist, builtin(3:6) | builtin(20)) @test mdlist(:newlist) == mdlist(builtin(3:6,20)) deletegroup!(:newlist) # testing the new API # # it is assumed that all matrices are generated during "test/download.jl" # and the builtin- and user-defined "randsym" but no others are available # @testset "mdlist" begin REM = length(mdlist("*/*")) @test REM >= 2500 #@test REM in [2757, 2856] # depends on whether UFL or TAMU url has been used @test length(mdlist(:builtin)) == 59 @test mdlist(:user) == String["randsym"] @test mdlist("") == [] @test mdlist("**") == mdlist(:) == mdlist(()) == sort!(collect(keys(MatrixDepot.MATRIX_DB.data))) @test mdlist("HB/1138_bus") == ["HB/1138_bus"] @test mdlist(sp(1)) == ["HB/1138_bus"] @test mdlist(mm(1)) == ["Harwell-Boeing/psadmit/1138_bus"] @test sort(mdlist(sp(:))) == mdlist("*/*") @test sort(mdlist(mm(1:1000))) == mdlist("*/*/*") @test mdlist(builtin(:)) == mdlist(isbuiltin) @test mdlist(user(:)) == mdlist(isuser) @test mdlist("*") == mdlist(islocal) @test length(mdlist("HB/*")) == 292 @test mdlist("HB**") == mdlist("HB/**") @test_throws ArgumentError listdir("*/*") @test listdir("Harwell-Boeing//") == ["Harwell-Boeing/*/* - (292)"] @test mdlist("*/hamm/*") == ["misc/hamm/add20", "misc/hamm/add32", "misc/hamm/memplus"] @test mdlist("*/hamm/*a*3?") == ["misc/hamm/add32"] @test mdlist("*/hamm/*a*3[123]") == ["misc/hamm/add32"] @test mdlist("*/hamm/*a*3[123]?") == [] @test length(mdlist("*/*/*")) == 498 @test listdir("*//*/*") == ["Harwell-Boeing/*/* - (292)", "NEP/*/* - (73)", "SPARSKIT/*/* - (107)", "misc/*/* - (26)"] @test listdir("//*") == ["/* - ($(length(mdlist(:local))))"] @test listdir("//*/*") == ["/*/* - ($REM)"] @test listdir("//*/*/*") == ["/*/*/* - (498)"] @test listdir("HB/") == ["HB/* - (292)"] @test length(mdlist("Harwell-Boeing/*/*")) == 292 @test mdlist(r".*ng/ma.*") == ["Harwell-Boeing/manteuffel/man_5976"] @test mdlist(sp(2001:2002)) == ["JGD_Groebner/c8_mat11_I", "JGD_Groebner/f855_mat9"] @test length(mdlist(sp(2757:3000))) == REM - 2756 @test_throws ArgumentError mdlist(:xxx) @test length(mdlist(isremote)) == REM + 498 @test length(mdlist(isloaded)) + length(mdlist(isunloaded)) == length(mdlist(isremote)) @test length(mdlist(isbuiltin)) + length(mdlist(isuser)) == length(mdlist(islocal)) @test length(mdlist(islocal)) + length(mdlist(isremote)) == length(mdlist(:all)) @test length(mdlist("**")) == length(mdlist("*")) + length(mdlist("*/*")) + length(mdlist("*/*/*")) @test mdlist(:all) == mdlist("**") @test length(mdlist(:symmetric)) == 21 @test length(mdlist(:illcond)) == 20 # intersections and unions @test mdlist((:posdef, :sparse)) == ["poisson", "wathen"] @test length(mdlist([:posdef,:sparse])) + length(mdlist((:posdef,:sparse))) == length(mdlist(:posdef)) + length(mdlist(:sparse)) # predicates of remote and local matrices @test length(mdlist(issymmetric)) == 29 @test length(mdlist(:symmetric & "kahan")) == 0 @test length(mdlist(:symmetric & "hankel")) == 1 @test mdlist(:local) == mdlist(islocal) @test mdlist(:builtin) == mdlist(isbuiltin) @test mdlist(:user) == mdlist(isuser) @test mdlist(:symmetric) == mdlist(issymmetric & islocal) # general metadata @test length(mdlist(@pred(m < 10000) & "HB/*")) == 284 # items with m < * @test length(mdlist(@pred(m < 10000) & isloaded)) == 10 # items with m < * @test length(mdlist(@pred(n < 10000) & "HB/*")) == 283 # items with n < * @test length(mdlist(@pred(n < 10000) & isloaded)) == 9 # items with n < * @test length(mdlist(@pred(nnz < 5000) & "HB/*")) == 163 # items with nnz < * @test length(mdlist(@pred(nnz < 5000) & isloaded)) == 2 # items with nnz < * @test length(mdlist(@pred(m > n) & "HB/*")) == 9 # items with m > n @test length(mdlist(@pred(m > n) & isloaded)) == 0 # items with m > n # metadata from header files @test length(mdlist(@pred(occursin("problem", kind)) & isloaded)) == 6 @test length(mdlist(keyword("graph") & isloaded)) == 2 @test length(mdlist(@pred(0 < date <= 1990) & isloaded)) == 1 @test length(mdlist(@pred(date >= 2006) & @pred(0 < date <= 2006) & isloaded)) == 2 @test length(mdlist(@pred(date == 0) & mm(:) & isloaded)) == 3 # metadata from ss_index.mat @test length(mdlist(@pred(posdef) & "HB/*")) == 60 @test length(mdlist(isposdef)) >= 60 @test mdlist(@pred(posdef)) == mdlist(isposdef & isremote) @test mdlist(:posdef) == mdlist(isposdef & islocal) @test length(mdlist(isloaded & MatrixDepot.prednzdev(0.0))) == 0 # metadata from svd files @test mdlist(@pred(svdok)) == ["HB/1138_bus"] data = mdopen("HB/1138_bus").data @test length(data.sv) > 0 @test data.cond > 8.0e6 @test data.norm > 30000 @test data.rank == 1138 @test data.svgap == Inf @test data.cholcand end @testset "aliases" begin @test mm(:) == mm(:, 1) @test mm([1,2,3]) == mm(1,2,3) == mm(1, 2:3) == mm([1:2],3) == mm([1:2,3]) @test mdlist(mm(:)) == mdlist(mm(1:1000)) @test mm(1:2, 4:5) == mm(1,2,4,5) end @testset "logical" begin # for the boolean syntax @test mdlist(~islocal) == mdlist(isremote) @test length(mdlist(isloaded & issymmetric)) == 7 @test length(mdlist(isloaded & ~issymmetric)) == 4 @test length(mdlist(isloaded & ~issymmetric | isuser & issymmetric)) == 5 @test length(mdlist(!islocal & issymmetric | isuser & issymmetric)) == 9 @test mdlist(islocal & ~isbuiltin) == mdlist(isuser) @test mdlist(islocal & ~isbuiltin) == mdlist(isuser) @test "a" & "b" === ("a", "b") @test ~"a" & "b" === (~"a", "b") @test ~"a" * "b" === ~"ab" @test ~"ab" === ~'a' * 'b' @test ~~islocal === islocal @test mdlist(~"*a*" & ~ "*e*") == mdlist(~["*a*", "*e*"]) @test mdlist(()) == mdlist(:all) @test "a" & r"b" == ("a", r"b") @test "a" & r"b" & "c" == ("a", r"b", "c") @test "a" | r"b" == ["a", r"b"] @test "a" | r"b" | "c" == ["a", r"b", "c"] @test mdlist(islocal & ~("*a*" | "*e*")) == mdlist(:local & ~"*a*" & ~ "*e*") @test "a" & ( "b" & "c" ) == ("a", "b", "c") @test "a" | ( "b" | "c" ) == ["a", "b", "c"] @test_throws ArgumentError mdlist([] & :invalid_group_name) @test MatrixDepot.mdlist(builtin(10, 1:7, 3)) == ["baart", "binomial", "blur", "cauchy", "chebspec", "chow", "circul", "deriv2"] @test MatrixDepot.fname(sin) == "unknown-function" @test_throws MethodError mdopen("baart", 10, 11) end @testset "charfun" begin data = mdopen("vand", 10).data @test charfun(())(data) @test charfun(isbuiltin)(data) @test charfun(isbuiltin)(data.name) @test charfun(:)("unknown") == false end @testset "properties" begin md = mdopen("gravity", 10) io = IOBuffer() @test show(io, md) === nothing @test propertynames(md) == [:A, :m, :n, :nnz, :dnz] @test md.A isa AbstractMatrix @test md.nnz == count(md.A .!= 0) @test md.dnz == 0 @test_throws DataError md.x md = mdopen("gravity", 10, false) io = IOBuffer() @test show(io, md) === nothing @test propertynames(md) == [:A, :b, :x, :m, :n, :nnz, :dnz] @test md.A isa AbstractMatrix @test md.b isa AbstractVector @test md.x isa AbstractVector md = mdopen("HB/well1033") io = IOBuffer() @test show(io, md) === nothing @test propertynames(md) == [:A, :b, :m, :n, :nnz, :dnz] @test md.A isa AbstractMatrix @test md.b isa AbstractMatrix @test_throws DataError md.x @test_throws DataError md.invalidname @test_throws ErrorException md.data.invalidname @test md.dnz == md.data.header.nnz @test length(mdlist(keyword("graph" & ("butterfly" | "network")) & isloaded)) == 2 @test length(mdlist(hasdata(:A & (:b | :x)))) == 2 end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
7131
#download import MatrixDepot: load, loadinfo, loadsvd # for test coverage MatrixDepot.update() # verify that no data are downloaded (empty directory) @test mdlist(isloaded) == [] # Suite Sparse @test loadinfo("*/1138_bus") == 1 # load only header @test load("**/1138_bus") == 2 # loaded both versions (sp and mm) @test load("HB/1138_bus") == 0 # count actually loaded @test load("Pajek/Journals") == 1 @test load("wing") == 0 # do not try to load local matrix # Matrix Market @test load("Harwell-Boeing/smtape/bp___200") == 1 @test mdlist(isloaded) == ["HB/1138_bus", "Harwell-Boeing/psadmit/1138_bus", "Harwell-Boeing/smtape/bp___200", "Pajek/Journals"] # read data @test matrixdepot("HB/1138_bus") !== nothing @test mdlist("**/1138_bus") == ["HB/1138_bus", "Harwell-Boeing/psadmit/1138_bus"] @test string(mdinfo("Harwell-Boeing/psadmit/662_bus")) == "# Harwell-Boeing/psadmit/662_bus\n\n" * "###### MatrixMarket matrix coordinate real symmetric\n\n662 662 1568\n" @test loadinfo(MatrixDepot.mdata("HB/1138_bus")) == 0 @test loadinfo(MatrixDepot.mdata("Bates/Chem97Zt")) == 1 @test length(string(mdinfo("Bates/Chem97Zt"))) == 447 # metadata access with old interface @test MatrixDepot.metareader(mdopen("Pajek/Journals"), "Journals.mtx") !== nothing @test_throws DataError MatrixDepot.metareader(mdopen("*/1138_bus"), "1138_bus_b") @test_throws DataError MatrixDepot.metareader(mdopen("that is nothing")) @test load("Bates/C*") == 2 @test mdinfo("Bates/Chem97Zt") !== nothing @test matrixdepot("Bates/Chem97Zt") !== nothing @test "Bates/Chem97Zt" in mdlist(isloaded) @test length(mdlist(isloaded)) == 6 @test load("**/epb0") == 1 @test loadsvd("*/1138_bus") == 1 # matrix market @test load("Harwell-Boeing/lanpro/nos5") == 1 @test length(mdlist(isloaded)) == 8 @test mdopen("Bai/dwg961b") !== nothing mdesc = mdopen("Bai/dwg961b") @test iscomplex(mdesc.data) @test issymmetric(mdesc.data) @test !ishermitian(mdesc.data) @test !isboolean(mdesc.data) @test metasymbols(mdesc) == [:A] @test mdesc.A == matrixdepot("Bai/dwg961b") mdesc = mdopen("Harwell-Boeing/cegb/cegb2802") @test isloaded(mdesc.data) == false @test_throws DataError mdesc.A # an example with rhs and solution mdesc = mdopen("DRIVCAV/cavity14") A1 = mdesc.A @test size(A1) == (2597, 2597) A2 = mdesc.A @test A1 === A2 # cache should be used @test size(mdesc.b, 1) == 2597 @test size(mdesc.x, 1) == 2597 @test_throws DataError mdesc["invlid"] @test_throws DataError mdesc.y # read a format array file @test MatrixDepot.mmreadheader(abspath(MatrixDepot.matrixfile(mdesc.data), "..", string("cavity14_b.mtx"))) !== nothing mdesc = mdopen("blur", 10, false) @test mdesc.A isa AbstractMatrix @test mdesc.b isa AbstractVector @test mdesc.x isa AbstractVector @test_throws DataError mdesc["invlid"] @test_throws DataError mdesc.y @test_throws DataError mdopen(sp(1)).b # no rhs data for this example mdesc = mdopen("*/bfly") @test mdesc["Gname_01.txt"] == "BFLY3\n" @test mdesc("Gname_01.txt") == "BFLY3\n" @test size(mdesc.G_06) == (2048, 2048) @test mdesc.G_06 === mdesc["G_06"] @test mdesc.G_06 === mdesc[Symbol("G_06.mtx")] fn = joinpath(dirname(MatrixDepot.matrixfile(mdesc.data)), "bfly_Gname_01.txt") @test_throws DataError MatrixDepot.mmreadheader(fn) # read from a pipeline io = IOBuffer("%%matrixmarket matrix array real general\n1 1\n2.5\n") @test MatrixDepot.mmread(io) == reshape([2.5], 1, 1) # read from temporary file mktemp() do path, io println(io, "%%MatrixMarket Matrix arRAy real GeneraL") println(io, "% author: willi") println(io) println(io, "% notes:") println(io, "%second Line") println(io); println(io, " ") println(io, "24 2") close(io) @test MatrixDepot.mmreadcomment(path) == "%%MatrixMarket Matrix arRAy real GeneraL\n% author: willi\n\n" * "% notes:\n%second Line\n\n \n24 2\n" @test MatrixDepot.mmreadheader(path) == Dict{Symbol,Any}(:symmetry=>"general",:m=>24,:n=>2,:field=>"real",:format=>"array", :author=>"willi",:notes=>"second Line") end mktemp() do path, io println(io, "%%MatrixMarket Matrix arRAi real GeneraL") println(io, "1 2") close(io) @test_throws DataError MatrixDepot.mmreadheader(path) end mktemp() do path, io println(io, "%%MatrixMarket Matrix array real GeneraL") println(io, "1 2 A") close(io) @test_throws DataError MatrixDepot.mmreadheader(path) end mktemp() do path, io println(io, "%%MatrixMarket Matrix coordinate real GeneraL") println(io, "1 2") close(io) @test_throws DataError MatrixDepot.mmreadheader(path) end @test MatrixDepot.mmreadheader("") === nothing # an example loading a txt file data = mdopen("Pajek/Journals") @test length(MatrixDepot.metareader(data, "Journals_nodename.txt")) > 100 @test length(MatrixDepot.metareader(data, "Journals_nodename.txt")) > 100 # repeat to use cache # reading mtx files io = IOBuffer(""" %%Matrixmarket matrix array real general 2 1 2.1 3.14e0 """) @test MatrixDepot.mmread(io) == reshape([2.1; 3.14], 2, 1) io = IOBuffer(""" %%Matrixmarket matrix array real symmetric 2 2 2.1 3.14e0 4 """) @test MatrixDepot.mmread(io) == [2.1 3.14; 3.14 4.0] io = IOBuffer(""" %%Matrixmarket matrix array real skew-symmetric 2 2 2.1 3.14e0 """) @test MatrixDepot.mmread(io) == [0 -2.1; 2.1 0] # the line containing blanks seemed once to suck when using IOBuffer io = IOBuffer("%%matrixmarket matrix array complex hermitian\n \n2 2\n2.1 0\n.314e+1 1\n+3.0 -0.0\n") @test MatrixDepot.mmread(io) == [2.1 3.14-im; 3.14+im 3] io = IOBuffer(""" %%Matrixmarket matrix coordinate pattern general 2 2 3 1 2 2 1 2 2 """) @test MatrixDepot.mmread(io) == [false true; true true] io = IOBuffer(""" %%Matrixmarket matrix coordinate pattern general 2 2 3 1 2 3 1 2 2 """) @test_throws DataError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matricxmarket matrix array real general 2 1 """) @test_throws Meta.ParseError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matricx array real general 2 1 """) @test_throws Meta.ParseError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix arroy real general 2 1 """) @test_throws Meta.ParseError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array rehal general 2 1 """) @test_throws Meta.ParseError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array real fluffy 2 1 """) @test_throws Meta.ParseError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array real general 2 2 1 2 """) @test_throws BoundsError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array real symmetric 2 1 1 2 """) @test_throws DimensionMismatch MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array real symmetric 2 2 1 2 """) @test_throws BoundsError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array complex hermitian 2 2 1 2 2 3 """) @test_throws BoundsError MatrixDepot.mmread(io) io = IOBuffer(""" %%Matrixmarket matrix array real skew-symmetric 2 2 """) @test_throws BoundsError MatrixDepot.mmread(io)
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
660
@testset "mdalternative interface" begin mpat = "Harwell-Boeing/psadmit/1138_bus" spat = "HB/1138_bus" @test mdlist(mm(spat)) == [mpat] @test mdlist(sp(mpat)) == [spat] @test mdlist(mm(mpat)) == [mpat] @test mdlist(sp(spat)) == [spat] @test mdlist(sp("vand")) == String[] @test mdlist(mm("Sandia/adder_dcop_17")) == String[] s1 = mdlist(sp(mm(:))) @test length(s1) == 455 m1 = mdlist(mm(s1)) @test length(m1) == 455 @test m1 ⊆ mdlist(mm(:)) m2 = mdlist(mm(sp(:))) @test length(m2) == 455 s2 = mdlist(sp(m2)) @test length(s2) == 455 @test s2 ⊆ mdlist(sp(:)) @test m1 == m2 end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
1452
macro inc(a) :(@testset $a begin let n, p, i; include($a) end end) end @testset "MatrixDepot generator tests" begin @inc("test_magic.jl") @inc("test_cauchy.jl") @inc("test_circul.jl") @inc("test_hadamard.jl") @inc("test_hilb.jl") @inc("test_dingdong.jl") @inc("test_frank.jl") @inc("test_invhilb.jl") @inc("test_forsythe.jl") @inc("test_grcar.jl") @inc("test_triw.jl") @inc("test_moler.jl") @inc("test_pascal.jl") @inc("test_kahan.jl") @inc("test_pei.jl") @inc("test_vand.jl") @inc("test_invol.jl") @inc("test_chebspec.jl") @inc("test_lotkin.jl") @inc("test_clement.jl") @inc("test_fiedler.jl") @inc("test_minij.jl") @inc("test_binomial.jl") @inc("test_tridiag.jl") @inc("test_lehmer.jl") @inc("test_parter.jl") @inc("test_chow.jl") @inc("test_randcorr.jl") @inc("test_poisson.jl") @inc("test_neumann.jl") @inc("test_rosser.jl") @inc("test_sampling.jl") @inc("test_wilkinson.jl") @inc("test_rando.jl") @inc("test_randsvd.jl") @inc("test_rohess.jl") @inc("test_kms.jl") @inc("test_wathen.jl") @inc("test_oscillate.jl") @inc("test_toeplitz.jl") @inc("test_hankel.jl") @inc("test_golub.jl") @inc("test_companion.jl") @inc("test_erdrey.jl") @inc("test_gilbert.jl") @inc("test_smallworld.jl") end @testset "regularization methods" begin include("regu.jl") end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
1313
import MatrixDepot: publish_user_generators, include_generator, Group, FunctionName using Logging "random symmetric matrix" function randsym(::Type{T}, n) where T A = zeros(T, n, n) for j = 1:n for i = j:n A[i,j] = randn() end end A = A + tril(A, -1)' return A end randsym(n) = randsym(Float64, n) include_generator(FunctionName, "randsym", randsym) include_generator(Group, :random, randsym) include_generator(Group, :symmetric, randsym) # update the database MatrixDepot.publish_user_generators() n = rand(1:8) @test matrixdepot("randsym", n) !== nothing @test mdinfo("randsym") !== nothing @test "randsym" in MatrixDepot.mdlist(:random) @test "randsym" in MatrixDepot.mdlist(:symmetric) @test_logs min_level=Logging.Warn MatrixDepot.init() n = rand(1:8) @test matrixdepot("randsym", n) !== nothing @test mdinfo("randsym") !== nothing @test mdinfo("randsym") == Base.Docs.doc(randsym) @test "randsym" in MatrixDepot.mdlist(:random) @test "randsym" in MatrixDepot.mdlist(:symmetric) setgroup!(:testgroup, "randsy*") @test mdlist(:testgroup) == ["randsym"] setgroup!(:testgroup, ["*/1138_bus"]) @test mdlist(:testgroup) == ["HB/1138_bus"] deletegroup!(:testgroup) @test_throws ArgumentError mdlist(:testgroup) @test_throws ArgumentError include_generator(Group, :lkjasj, sin)
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
91
n = rand(1:38) @test mdinfo(builtin(n)) !== nothing @test mdinfo(builtin(1:n)) !== nothing
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
84
@test mdinfo(:symmetric | :posdef) !== nothing @test mdinfo(isloaded) !== nothing
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
2731
n = 7 # rand(1:10) r = mdopen("deriv2", n, false) @test r !== nothing && r.A !== nothing rf32 = mdopen("deriv2", Float32, n, false) @test rf32 !== nothing && rf32.A !== nothing r2 = mdopen("deriv2", Float32, n, 2, false) @test r2 !== nothing && r2.b !== nothing @test mdopen("deriv2", Float32, (n ÷ 2) * 2, 3, false).A !== nothing @test_throws ArgumentError matrixdepot("deriv2", Float64, n, 4, false) A = matrixdepot("deriv2", n) @test A == r.A @test r.A*r.x ≈ r.b @test issymmetric(r.A) r = mdopen("shaw", 2*n, false) @test r !== nothing && r.A !== nothing A = matrixdepot("shaw", 2*n) @test A !== nothing # print(r) @test issymmetric(r.A) rf32 = matrixdepot("shaw", Float32, 2*n, false) @test rf32 !== nothing r = mdopen("wing", n, false) @test r !== nothing && r.A !== nothing A = matrixdepot("wing", n) @test A !== nothing && A == r.A @test r.A == matrixdepot("wing", n, 1/3, 2/3, false) r = mdopen("foxgood", n, false) @test r !== nothing && r.A !== nothing rf32 = mdopen("foxgood", Float32, n, false) @test rf32 !== nothing && rf32.A !== nothing A = matrixdepot("foxgood", n) @test A == r.A r = mdopen("heat", Float32, 2*n, false) @test r !== nothing && r.A !== nothing rf32 = matrixdepot("heat", Float32, 2*n) @test rf32 == r.A r = mdopen("baart", 2*n, false) @test r !== nothing && r.b !== nothing rf32 = mdopen("baart", Float32, 2*n, false) @test rf32 !== nothing && rf32.A !== nothing A = matrixdepot("baart", 2*n) @test A == r.A n = 8 # rand(3:10) r = mdopen("phillips", 4*n, false) @test r !== nothing && r.A !== nothing rf32 = matrixdepot("phillips", Float32, 4*n) @test rf32 !== nothing A = matrixdepot("gravity", n) @test A !== nothing @test matrixdepot("gravity", n, 1, 0, 1, 0.25) == A @test mdopen("gravity", Float32, n, 1, false).A !== nothing @test mdopen("gravity", Float32, n, 2, false).A !== nothing @test mdopen("gravity", Float32, n, 3, false).A !== nothing @test_throws ErrorException matrixdepot("gravity", Float32, n, 4, false) A = matrixdepot("blur", n) @test A !== nothing @test matrixdepot("blur", n, 3, 0.7) == A r1 = mdopen("blur", Float32, n, false) @test r1 !== nothing && r1.A !== nothing A = matrixdepot("spikes", n) @test A !== nothing @test matrixdepot("spikes", n, 5) == A n = 7 # rand(5:10) r1 = mdopen("spikes", Float32, n, false) @test r1 !== nothing && r1.A !== nothing A = matrixdepot("ursell", n) @test A !== nothing @test matrixdepot("ursell", Float64, n) == A r1 = mdopen("ursell", Float32, n, false) @test r1 !== nothing && r1.A !== nothing A = matrixdepot("parallax", n) @test A !== nothing m, n = size(A) @test m == 26 @test matrixdepot("parallax", Float64, n) == A r1 = mdopen("parallax", Float32, n, false) @test r1 !== nothing && r1.A !== nothing
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
699
#download from remote site import MatrixDepot: URL_REDIRECT, load, loadinfo, loadsvd # test only for julia nightly if length(VERSION.prerelease) == 0 println("remote tests not executed") else URL_REDIRECT[] = 0 # sp pattern = "*/494_bus" # which has not been touched in other tests @test loadinfo(pattern) == 1 # load only header println("downloading svd for $pattern") @test loadsvd(pattern) == 1 # load svd extension data @test load(pattern) == 1 # loaded full data # Matrix Market pattern = "*/*/494_bus" # which has not been touched in other tests @test loadinfo(pattern) == 1 # load only header @test load(pattern) == 1 # loaded full data end
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
1061
ENV["MATRIXDEPOT_URL_REDIRECT"] = length(VERSION.prerelease) == 0 ? "1" : "1" const basedir = tempname() # tests start with a clean data directory ENV["MATRIXDEPOT_DATA"] = abspath(basedir, "data") using MatrixDepot using Test using LinearAlgebra using SparseArrays import MatrixDepot: DataError # that will download the index files if necessary and initialize internal data MatrixDepot.init() @testset "MatrixDepot.jl" begin include("generators.jl") include("include_generator.jl") @testset "MatrixDepot simulate remote matrix tests" begin tests = [ "download", "common", "number", "property", "downloadmm", ] @testset "$t" for t in tests tp = joinpath(@__DIR__(), "$(t).jl") println("running $(tp) ...") include(tp) println("finished $(tp)") end end @testset "MatrixDepot real remote matrix tests" begin println("running remote.jl ...") include("remote.jl") println("finished remote.jl") end end # testset MatrixDepot.jl
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
201
n = 10 # rand(1:10) @test matrixdepot("binomial", n) == matrixdepot("binomial", Float64, n) A = matrixdepot("binomial", n) @test A*A ≈ 2^(n-1)*Matrix(1.0I, n, n) println("'binomial' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
236
n = 9 # rand(1:10) @test matrixdepot("cauchy", n) == matrixdepot("cauchy", Float64[1:n;]) x = ones(Float64, n) y = x .+ 2 A = zeros(Float64, n, n) fill!(A, 0.25) @test matrixdepot("cauchy", x, y) ≈ A println("'cauchy' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
351
n = 10 # rand(1:10) # no null vector for 1-by-1 chebspec. if n == 1 n = 2 end A = matrixdepot("chebspec", n) # A has null vector ones(n) @test A*ones(n) ≈ zeros(n) atol = 1e-6 B = matrixdepot("chebspec", n, 1) # B's eigenvalues have negative real parts. v = real(eigvals(B)) for i = 1:n @test v[i] < 0 end println("'chebspec' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
235
n = 10 # rand(1:10) @test matrixdepot("chow", n) == matrixdepot("chow", Float64, n) @test matrixdepot("chow",Int, 5, 5, 0)[5,1] == 3125 @test diag(matrixdepot("chow", n, 2, 4)) == ones(Float64, n) * 6 println("'chow' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
292
n = 10 # rand(1:10) A = ones(Float64, n, n) @test matrixdepot("circul", ones(Float64,n)) ≈ A x = [1:n;]; A = matrixdepot("circul", x) # test symmetry @test A + A' == (A + A')' B = matrixdepot("circul", n) C = matrixdepot("circul", [1:n;], n) @test B ≈ C println("'circul' passed test..." )
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
283
n = 9 # rand(1:10) @test matrixdepot("clement", Float64, n) == matrixdepot("clement", n) A = matrixdepot("clement", n) B = matrixdepot("clement", n, 1) @test diag(A+A', 1) == n*ones(n-1) @test issymmetric(Array(B)) θ = matrixdepot("clement", 1) println("'clement' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
212
n = 9 # rand(1:10) A = matrixdepot("companion", Float32, n) @test diag(A, -1) == ones(Float32, n-1) v = [3., 4, 2, 10] B = matrixdepot("companion", v) @test B[:,end] == v println("'companion' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
159
n = 10 # rand(1:10) p = -2*Float64[1:n;] .+ (n + 1.5); C = matrixdepot("cauchy", p) @test matrixdepot("dingdong", n) ≈ C println("'dingdong' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
232
n = 10 # rand(1:10) A = matrixdepot("erdrey", n) B = matrixdepot("erdrey", n, ceil(Int, n*log(n)/2)) @test nnz(A) == nnz(B) @test issymmetric(A) C = matrixdepot("erdrey", 10, 3) @test nnz(C) == 6 println("'erdrey' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
227
n = 10 # rand(1:10) @test matrixdepot("fiedler", n) == matrixdepot("fiedler", [1:n;]) A = matrixdepot("fiedler", n) @test issymmetric(A) for i = 1:n, j =1:n @test A[i,j] ≈ abs(i-j) end println("'fiedler' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
657
n = 10 # rand(1:10) @test matrixdepot("forsythe", n) == matrixdepot("forsythe", n, sqrt(eps(Float64)), zero(Float64)) @test matrixdepot("forsythe", n , 1, 2) == matrixdepot("forsythe", Float64, n, 1, 2) T = Float32 a = convert(T, 3) b = convert(T, 4) @test matrixdepot("forsythe", T, n, 3, 4) == matrixdepot("forsythe", n, a, b) if n != 1 # this test does not apply for n = 1 A = zeros(T, n, n) for i = 1:n, j = 1:n A[i,j] = j == i ? b : j == i + 1 ? 1.0 : (i == n && j == 1) ? a : 0.0 end @test matrixdepot("forsythe", n, a, b) ≈ A end println("'forsythe' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
436
n = 8 # rand(1:10) @test matrixdepot("frank", n) == matrixdepot("frank", Float64, n, 0) A = zeros(Float64, n, n) for i = 1:n, j = 1:n A[i,j] = i<=j ? n + 1 -j : j == i - 1 ? n - j : zero(Float64) end @test matrixdepot("frank", n) ≈ A A = zeros(Float64, n, n) for i = 1:n, j = 1:n A[n+1-j,n+1-i] = i<=j ? n + 1 -j : j == i - 1 ? n - j : zero(Float64) end @test matrixdepot("frank", n, 1) ≈ A println("'frank' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
259
n = 79 # rand(40:100) A = matrixdepot("gilbert", n) @test issymmetric(A) B = matrixdepot("gilbert", n, 0.2) C = matrixdepot("gilbert", Int, n, 0.5) @test nnz(B) <= nnz(C) @test matrixdepot("gilbert", Int, 1) !== nothing println("'gilbert' passed test ...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
160
n = 10 # rand(6:10) A = matrixdepot("golub", n) @test cond(A) > 1.e8 B = matrixdepot("golub", Int, n) @test cond(A) > 1.e8 println("'golub' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
216
n = 7 # rand(3:10) @test matrixdepot("grcar", n, 3) == matrixdepot("grcar", n) A = matrixdepot("grcar", n, n-1) @test istril(A - ones(n,n)) @test istriu(A + diagm(-1 => ones(n-1))) println("'grcar' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
211
let n for n in [2, 4, 16] H = matrixdepot("hadamard", Int, n) @test H*H' == n * Matrix(1.0I, n, n) end @test_throws ArgumentError matrixdepot("hadamard", 0) end println("'hadamard' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
283
A = matrixdepot("hankel", [1:5;]) @test A == matrixdepot("hankel", 5) r1 = rand(5) r2 = rand(5) B = matrixdepot("hankel", r1, r2) @test issymmetric(B) C = matrixdepot("hankel", Int, [1,2,3], [3, 4, 5, 6]) @test C[3,4] == 6 @test C[2,4] == C[3,3] println("'hankel' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
273
n = 10 # rand(1:10) @test matrixdepot("hilb", n) == matrixdepot("hilb", n, n) @test matrixdepot("hilb" , Float16, n) ≈ matrixdepot("hilb", Float32, n) x = Float64[1:n;] y = x .- 1 @test matrixdepot("hilb", n) ≈ matrixdepot("cauchy", x, y) println("'hilb' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
125
n = 10 # rand(1:10) A = matrixdepot("invhilb", n) @test issymmetric(A) @test isposdef(A) println("'invhilb' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
139
n = 7 # rand(1:7) A = matrixdepot("invol", n) # A*A ≈ eye(n) @test A*A ≈ Matrix(1.0I, n, n) atol = 1e-5 println("'invol' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
288
n = 10 # rand(1:10) m = 9 # rand(1:10) @test matrixdepot("kahan", n) == matrixdepot("kahan", n, 1.2, 25.) @test matrixdepot("kahan", m ,n, 4, 5) == matrixdepot("kahan", Float64, m, n, 4, 5) @test matrixdepot("kahan", n, 0.5*pi, 1) ≈ Matrix(1.0I, n,n) println("'kahan' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
269
n = 10 # rand(1:10) A = matrixdepot("kms", n) B = [1:n;]*ones(n)' B = abs.(B - B') B = 0.5.^B @test A ≈ B # test complex number C = [1 2im -4 -8im; -2im 1 2im -4; -4 -2im 1 2im; 8im -4 -2im 1] @test matrixdepot("kms", 4, 2im) ≈ C println("'kms' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
240
n = 10 # rand(1:10) @test matrixdepot("lehmer", Float64, n) == matrixdepot("lehmer", n) A = ones(n, 1) * [1:n;]' A = A./A' A = tril(A) + tril(A)' - Matrix(1.0I, n, n) @test matrixdepot("lehmer", n) ≈ A println("'lehmer' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
169
n = 10 # rand(1:10) A = matrixdepot("hilb", n) B = matrixdepot("lotkin", n) @test A[2:n, :] == B[2:n, :] @test B[1,:][:] == ones(n) println("'lotkin' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
348
for n in [1, 3, 4, 5, 6] M = matrixdepot("magic", n) @test sum(M, dims=1) == sum(M, dims=2)' k = rand(1:n) @test sum(M, dims=1)[k] == sum(M, dims=2)'[k] # diagonal == antidiagnoal p = [n:-1:1;] @test sum(diag(M)) == sum(diag(M[:,p])) end @test size(matrixdepot("magic", 2)) == (2, 2) println("'magic' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
121
n = 10 # rand(1:10) A = matrixdepot("minij", n) @test issymmetric(A) @test isposdef(A) println("'minij' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
263
n = 10 # rand(1: 10) @test matrixdepot("moler", n) == matrixdepot("moler", n, -1) M = matrixdepot("moler", n) for i = 1:n, j = 1:n if i != j @test M[i,j] ≈ min(i,j) - 2 else @test M[i,i] ≈ i end end println("'moler' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
817
n = 10 # rand(2:10) @test matrixdepot("neumann", 1) == reshape([4.0], 1, 1) @test matrixdepot("neumann", n) == matrixdepot("neumann", Float64, n) n_mesh, n = n, n^2 B = zeros(Float64, n, n) i = 0 for i_mesh in 1:n_mesh, j_mesh in 1:n_mesh global i = i + 1 if i_mesh > 1 j = i - n_mesh else j = i + n_mesh end B[i,j] = B[i,j] - 1 if j_mesh > 1 j = i - 1 else j = i + 1 end B[i,j] = B[i,j] - 1 j = i B[i,j] = 4 if j_mesh < n_mesh j = i + 1 else j = i - 1 end B[i,j] = B[i,j] - 1 if i_mesh < n_mesh j = i + n_mesh else j = i - n_mesh end B[i,j] = B[i,j] - 1 end A = matrixdepot("neumann", n_mesh) @test Matrix(A) ≈ B println("'neumann' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
931
let mode, n, A, p, k, A # test two properties of oscillating matrix # For an n x n oscillating matrix A, the following holds: # 1. A has n distinct and positive eigenvalues λ_1 > λ_2 > ... > λ_n > 0 # 2. The ith eigenvector, corresponding to λ_i in the above ordering has # exactly i-1 sign changes. n = 8 # rand(2:10) @test_throws ArgumentError matrixdepot("oscillate", n, 4) for mode = 1:2 A = matrixdepot("oscillate", n, mode) eva, evc = eigen(A) @test all([ei > 0 for ei in eva]) p = sortperm(eva, rev = true) evc = evc[:,p] # compute the number of sign change function num_sign_change(v) signv = sign.(v) change = signv[1] num = 0 for i in signv if i != change num += 1 change = i end end return num end k = rand(1:n) @test num_sign_change(evc[:,k]) == k - 1 end @test matrixdepot("oscillate", n) !== nothing end println("'oscillate' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
212
n = 10 # rand(1:10) @test matrixdepot("parter", n) == matrixdepot("parter", Float64, n) A = matrixdepot("cauchy", [1.:n;] .+ 0.5, -[1.:n;]) @test matrixdepot("parter", n) ≈ A println("'parter' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
280
n = 10 # rand(1:10) A = matrixdepot("pascal", n) @test isposdef(A) @test issymmetric(A) P = diagm(0 => (-1).^[0:n-1;]) P[:,1] = ones(n, 1) for j = 2: n-1 for i = j+ 1:n P[i,j] = P[i-1, j] - P[i-1, j-1] end end @test A ≈ P*P' println("'pascal' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
198
n = 7 # rand(1:10) m = 17 # rand(1:20) A = matrixdepot("pei", n, m) B = ones(n,n) @test issymmetric(A) @test matrixdepot("pei", n) - triu(B) - tril(B) ≈ zeros(n,n) println("'pei' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
721
n = 10 # rand(1:10) @test matrixdepot("poisson", Float64, n) == matrixdepot("poisson", n) A = Matrix(matrixdepot("poisson", n)) n_mesh, n = n, n^2 B = zeros(Float64, n, n) i = 0 for i_mesh in 1 : n_mesh for j_mesh in 1 : n_mesh global i = i + 1 if i_mesh > 1 j = i - n_mesh B[i,j] = -1 end if j_mesh > 1 j = i - 1 B[i,j] = -1 end j = i B[i,j] = 4 if j_mesh < n_mesh j = i + 1 B[i,j] = -1 end if i_mesh < n_mesh j = i + n_mesh B[i,j] = -1 end end end @test A ≈ B println("'poisson' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
247
n = 10 # rand(1:10) A = matrixdepot("randcorr", n) @test issymmetric(A) # symmetric # positive semidefinite for eig in eigvals(A) @test eig >= 0 end # 1s on the diagonal @test diag(A) ≈ ones(Float64, n) println("'randcorr' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
435
let i, n, A, B, C, θ n = 5 # rand(1:5) A = matrixdepot("rando", Int, n, 1) B = matrixdepot("rando", Int, n, 2) C = matrixdepot("rando", Int, n, 3) for i in eachindex(A) @test A[i] == 0 || A[i] == 1 end @test all([bi == -1 || bi == 1 for bi in B]) @test all([bi == -1 || bi == 0 || bi == 1 for bi in C]) @test_throws ArgumentError matrixdepot("rando", 3, 3, 5) θ = matrixdepot("rando", n) end println("'rando' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
560
n = 6 # rand(2:10) kappa = 5 # rand(2:6) mode = 2 # rand(1:5) A = matrixdepot("randsvd", n, kappa, mode) B = matrixdepot("randsvd", n, kappa) if mode == 5 @test cond(A) <= kappa else @test cond(A) ≈ kappa end A5 = matrixdepot("randsvd", n, kappa, 5) A4 = matrixdepot("randsvd", n, kappa, 4) A3 = matrixdepot("randsvd", n, kappa, 3) A2 = matrixdepot("randsvd", n, kappa, 2) A1 = matrixdepot("randsvd", n, kappa, 1) θ = matrixdepot("randsvd", 1) @test_throws ArgumentError matrixdepot("randsvd", 5, kappa, 6) println("'randsvd' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
269
n = 8 # rand(2: 10) # test Hessenberg A = matrixdepot("rohess", n) B = tril(A) - diagm(0 => diag(A)) - diagm(-1 => diag(A, -1)) @test B ≈ zeros(n,n) atol=1.0e-7 # test orithogonality @test A'*A ≈ Matrix(1.0I, n, n) atol=1.0e-7 println("'rohess' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
981
A = matrixdepot("rosser", Int, 8, 2, 1) # B is the test matrix used in the paper #. Rosser, Lanczos, Hestenes and Karush, J. Res. Natl. Bur. Stand. Vol. 47 (1951), pp291-297. B = [611 196 -192 407 -8 -52 -49 29; 196 899 113 -192 -71 -43 -8 -44; -192 113 899 196 61 49 8 52; 407 -192 196 611 8 44 59 -23; -8 -71 61 8 411 -599 208 208; -52 -43 49 44 -599 411 208 208; -49 -8 8 59 208 208 99 -911; 29 -44 52 -23 208 208 -911 99]; @test A == B # test eigenvalues e1 = eigvals(matrixdepot("rosser", 2, 2, 1)) e2 = [500, 510] @test e1 ≈ e2 e1 = eigvals(matrixdepot("rosser", 4, 2, 1)) e2 = [0.1, 1000, 1019.9, 1020] @test e1 ≈ e2 atol=1e-2 e1 = eigvals(matrixdepot("rosser", 16, 2, 1)) e2 = [-1020, -1020, 0, 0, 0.098, 0.098, 1000, 1000, 1000, 1000, 1000, 1020, 1020, 1020, 1020, 1020] @test e1 ≈ e2 atol=11 @test_throws ArgumentError matrixdepot("rosser", 0) @test matrixdepot("rosser", 1) isa Matrix println("'rosser' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
213
n = 7 # rand(1:7) @test matrixdepot("sampling", n) == matrixdepot("sampling", Float64, n) A = matrixdepot("sampling", n) v = sort(eigvals(A)) @test v ≈ [0: n - 1;] atol=1e-10 println("'sampling' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
215
n = 10 # rand(1:10) A = matrixdepot("smallworld", n) B = matrixdepot("smallworld", Int, n) C = matrixdepot("erdrey", n) C2 = MatrixDepot.shortcuts(C, 0.6) @test nnz(C) <= nnz(C2) println("'erdrey' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
326
A = matrixdepot("toeplitz", [1,2,3,4,5]) @test A == matrixdepot("toeplitz", 5) B = matrixdepot("toeplitz", [1,2,3], [1,4,5]) @test B[1,3] == 5 @test B[3,1] == 3 @test B[1,2] == 4 println("'toeplitz' passed test...") n = 10 # rand(2:10) A = matrixdepot("prolate", n) @test issymmetric(A) println("'prolate' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
304
n = 10 # rand(1:10) @test matrixdepot("tridiag", [1,1,1], [1,1,1,1], [1,1,1]) == matrixdepot("tridiag", 4, 1,1,1) @test matrixdepot("tridiag", Float64, n) == matrixdepot("tridiag", n) A = matrixdepot("tridiag", n) @test isposdef(Array(A)) @test issymmetric(Array(A)) println("'tridiag' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
387
n = 9 # rand(1:10) m = 8 # rand(1:10) k = n-2 #rand(1:n) alpha = 3.0 @test matrixdepot("triw", Float64, m, n, alpha, k) == matrixdepot("triw", m, n, alpha, k) @test matrixdepot("triw", n) == matrixdepot("triw", Float64, n, n, -1, n-1) A = matrixdepot("triw", Float32, n) @test istriu(A) # B = A'*A has diagonal B(i,i) = i @test diag(A'*A) ≈ [1. : n;] println("'triw' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
203
n = 10 #rand(1:10) m = n ÷ 2 # rand(1:n) @test matrixdepot("vand", Int, n) == matrixdepot("vand", [1:n;]) A = matrixdepot("vand", Int, n) @test A[:, m] == [1:n;].^(m-1) println("'vand' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
174
n = 5 # rand(1:5) A = matrixdepot("wathen", n) @test typeof(A) <: SparseMatrixCSC @test issymmetric(Matrix(A)) @test isposdef(Matrix(A)) println("'wathen' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
code
324
n = 5 # rand(2:10) A = matrixdepot("wilkinson", n) @test A == matrixdepot("wilkinson", Float64, n) @test issymmetric(Matrix(A)) @test diag(Matrix(A),1) ≈ ones(Float64, n - 1) # symmetric along antidiagonal @test issymmetric(Matrix(A)[n:-1:1,:]) θ = matrixdepot("wilkinson", 1) println("'wilkinson' passed test...")
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
docs
5864
## Matrix Depot Release Notes v1.1 * remove deprecated method of defining user functions * remove obsolete methods of accessing remote SuiteSparse data * deprecate `@addgroup` and `@rmgroup`, use `setgroup!` and `deletegroup!` * add feature of alternative matrices relating MM matrices to SS matrices v1.0.7 * bug fix release v1.0.6 * allow to define user functions in separate package * deprecate way of storing user definitions in myMatrixDepot data subdirectory v1.0.0 * additional meta-data for suite-sparse collection specially SVD data * improved testing * ready for windows * adapt documentation v0.8.1 * fix problem with serialization of database * adapt data recognition for SuiteSparse index file * fix typo in sample problem "baart" v0.8.0 * Improved API (see: README.md and `?MatrixDepot`) * Keyword search * Logical expressions of predicates * Access current remote repositories (2018.8) * some bugs fixed - see git log * Documentation adapted v0.7.0 * Drop support for Julia v0.6 v0.6.0 * Adapt to Juliav0.7 - deprecations and minor bugs v0.5.6 * Fix various typos in documentation, thanks to @jiahao. v0.5.5 * Improve the documentation of regularization problems. v0.5.4 * Fix `SparseMatrix` deprecation for Julia v0.5. * Enhance the UF sparse matrix collection's meta data storage. v0.5.3 * Add new test problems for regularization methods: - `parallax`: http://matrixdepotjl.readthedocs.org/en/latest/regu.html#term-parallax * Allow the UF sparse matrix collection interface to store meta data. v0.5.2 * Update documentation. v0.5.1 * Fix a bug in user defined generators. * Fix reference formatting. * Allow accessing matrices by different subtypes of Integer or UnitRange. v0.5.0 * Drop support for Julia 0.3 * Various enhancements, including: - better formatted documentation for matrix generators. - automatically includes all Julia files in the directory `myMatrixDepot`, so that adding new matrix generators is more convenient and flexible. See http://matrixdepotjl.readthedocs.org/en/latest/user.html more details. v0.4.3 * Ignore any changes to the directory `myMatrixDepot`. This means any local changes to `myMatrixDepot\generator.jl` won't be affected when we upgrade to a new version of Matrix Depot. * Add more tests v0.4.2 * Fix: build failing on Julia v0.5 * Prevent `@rmgroup` from introducing extra empty lines * Add more tests v0.4.1 * Add new feature: - allow users to download a group of matrices from UF sparse matrix collection. v0.4.0 * Add new feature: - allow users to add new matrix generators. see http://matrixdepotjl.readthedocs.org/en/latest/user.html * Add new test problems for regularization methods: - `spikes` - `ursell` * Add new test matrices: - `golub` see http://blogs.mathworks.com/cleve/2015/08/24/golub-matrices-deceptively-ill-conditioned/ - `companion`: Companion matrix. * Document function `matrixdepot`. v0.3.5 * Add new test problems for regularization methods: - `gravity` - `blur` * Add new feature: - access matrices by a mixture of number and range. For example, we could do `matrixdepot(1:4, 6, 10:15)`. * Implement all three examples for `deriv2`. v0.3.4 * fix Julia v0.5 String deprecation. * implement a more general matrix generator. * add new matrix: Hankel matrix `hankel` * enumerate matrix input options * add option `matrixonly` for regularization problems. v0.3.3 * display the matrices in group lists alphabetically. * add group `"all"` for all the matrices in the collection. * fix pascal matrix overflow error. v0.3.2 * make `matrixdepot()` display better information. * rename `@addproperty` to `@addgroup` and rename `@rmproperty` to `@rmgroup`. * rename property `regu` to `regprob`. * set Float64 as the default data type for all the parameterized matrices in the collection. * update matrix references. v0.3.1 * Add new test problems for regularization methods: - `heat` - `phillips` - `baart` v0.3.0 * Add test problems for regularization methods: - `deriv2` - `foxgood` - `shaw` - `wing` * Reintroduce Matrix Market interface * Define new functions for test collection interfaces - `matrixdepot(name, :get)`: download matrix data `name`. - `matrixdepot(name, :read)`: read matrix data `name`. v0.2.8 * Add new test matrices - `oscillate`: a random test matrix for numerical regularization methods. - `prolate`: a symmetric ill-conditioned Toeplitz matrix. - `toeplitz`: Toeplitz matrix. v0.2.7 * Fix some typos and v0.4 deprecation warnings v0.2.6 * add reference information for test matrices * update demo v0.2.5 * support accessing matrices by number and UnitRange * matrices in the collection are ordered alphabetically * temporarily suspend the NIST Matrix Market interface * use base Matrix Market reader for Julia 0.4 v0.2.2 * Include an interface to NIST Matrix Market * reimplement ransvd to include rectangular case v0.2.1 * Include an interface to the UF Sparse Matrix Collection v0.1.3 * New matrices wathen: a sparse symmetric positive random matrix arose from the finite element method * Style the output information v0.1.2 * New matrices rohess: random orthogonal upper Hessenberg matrix kms: Kac-Murdock-Szego Toeplitz matrix * Others fix test error for randsvd. v0.1.1 * New matrices wilkinson: Wilkinson's eigenvalue test matrix. rando: random matrix with entries -1, 0 or 1. randsvd: random matrix with pre-assigned singular values. * New property random: the matrix is random. * Optimized Vandermonde matrix generation for better performance Thanks to @synapticarbors and @stevengj v0.1.0 * New matrices rosser: a matrix with close eigenvalues. sampling: a matrix with application in sampling theory. * Sphinx documentation
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.13
b7e11245178a57be72e47a69468dca6b73f192d8
docs
17094
# ![logo](doc/logo2.png) Matrix Depot [![Build Status][gha-img]][gha-url] [![Coverage Status][codecov-img]][codecov-url] [![Documentation Status][rtd-img]][rtd-url] An extensible test matrix collection for Julia. * [Release Notes](https://github.com/JuliaMatrices/MatrixDepot.jl/blob/master/NEWS.md) Give access to a wealth of sample and test matrices and accompanying data. A set of matrices is generated locally (with arguments controlling the special case). Another set is loaded from one of the publicly accessible matrix collections [`SuiteSparse Matrix Collection`](https://sparse.tamu.edu) (formerly `University of Florida Matrix Collection`) and the [`Matrix Market Collection`](https://math.nist.gov/MatrixMarket), the latter being obsolescent. Access is like ```julia using MatrixDepot ?MatrixDepot # display package help info A = matrixdepot("hilb", 10) # locally generated hilbert matrix dimensions (10,10) A = matrixdepot("HB/1138_bus") # named matrix of the SuiteSparse Collection ``` or ```julia md = mdopen("*/bfly") # named matrix with some extra data A = md.A co = md.coord tx = md("Gname_10.txt") md.<tab><tab> # overview of the "fields" of md returning like # A m n dnz nnz coord Gname_10.txt G_10 Gcoord_10 ``` or also ```julia mdinfo("gravity") # text info about the selected matrix md = mdopen("gravity", 10, false) # locally generated example with rhs and solution A = md.A b = md.b x = md.x ``` ## Install **NOTE:** If you use Windows, you need to install MinGW/MSYS or Cygwin in order to use the SuiteSparse sparse and MatrixMarket matrix collection interface. To install the release version, type ```julia julia> Pkg.add("MatrixDepot") ``` ## Usage ### Naming #### Matrix Names Every Matrix type has a unique name, which is a string of one of the forms: 1. `"name"` - used for matrices, which are generated locally. 2. `"dir/name"` - for all matrices of the `SuiteSparse` collection. 3. `"dir/subdir/name"` - for all matrices of the `MatrixMarket` collection. The names are similar to relative path names, separated by a slash character. The components of the name must not contain any of the characters `"/*[]"`. #### Groups a set of matrices may be assigned to predefined or user-defined groups. The group names are represented as `Julia` symbols in the form `:symmetric`. The group names are therefore restricted to valid `Julia` identifiers, that means start with a letter and contain only letters, digits, and `'_'`. #### Numeric Identifiers Every matrix has a numeric identifier, which is unique for its area: * `builtin(id)` - one of the built-in matrix generators - currently `id ∈ 1:59`. * `user(id)` - a user-defined matrix generator - starting with `1`. * `sp(id)` - one of the `SuiteSparse` collection. The integer ids are the 'official' ident numbers assigned by the collection. Currently `id ∈ 1:3000`. * `mm(id)` - one of the `MatrixMarket` collection. Here id follows the ordering of the index file of the collection. ### Sets of Matrix Names - Pattern For some functions it makes sense to have lists of matrix names to operate on, for example to select a set matrices with certain properties. These sets are described by 'Patterns', which are applied to matrix names and also to other matrix properties. The following pattern types are supported: 1. `"name"` - a string matching exactly a matrix name 2. `"shell-pattern"` - a string with shell wildcards `'?', '*', "[...]"` included. 3. `r"egular expression"` - a regular expression to match the matrix name. 4. `:group` - one of the defined group names; match all matrices in the group 5. `qualified numeric identifiers` - examples `builtin(10)`, `sp(1:5, 7)`, `mm(1), sp(:)` 6. `predicate_function` - the name of a predefined or user-defined boolean function of the internal data type `MatrixData`. Example: `issymmetric`. 7. `abstract vector of sub-patterns` - `OR` - any of the sub-pattern matches 8. `tuple of sub-patterns` - `AND` - all of the sub-patterns match 9. `~pattern` - negation of a pattern the \neg - operator ~ may be applied to all patterns To express `OR` and `AND`, the binary operators `|` and `&` and `(` / `)` are preferred. Examples: ```julia "gravity" | "HB/*" & ~(ishermitian & iscomplex) & ~sp(20:30) ``` The set of all known matrices can be expressed as empty tuple `()`. In a shell- pattern the double `**` matches also slash characters, in contrast to the single `*`. A convenient form of a predicate-generator is ```julia @pred(expression) ``` where expression is a valid `Julia` boolean expression, which may access all properties of `MatrixData` as literal variable names. Examples: `@pred(author == "J. Brown")` is translated to: `d -> :author in propertynames(d) && d.author == "J. Brown"` `@pred(500_000 <= n * m < 1_000_000)` restricts the size of matched matrices. `@pred(10^4 <= n <= 2*10^4 && n == m && nnz / n > 10 )` in average more than 10 entries per row There is s set of predefined predicate functions including: `(issymmetric, ishermitian, isgeneral, isskew, isreal, iscomplex, isboolean, islocal, isremote, isloaded, isunloaded, isbuiltin, isuser, issparse)` Special predicate generators `keyword(word...)` and `hasdata(symbol...)` allow to support keyword-search and check for the existence of meta-data. For example: `hasdata(:x) & ~keyword("fluid"` provides solution (x) and does not mention "fluid". ### Number of nonzeros Beware that some sparse matrices contain non-structural zeros, that is, coefficients stored explicitly but whose value is `0`. In this case a discrepancy between nnz(A) and sum(!iszero, A) will be observed. ## Accessing Data ### Listing matrices with certain properties ```julia mdinfo() # overview listgroups() # list all defined group names mdlist(pattern) # array of matrix names according to pattern listdata(pattern) # array of `MatrixData`objects according to pattern listnames(pattern) # MD-formatted listing of all names according to pattern listdir("*//*") # MD-formatted - group over part before `//` - count matching ``` ### Information about matrices ```julia mdinfo() # overview over database mdinfo(pattern) # individual documentation about matrix(es) matching pattern ``` ### Generating a matrix `A = matrixdepot("kahan", 10)` generates a matrix using one of the built-in generators `md = mdopen("kahan", 10)` returns a handle `md`; matrix can be obtained by `A = md.A` ### Accessing Meta-Data In general the first form is preferable, if only the pure matrix is required. For remote collections no arguments are used. The second form allows to access all types of 'meta-data', which may be available for some local or remote matrices. Examples: `md = mdopen("spikes", 5, false); A = md.A; b = md.b; x = md.x` `md = mdopen("Rommes/bips07_1998"); A = md.A; v = md.iv; title = md.data.title; nodenames = md("nodename.txt")` The last example shows, how to access textual meta-data, when the name contains `Julia` non-word characters. Also if the metadata-name is stored in a variable, the last form has to be used. `meta = metasymbols(md)[2]; sec_matrix = md(meta)` The function `metasymbols` returns a list of all symbols denoting metadata provided by `md`. Whether expressed as symbols or strings does not matter. The system function `propertynames(md)` returns all data of `md`. That includes size information and metadata. `propertynames(md.data)` gives an overview about all attributes of the `md.data::MatrixData`, which can for example be used in the `@pred` definitions. ### Backoffice Jobs The remote data are originally stored at the remote web-site of one of the matrix collections. Before they are presented to the user, they are downloaded to local disk storage, which serves as a permanent cache. By default, the data directory is a scratchspace managed by [`Scratch.jl`](https://github.com/JuliaPackaging/Scratch.jl), but can be changed by setting the `MATRIXDEPOT_DATA` environment variable. The data directory can be queried by julia> MatrixDepot.data_dir() "/home/.../.julia/scratchspaces/b51810bb-c9f3-55da-ae3c-350fc1fbce05/data The occasional user needs not bother about downloads, because that is done in the background if matrix files are missing on the local disk. The same is true for the data required by `mdinfo(pattern)`. Actually these are stored in separate files if the full matrix files (which may be huge) are not yet loaded. #### Bulk Downloads ##### Load Header Data A download job to transmit a subset of remote matrix files may be started to load header data for all files. Header data always include the matrix type according to the matrix-market-format and the size values `m` row-number, `n` = columns-number, and `dnz` number of stored data of the main sparse matrix. `MatrixDepot.loadinfo(pattern)` where `pattern` defines the subset. That is possible for the [SuiteSparse collection](https://sparse.tamu.edu) and the [NIST MatrixMarket collection](https://math.nist.gov/MatrixMarket). The patterns can always refer to matrix names and id numbers. In the case of `SuiteSparse` collection, also the metadata `"date"`, `"kind"`, `"m"`, `"n"`, `"nnz"` are available and can be used, before individual matrix data have been loaded. They are contained in a data file obtained from the remote site. For `MatrixMarket` collection, patterns are restricted to names and id numbers. In general it would be possible by `loadinfo("**")` to load all header data. That would last maybe an hour and generate some traffic for the remote sites. Nevertheless it is not necessary to do so, if you don't need the header data for the following task. ##### Load Complete Data Files **`MatrixDepot.load(pattern)`** loads all data files for the patterns. Patterns can only refer to attributes, which are already available. In the case of `SuiteSparse` that includes the size info `"date"`, `"kind"`, `"m"`, `"n"`, and `"nnz"` and all additional attributes loaded in the previous step, which include `"author"`, `"title"`, `"notes"`, and keywords. In the case of `MatrixMarket` you can only refer to `"m"`, `"n"`, and `"dnz"`, if previously loaded with the header data. Please do not: `MatrixDepot.load("**")`. That would require some day(s) to finish and include some really big data files (~100GB), which could be more than your disks can hold. Make a reasonable selection, before you start a bulk download. Local and already loaded matrices are skipped automatically. Example: `MatrixDepot.load(sp(:) & @pred(nnz < 100_000))` to download only problems with given number of stored entries in the main matrix. ## Sample Session To see an overview of the matrices in the collection, type ```julia julia> using MatrixDepot julia> mdinfo() Currently loaded Matrices ––––––––––––––––––––––––––– builtin(#) –––––––––– ––––––––––– ––––––––––– ––––––––––– –––––––––– –––––––––––– ––––––––––– ––––––––––– ––––––––––––– –––––––––––– 1 baart 7 circul 13 fiedler 19 gravity 25 invhilb 31 magic 37 parter 43 randcorr 49 shaw 55 ursell 2 binomial 8 clement 14 forsythe 20 grcar 26 invol 32 minij 38 pascal 44 rando 50 smallworld 56 vand 3 blur 9 companion 15 foxgood 21 hadamard 27 kahan 33 moler 39 pei 45 randsvd 51 spikes 57 wathen 4 cauchy 10 deriv2 16 frank 22 hankel 28 kms 34 neumann 40 phillips 46 rohess 52 toeplitz 58 wilkinson 5 chebspec 11 dingdong 17 gilbert 23 heat 29 lehmer 35 oscillate 41 poisson 47 rosser 53 tridiag 59 wing 6 chow 12 erdrey 18 golub 24 hilb 30 lotkin 36 parallax 42 prolate 48 sampling 54 triw user(#) ––––––––– 1 randsym Groups –––––– ––––––– ––––– –––– ––––– ––––– ––––––– ––––––– –––––– –––––– ––––––– –––––– ––––––––– all builtin local user eigen graph illcond inverse posdef random regprob sparse symmetric Suite Sparse of –––––––––––– –––– 2770 2833 MatrixMarket of –––––––––––– ––– 488 498 ``` We can generate a 4-by-4 Hilbert matrix by typing ```julia julia> matrixdepot("hilb", 4) 4x4 Array{Float64,2}: 1.0 0.5 0.333333 0.25 0.5 0.333333 0.25 0.2 0.333333 0.25 0.2 0.166667 0.25 0.2 0.166667 0.142857 ``` We can type the matrix name to get documentation about the matrix. ```julia julia> mdinfo("hilb") Hilbert matrix ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡ The Hilbert matrix has (i,j) element 1/(i+j-1). It is notorious for being ill conditioned. It is symmetric positive definite and totally positive. Input options: • [type,] dim: the dimension of the matrix; • [type,] row_dim, col_dim: the row and column dimensions. Groups: ["inverse", "ill-cond", "symmetric", "pos-def"] References: M. D. Choi, Tricks or treats with the Hilbert matrix, Amer. Math. Monthly, 90 (1983), pp. 301-312. N. J. Higham, Accuracy and Stability of Numerical Algorithms, second edition, Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 2002; sec. 28.1. ``` We can also specify the data type for locally generated matrices. ```julia julia> matrixdepot("hilb", Float16, 5, 3) 5x3 Array{Float16,2}: 1.0 0.5 0.33325 0.5 0.33325 0.25 0.33325 0.25 0.19995 0.25 0.19995 0.16663 0.19995 0.16663 0.14282 julia> matrixdepot("hilb", Rational{Int}, 4) 4x4 Array{Rational{T<:Integer},2}: 1//1 1//2 1//3 1//4 1//2 1//3 1//4 1//5 1//3 1//4 1//5 1//6 1//4 1//5 1//6 1//7 ``` Matrices can be accessed by a variety of patterns and composed patterns. Integer numbers `i` refer to the ident numbers in `sp(i)`, `mm(i)`, `builtin(i)`, `user(i)`. Here `sp` ... denote the supported matrix collections SuiteSparse (formerly UFL), Matrix Market, built-in, user-defined. ```julia julia> mdlist(sp(1)) # here sp(1) is the ident number of the SuiteSparse collection list(1) ––––––––––– HB/1138_bus julia> listnames(builtin(1, 5:10)) # the internal numbering of the builtin-functions list(7) ––––––– –––––––– –––– –––––– ––––––– ––––––––– –––––– baart chebspec chow circul clement companion deriv2 julia> mdlist(builtin(1:4, 6, 10:15) | user(1:10) ) 12-element Array{String,1}: "baart" "binomial" "blur" "cauchy" "chow" "deriv2" "dingdong" "erdrey" "fiedler" "forsythe" "foxgood" "randsym" ``` While the `listnames` command renders the output as markdown table, the internal `mdlist` produces an array of valid matrix names. We can type a group name to see all the matrices in that group. Group names are always written as symbols to distinguish them form matrix names and pattern, which are always strings. ```julia julia> listnames(:symmetric) list(22) –––––––– –––––––– ––––––– –––––– ––––––––– –––––––– ––––––– ––––––––– cauchy dingdong hilb lehmer oscillate poisson randsym wilkinson circul fiedler invhilb minij pascal prolate tridiag clement hankel kms moler pei randcorr wathen ``` ## Extend Matrix Depot It is possible to extend the builtin local problems with user defined generators and groups. We can add [new matrix generators](http://matrix-depot.readthedocs.org/en/latest/user.html) and define [new groups of matrices](http://matrix-depot.readthedocs.org/en/latest/properties.html). ## References * Weijian Zhang and Nicholas J. Higham, "Matrix Depot: An Extensible Test Matrix Collection for Julia", *PeerJ Comput. Sci.*, 2:e58 (2016), [[pdf]](https://peerj.com/articles/cs-58/) * Nicholas J. Higham, "Algorithm 694, A Collection of Test Matrices in MATLAB", *ACM Trans. Math. Software*, vol. 17. (1991), pp 289-305 [[pdf]](http://www.maths.manchester.ac.uk/~higham/narep/narep172.pdf) [[doi]](https://dx.doi.org/10.1145/114697.116805) * T.A. Davis and Y. Hu, "The University of Florida Sparse Matrix Collection", *ACM Transaction on Mathematical Software*, vol. 38, Issue 1, (2011), pp 1:1-1:25 [[pdf]](http://www.cise.ufl.edu/research/sparse/techreports/matrices.pdf) * R.F. Boisvert, R. Pozo, K. A. Remington, R. F. Barrett, & J. Dongarra, " Matrix Market: a web resource for test matrix collections", *Quality of Numerical Software* (1996) (pp. 125-137). [[pdf]](http://www.netlib.org/utk/people/JackDongarra/pdf/matrixmarket.pdf) * Per Christian Hansen, "Test Matrices for Regularization Methods", *SIAM Journal on Scientific Computing*, vol. 16, 2, (1995) pp.506-512. [[pdf]](http://epubs.siam.org/doi/abs/10.1137/0916032) [[doi]](https://dx.doi.org/10.1137/0916032) [gha-img]: https://github.com/JuliaMatrices/MatrixDepot.jl/workflows/CI/badge.svg [gha-url]: https://github.com/JuliaMatrices/MatrixDepot.jl/actions?query=workflow%3ACI [codecov-img]: https://codecov.io/gh/JuliaMatrices/MatrixDepot.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/JuliaMatrices/MatrixDepot.jl [rtd-img]: https://readthedocs.org/projects/matrix-depot/badge/?version=latest [rtd-url]: https://matrix-depot.readthedocs.io/en/latest/?badge=latest
MatrixDepot
https://github.com/JuliaLinearAlgebra/MatrixDepot.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
1137
module getDeps using IntegrationTests using Pkg include(joinpath(dirname(@__FILE__), "prepareIntegrationTest.jl")) """ print_job_yaml(job_name::AbstractString) Generate a GitLab CI job yaml file for a given package name and print it to stdout. # Arguments - `package_name`: Name of the package """ function print_job_yaml(package_name::AbstractString) # Do not use a YAML library, as the generated YAML code is too simple to justify # the additional runtime of installing the YAML package. job_yaml = """integrationTest$package_name: image: "alpine:latest" script: - echo "run Integration Test for package $package_name" """ return print(job_yaml) end # see README.md if !isinteractive() tmp_path = mktempdir() prepareIntegrationTest.create_package_eco_system(tmp_path) # extra Project.toml to generate dependency graph for the whole project Pkg.activate(joinpath(tmp_path, "MyPkgMeta")) depending_packages = IntegrationTests.depending_projects("MyPkgC", r"^MyPkg*") for dep in depending_packages print_job_yaml(dep) end end end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
494
module getDeps using IntegrationTests using Pkg include(joinpath(dirname(@__FILE__), "prepareIntegrationTest.jl")) # see README.md if !isinteractive() tmp_path = mktempdir() prepareIntegrationTest.create_package_eco_system(tmp_path) # extra Project.toml to generate dependency graph for the whole project Pkg.activate(joinpath(tmp_path, "MyPkgMeta")) depending_packages = IntegrationTests.depending_projects("MyPkgC", r"^MyPkg*") print(depending_packages) end end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
636
module getDeps using IntegrationTests using Pkg include(joinpath(dirname(@__FILE__), "prepareIntegrationTest.jl")) # see README.md if !isinteractive() tmp_path = mktempdir() prepareIntegrationTest.create_package_eco_system(tmp_path) # extra Project.toml to generate dependency graph for the whole project Pkg.activate(joinpath(tmp_path, "MyPkgMeta")) depending_packages = IntegrationTests.depending_projects("MyPkgC", r"^MyPkg*") # compare with expected result # needs to be negated, because true would result in error code 1 exit(!(sort(depending_packages) == sort(["MyPkgA", "MyPkgB"]))) end end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
1402
module prepareIntegrationTest using Pkg """ create_package_eco_system(base_path) Creates a Julia package ecosystem in the `base_path` folder for testing purposes. # Arguments - `base_path`: Path to folder where ecosystem is created. """ function create_package_eco_system(base_path) # A graphical representation of the dependencies between the packages can be found in the # README.md. cd(base_path) Pkg.generate("MyPkgA") Pkg.generate("MyPkgB") Pkg.generate("MyPkgC") Pkg.generate("MyPkgD") Pkg.generate("MyPkgE") Pkg.generate("MyPkgMeta") Pkg.activate("MyPkgE") Pkg.add("JSON") Pkg.add("Pkg") Pkg.add("Test") Pkg.activate("MyPkgD") Pkg.develop(; path=joinpath(base_path, "MyPkgE")) Pkg.activate("MyPkgC") Pkg.add("JSON") Pkg.develop(; path=joinpath(base_path, "MyPkgE")) Pkg.activate("MyPkgB") Pkg.develop(; path=joinpath(base_path, "MyPkgE")) Pkg.develop(; path=joinpath(base_path, "MyPkgC")) Pkg.add("PkgTemplates") Pkg.activate("MyPkgA") Pkg.develop(; path=joinpath(base_path, "MyPkgE")) Pkg.develop(; path=joinpath(base_path, "MyPkgD")) Pkg.develop(; path=joinpath(base_path, "MyPkgC")) Pkg.develop(; path=joinpath(base_path, "MyPkgB")) Pkg.add("YAML") Pkg.activate("MyPkgMeta") Pkg.develop(; path=joinpath(base_path, "MyPkgA")) return Nothing end end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
408
using JuliaFormatter # we asume the format_all.jl script is located in QEDbase.jl/.formatting project_path = Base.Filesystem.joinpath(Base.Filesystem.dirname(Base.source_path()), "..") not_formatted = format(project_path; verbose=true) if not_formatted @info "Formatting verified." else @warn "Formatting verification failed: Some files are not properly formatted!" end exit(not_formatted ? 0 : 1)
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
1971
using Pkg # targeting the correct source code # this asumes the make.jl script is located in QEDbase.jl/docs project_path = Base.Filesystem.joinpath(Base.Filesystem.dirname(Base.source_path()), "..") Pkg.develop(; path=project_path) using Documenter using DocumenterMermaid using IntegrationTests readme_path = Base.Filesystem.joinpath(project_path, "README.md") # Documenter.jl expect index.md as landing page index_path = Base.Filesystem.joinpath(project_path, "docs/src/index.md") # Copy README.md from the project base folder and use it as the start page open(readme_path, "r") do readme_in readme_string = read(readme_in, String) # replace static links in the README.md with dynamic links, which are resolved by documenter.jl readme_string = replace( readme_string, "[Pipeline Tutorials](https://qedjl-project.github.io/IntegrationTests.jl/main/pipeline_tutorials.html)" => "[Pipeline Tutorials](@ref)", "[Integration Test Tool](https://qedjl-project.github.io/IntegrationTests.jl/main/integration_test_tool.html)" => "[Integration Test Tool](@ref)", ) open(index_path, "w") do readme_out write(readme_out, readme_string) end end pages = [ "Home" => "index.md", "Integration Test Tool" => "integration_test_tool.md", "Pipeline Tutorials" => "pipeline_tutorials.md", "References" => "api.md", ] makedocs(; sitename="IntegrationTests.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://qedjl-project.gitlab.io/IntegrationTests.jl", assets=String[], ), modules=[IntegrationTests], authors="Simeon Ehrig", repo=Documenter.Remotes.GitHub("QEDjl-project", "IntegrationTests.jl "), pages=pages, ) # delete README.md in the doc/src folder so that no one can accidentally edit the wrong file rm(index_path) deploydocs(; repo="github.com/QEDjl-project/IntegrationTests.jl.git", push_preview=false)
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
7383
module IntegrationTests using Pkg export depending_projects export build_dependency_graph """ build_dependency_graph( info::Union{Pkg.API.ProjectInfo,Pkg.API.PackageInfo}=Pkg.project(), visited_packages::AbstractVector{String}=Vector{String}(), )::Dict{String,Union{Dict,Nothing}} Construct the dependency graph of the currently active project. # Arguments - `project_info::Union{Pkg.API.ProjectInfo,Pkg.API.PackageInfo}`: properties about the current project and Julia packages, such as name and version - `visited_packages::AbstractVector{String}`: list of packages that have already been processed # Returns Dependency diagram of the active project, stored in a `Dict`. The key is always the package name. The value is either a `Dict` if the package has dependencies or `nothing` if there are no dependencies. If a package is a dependency more than once, only the first appearance has dependencies. All other appearances have no dependencies. Standard library packages are ignored. """ function build_dependency_graph( project_info::Union{Pkg.API.ProjectInfo,Pkg.API.PackageInfo}=Pkg.project(), visited_packages::AbstractVector{String}=Vector{String}(), )::Dict{String,Union{Dict,Nothing}} graph = Dict() for (name, uuid) in project_info.dependencies # if the version number is nothing, it is the stdlib and we can ignore it if isnothing(Pkg.dependencies()[uuid].version) continue end # if a dependency is used by many packages, only adds one time with all dependencies # the next time, add it without dependencies to avoid redundancy if !(name in visited_packages) graph[name] = build_dependency_graph(Pkg.dependencies()[uuid], visited_packages) push!(visited_packages, name) else graph[name] = nothing end end return graph end """ depending_projects( package_name::AbstractString, package_filter::Union{<:AbstractString,Regex} project_tree::AbstractDict=build_dependency_graph() )::Vector{String} Returns a list of packages that have the package `package_name` as a dependency. # Arguments - `package_name`: Name of the dependency - `package_filter`: Ignore all packages that do not match `package_filter`. This includes the top node package of the graph. Child nodes are always checked for `package_name`, but they are not traversed if they do not match `package_filter`. - `project_tree`: Project tree in which to search for dependent packages. Each (sub-)package needs to be `AbstractDict{String, AbstractDict}` # Returns A `Vector{String}` containing the names of all packages that have the given dependency. """ function depending_projects( package_name::AbstractString, package_filter::Union{<:AbstractString,Regex}, project_tree::AbstractDict=build_dependency_graph(), )::Vector{String} packages::Vector{String} = [] visited_packages::Vector{String} = [] _traverse_tree!(package_name, package_filter, project_tree, packages, visited_packages) return packages end """ depending_projects( package_name::AbstractString, package_filter::AbstractVector{<:AbstractString}, project_tree::AbstractDict=build_dependency_graph() )::Vector{String} """ function depending_projects( package_name::AbstractString, package_filter::AbstractVector{<:AbstractString}, project_tree::AbstractDict=build_dependency_graph(), )::Vector{String} packages::Vector{String} = [] visited_packages::Vector{String} = [] if length(package_filter) == 0 throw(ArgumentError("package_filter must not be empty")) end _traverse_tree!(package_name, package_filter, project_tree, packages, visited_packages) return packages end """ _match_package_filter( package_filter::Union{<:AbstractString,Regex}, package::AbstractString )::Bool Check if `package_filter` contains `package`. Wrapper function for `contains()` and `in()`. # Returns - `true` if it matches. """ function _match_package_filter( package_filter::Union{<:AbstractString,Regex}, package::AbstractString )::Bool return contains(package, package_filter) end """ _match_package_filter( package_filter::AbstractVector{<:AbstractString}, package::AbstractString )::Bool """ function _match_package_filter( package_filter::AbstractVector{<:AbstractString}, package::AbstractString )::Bool return package in package_filter end """ _traverse_tree!( package_name::AbstractString, package_filter::Union{<:AbstractString,Regex,AbstractVector{<:AbstractString}}, project_tree::AbstractDict, packages::AbstractVector{<:AbstractString}, visited_packages::AbstractVector{<:AbstractString} ) Traverse the project tree and add any package to `packages` that has the package `package_name` as a dependency. # Arguments - `package_name`: Name of the dependency - `package_filter`: Ignore all packages that do not match `package_filter`. This includes the top node package of the graph. Child nodes always are checked for `package_name`, but they are not traveres if they do not match `package_filter`. - `project_tree`: Project tree, where to search the dependent packages. Each (sub-) package needs to be AbstractDict{String, AbstractDict} - `packages`: Packages which has `package_name` as dependency. - `visited_packages`: List of packages that are not traveresed again. Avoids circular, infinite traversing. """ function _traverse_tree!( package_name::AbstractString, package_filter::Union{<:AbstractString,Regex,AbstractVector{<:AbstractString}}, project_tree::AbstractDict, packages::AbstractVector{<:AbstractString}, visited_packages::AbstractVector{<:AbstractString}, ) for project_name_version in keys(project_tree) # remove project version from string -> usual shape: `packageName.jl version` project_name = split(project_name_version)[1] # do not traverse packages further that we have already seen if project_name in visited_packages continue end # do not traverse packages that don't match the given filter if !_match_package_filter(package_filter, project_name) continue end push!(visited_packages, String(project_name)) # independent of a match, traverse all dependencies because they can also have the package as dependency _traverse_tree!( package_name, package_filter, project_tree[project_name_version], packages, visited_packages, ) # if the dependency is nothing, continue (I think this represents that the package was already set as dependency of a another package and therefore does not repeat the dependency) if isnothing(project_tree[project_name_version]) || isempty(project_tree[project_name_version]) continue end # search dependencies for the requested one if any( startswith(x, package_name) for x in keys(project_tree[project_name_version]) ) push!(packages, project_name) end end end end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
2410
using IntegrationTests using PkgDependency using Pkg import Term.Trees: Tree # compare each node of both generated dependency graphs # the test requires, that both algorithm processes the dependencies in Pkg.project().dependencies() # and Pkg.dependencies()[uuid].dependencies() in the same order function compare_nodes(integTest, pkgDep, origin_string="graph: root") if isnothing(integTest) || isnothing(pkgDep) @test isnothing(integTest) == isnothing(pkgDep) return nothing end integ_test_keys = collect(keys(integTest)) sort!(integ_test_keys) # PkgDependency stores the package name together with the version number # e.g. Term v1.0.1 # therefore remove version number, that packages can be compared pkg_dep_keys = map(x -> split(x)[1], collect(keys(pkgDep))) sort!(pkg_dep_keys) @test length(integ_test_keys) == length(pkg_dep_keys) @test integ_test_keys == pkg_dep_keys # printing the whole graphs does provide useful debug information # print more clever debug information if length(integ_test_keys) != length(pkg_dep_keys) || integ_test_keys != pkg_dep_keys println(origin_string) println("IntegrationTests.build_dependency_graph()\n$(integ_test_keys)") println("PkgDependency.builddict()\n$(pkg_dep_keys)") return nothing end # check the dependencies of this node for child in integ_test_keys pkgDep_name = "" for name in keys(pkgDep) # for PkgDependency, we need the package name + version nummer as key if startswith(name, child) pkgDep_name = name break end end compare_nodes(integTest[child], pkgDep[pkgDep_name], origin_string * "->" * child) end end @testset "compare build_dependency_graph() with reference implementation for PkgDependency" begin # The test takes the dependency graph of the test environment from IntegrationTest, # builds the dependency graph with IntegrationTests.build_dependency_graph() and the # reference implementation PkgDependency.builddict() and compares the graphs node by node. inteGrationTestsGraph = IntegrationTests.build_dependency_graph() pkgDependencyGraph::AbstractDict = PkgDependency.builddict( Pkg.project().uuid, Pkg.project() ) compare_nodes(inteGrationTestsGraph, pkgDependencyGraph) end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
9279
import Term.Trees: Tree # set environment variable PRINTTREE=1 to visualize the project trees of the testsets function printTree()::Bool return parse(Bool, get(ENV, "PRINTTREE", "0")) end @testset "direct dependency to main" begin project_tree = Dict("MyMainProject.jl 1.0.0" => Dict("MyDep1.jl 1.0.0" => Dict())) if printTree() print(Tree(project_tree; name="direct dependency to main")) end # dependency exist and prefix is correct @test IntegrationTests.depending_projects( "MyDep1.jl", ["MyMainProject.jl"], project_tree ) == ["MyMainProject.jl"] # dependency does not exist and prefix is correct @test isempty( IntegrationTests.depending_projects("MyDep2.jl", "MyMainProject.jl", project_tree) ) # dependency exist and prefix is incorrect @test isempty( IntegrationTests.depending_projects("MyDep1.jl", "ExternProject.jl", project_tree) ) # dependency does not exist and prefix is incorrect @test isempty( IntegrationTests.depending_projects("MyDep2.jl", "ExternProject.jl", project_tree) ) end @testset "test package filter api" begin project_tree = Dict( "MyMainProject.jl 1.0.0" => Dict( "MyDep1.jl 1.0.0" => Dict( "YourDep1.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict()), "MyDep2.jl 1.0.0" => Dict( "ForeignDep1.jl 1.0.0" => Dict(Dict("MyDep3.jl 1.0.0" => Dict())), ), ), "yourDep2.jl 1.0.0" => Dict("MyDep1.jl 1.0.0" => Dict()), ), ) if printTree() print(Tree(project_tree; name="test package filter api")) end @testset "single package name" begin @test sort(depending_projects("MyDep1.jl", "", project_tree)) == sort(["MyMainProject.jl", "yourDep2.jl"]) @test sort(depending_projects("MyDep1.jl", "MyMainProject.jl", project_tree)) == sort(["MyMainProject.jl"]) @test sort(depending_projects("yourDep2.jl", "MyMainProject.jl", project_tree)) == sort(["MyMainProject.jl"]) end @testset "regex" begin @test sort(depending_projects("MyDep2.jl", r"My*", project_tree)) == sort(["MyDep1.jl"]) @test sort(depending_projects("MyDep2.jl", r"MyDep*", project_tree)) == sort([]) @test sort( depending_projects("MyDep2.jl", r"MyDep*|^MyMainProject.jl$", project_tree) ) == sort(["MyDep1.jl"]) @test sort(depending_projects("MyDep1.jl", r"^MyMainProject.jl$", project_tree)) == sort(["MyMainProject.jl"]) @test sort( depending_projects( "MyDep1.jl", r"^MyMainProject.jl$|^yourDep2.jl$", project_tree ), ) == sort(["MyMainProject.jl", "yourDep2.jl"]) @test sort( depending_projects("MyDep3.jl", r"^MyMainProject.jl$|^MyDep*", project_tree) ) == sort([]) @test sort( depending_projects( "MyDep3.jl", r"^MyMainProject.jl$|^MyDep*|^Foreign*", project_tree ), ) == sort(["ForeignDep1.jl"]) @test sort( depending_projects( "MyDep3.jl", r"^MyMainProject.jl$|^MyDep*|^Your*", project_tree ), ) == sort(["YourDep1.jl"]) @test sort( depending_projects( "MyDep3.jl", r"^MyMainProject.jl$|^MyDep*|^Foreign*|^Your*", project_tree ), ) == sort(["ForeignDep1.jl", "YourDep1.jl"]) @test sort(depending_projects("MyDep1.jl", r"", project_tree)) == sort(["MyMainProject.jl", "yourDep2.jl"]) end @testset "list of package names" begin @test sort(depending_projects("MyDep1.jl", ["MyMainProject.jl"], project_tree)) == sort(["MyMainProject.jl"]) @test sort( depending_projects("MyDep2.jl", ["MyMainProject.jl", "MyDep1.jl"], project_tree) ) == sort(["MyDep1.jl"]) @test sort( depending_projects( "MyDep3.jl", ["MyMainProject.jl", "MyDep1.jl", "ForeignDep1.jl", "MyDep3.jl"], project_tree, ), ) == sort([]) @test sort( depending_projects( "MyDep3.jl", [ "MyMainProject.jl", "MyDep1.jl", "MyDep2.jl", "ForeignDep1.jl", "MyDep3.jl", ], project_tree, ), ) == sort(["ForeignDep1.jl"]) @test sort( depending_projects( "MyDep3.jl", [ "YourDep1.jl", "MyMainProject.jl", "MyDep1.jl", "MyDep2.jl", "ForeignDep1.jl", "MyDep3.jl", ], project_tree, ), ) == sort(["YourDep1.jl", "ForeignDep1.jl"]) # using strings and regex in a vector is not allowed # use instead a single regex @test_throws MethodError depending_projects( "MyDep2.jl", ["MyMainProject.jl", r"MyDep1.jl"], project_tree ) @test_throws ArgumentError depending_projects( "MyDep2.jl", Vector{String}(), project_tree ) end end @testset "complex dependencies" begin #! format: off project_tree = Dict("MyMainProject.jl 1.0.0" => Dict("MyDep1.jl 1.0.0" => Dict(), "MyDep2.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict(), "ForeignDep1.jl 1.0.0" => Dict()), "ForeignDep2.jl 1.0.0" => Dict("ForeignDep3.jl 1.0.0" => Dict(), "ForeignDep4.jl 1.0.0" => Dict()), "MyDep4.jl 1.0.0" => Dict("MyDep5.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict())), "ForeignDep2.jl 1.0.0" => Dict("MyDep5.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict()), "MyDep3.jl 1.0.0" => Dict(), "MyDep6.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict())), "MyDep7.jl 1.0.0" => Dict("MyDep5.jl 1.0.0" => Dict("MyDep3.jl 1.0.0" => Dict()), "MyDep3.jl 1.0.0" => Dict()), ) ) #! format: on if printTree() print(Tree(project_tree; name="complex dependencies")) end package_filter = [ "MyMainProject.jl", "MyDep1.jl", "MyDep2.jl", "MyDep3.jl", "MyDep4.jl", "MyDep5.jl", "MyDep6.jl", "MyDep7.jl", ] # sort all vectors to guaranty the same order -> guaranty is not important for the actual result, onyl for comparison @test sort( IntegrationTests.depending_projects("MyDep1.jl", package_filter, project_tree) ) == sort(["MyMainProject.jl"]) @test sort( IntegrationTests.depending_projects("MyDep2.jl", package_filter, project_tree) ) == sort(["MyMainProject.jl"]) # MyDep5.jl should only appears one time -> MyDep4.jl and MyDep7.jl has the same MyDep5.jl dependency @test sort( IntegrationTests.depending_projects("MyDep3.jl", package_filter, project_tree) ) == sort(["MyDep2.jl", "MyDep5.jl", "MyDep7.jl"]) @test sort( IntegrationTests.depending_projects("MyDep5.jl", package_filter, project_tree) ) == sort(["MyDep4.jl", "MyDep7.jl"]) # cannot find MyDep6.jl, because it is only a dependency of a foreign package @test isempty( IntegrationTests.depending_projects("MyDep6.jl", package_filter, project_tree) ) @test isempty(IntegrationTests.depending_projects("MyDep3.jl", ["Foo"], project_tree)) end @testset "circular dependency" begin # I cannot create a real circular dependency with this data structur, but if Circulation appears in an output, we passed MyDep1.jl and MyDep2.jl two times, which means it is a circle project_tree = Dict( "MyMainProject.jl 1.0.0" => Dict( "MyDep1.jl 1.0.0" => Dict( "MyDep2.jl 1.0.0" => Dict( "MyDep1.jl 1.0.0" => Dict( "MyDep2.jl 1.0.0" => Dict("Circulation" => Dict()) ), ), ), ), ) if printTree() print(Tree(project_tree; name="circular dependencies")) end package_filter = ["MyMainProject.jl", "MyDep1.jl", "MyDep2.jl"] @test sort( IntegrationTests.depending_projects("MyDep1.jl", package_filter, project_tree) ) == sort(["MyMainProject.jl", "MyDep2.jl"]) @test sort( IntegrationTests.depending_projects("MyDep2.jl", package_filter, project_tree) ) == sort(["MyDep1.jl"]) @test isempty(IntegrationTests.depending_projects("MyDep2.jl", ["Foo"], project_tree)) @test isempty( IntegrationTests.depending_projects("Circulation", package_filter, project_tree) ) end
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
code
108
using IntegrationTests using Test include("./depending_project.jl") include("./build_dependency_graph.jl")
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
1063
# Changelog ## Version 1.0.0 **Initial Release** ### New features - [#6](https://github.com/QEDjl-project/IntegrationTests.jl/pull/6): Adding the traversal algorithm to find packages for the integration tests in a Julia dependency graph - [#11](https://github.com/QEDjl-project/IntegrationTests.jl/pull/11): Add GitHub Actions example - [#16](https://github.com/QEDjl-project/IntegrationTests.jl/pull/16): Add GitLab CI example - [#19](https://github.com/QEDjl-project/IntegrationTests.jl/pull/19): Support Julia 1.10 - [#18](https://github.com/QEDjl-project/IntegrationTests.jl/pull/18): Add algorithm to build dependency graph of the active Julia project (replace implementation from PkgDependency) ### Maintenance - [#1](https://github.com/QEDjl-project/IntegrationTests.jl/pull/1): Add code formatter - [#5](https://github.com/QEDjl-project/IntegrationTests.jl/pull/4): Add initial documentation - [#7](https://github.com/QEDjl-project/IntegrationTests.jl/pull/7): Add integration test to test algorithm with on the fly created Julia package eco-system
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
3703
# IntegrationTests [![Doc Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://qedjl-project.github.io/IntegrationTests.jl/stable/) [![Doc Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://qedjl-project.github.io/IntegrationTests.jl/dev) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) # About `IntegrationTests.jl` provides tools and instructions for automatically creating integration tests for Julia projects in continuous integration pipelines such as [GitLab CI](https://docs.gitlab.com/ee/ci/) and [GitHub Actions](https://docs.github.com/en/actions). # What are integration tests Integration tests are required if you want to test whether different packages work together after a code change. For example, if package A is used by package B and the API of package A has been changed, the integration test checks whether package B still works. ## Example Project Our example package eco system contains the two packages `PkgA` and `PkgB`. `PkgB` uses a function from `PkgA`. ```mermaid graph TD pkgb(PkgB) -->|using| pkga(PkgA) ``` `PkgA` provides the following function: ```julia module PkgA foo(i) = i + 3 end ``` `PkgB` uses the function of `PkgA` in the following way: ```julia module PkgB using PkgA bar() = PkgA.foo(3) end ``` `PkgB` implements a test that checks whether `bar()` works: ```julia using PkgB using Test @testset "PkgB.jl" begin @test PkgB.bar() == 6 end ``` Suppose we change `foo(i) = i + 3` to `foo(i, j) = i + j + 3`. The `bar()` function in `PkgB` will no longer work because `bar()` calls `foo()` with only one parameter. The integration test will detect the problem and allow the developer to fix the problem before the pull request is merged. For example, a fix can be developed for `PkgB` that calls `foo()` with two arguments. # Functionality `IntegrationTests.jl` provides CI configuration files and a tool for the dynamic generation of integration tests for a specific project. The tool determines the dependent packages based on a given `Project.toml` of the entire package ecosystem. This is possible because a `Project.toml` of a package describes the dependencies as a graph. The graph can also contain the dependencies of the dependencies. Therefore, you can create a dependency graph of a package ecosystem. A package ecosystem can look like this: ```mermaid graph TD qed(QED.jl) --> base(QEDbase.jl) qed --> processes(QEDprocesses.jl) --> base qed --> fields(QEDfields.jl) --> base processes --> fields qed --> events(QEDevents.jl) --> base ``` [Project.toml](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/blob/08613adadea8a85bb4cbf47065d118eaec6f03d6/Project.toml) of the `QED.jl` package. For example, if `QEDfields.jl` is changed, `IntegrationTests.jl` returns that `QED.jl` and `QEDprocesses.jl` are dependent on `QEDfields.jl`, and we can generate the integration test jobs. Full CI pipeline examples for GitLab CI and GitHub Actions can be found in the [Pipeline Tutorials](https://qedjl-project.github.io/IntegrationTests.jl/dev/pipeline_tutorials/) section. For more details on the `IntegrationTests.jl` tool, see the [Integration Test Tool](https://qedjl-project.github.io/IntegrationTests.jl/dev/integration_test_tool/) section. # Credits This work was partly funded by the [Center for Advanced Systems Understanding (CASUS)](https://www.casus.science) that is financed by Germany’s Federal Ministry of Education and Research (BMBF) and by the Saxon Ministry for Science, Culture and Tourism (SMWK) with tax funds on the basis of the budget approved by the Saxon State Parliament.
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
2198
# About The scripts in this folder perform integration tests with an generated Julia package ecosystem. Therefore, the `create_package_eco_system()` function in `prepareIntegrationTest.jl` creates various Julia packages and sets the dependencies. The following diagram shows the created package ecosystem. ```mermaid graph TD MyPkgMeta(MyPkgMeta) --> MyPkgA(MyPkgA) MyPkgA --> MyPkgE(MyPkgE) MyPkgA --> MyPkgB(MyPkgB) --> MyPkgE MyPkgA --> MyPkgC(MyPkgC) --> MyPkgE MyPkgB --> MyPkgC MyPkgA --> MyPkgD(MyPkgD) --> MyPkgE MyPkgE --> JSON(JSON) MyPkgE --> Pkg(Pkg) MyPkgE --> Test(Test) MyPkgC --> JSON MyPkgB --> PkgTemplate(PkgTemplate) MyPkgA --> JSON ``` All packages starting with `MyPkg` are locally created packages. The other packages are third-party dependencies on existing packages from the Julia Registry. The `MyPkgMeta` is a specially created package. It is not part of the normal package ecosystem and is only needed to generate the correct list of dependencies. For more details, read the the [Integration Test Tool documentation](https://qedjl-project.github.io/IntegrationTests.jl/dev/integration_test_tool/). `MyPkgMeta` has only one dependency, namely the package `MyPkgA`. The `MyPkgA` itself has all other packages as direct dependencies. We use the environment of the `MyPkgMeta` package to construct the dependency tree for the `depending_projects()` function. We cannot use `MyPkgA` directly because a package is not a member of its own dependency graph. This means that `depending_projects()` would not check if `MyPkgA` is a dependency of the package we are looking for, as it is not part of the dependency graph. # Test scripts All test scripts use the same example ecosystem but the scripts perform different types of tests: - `getDeps.jl`: Calls the function `depending_projects()` and compares the generated list of package names with a list of expected package names. - `generateGithubActions.jl`: Calls the `depending_projects()` function, takes the generated list of package names and print it. Then GitHub Action create and execute a CI job for each entry. Then creates a GitHub action request for each package name.
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
170
# References ## Public API ```@autodocs Modules = [IntegrationTests] Private = false ``` ## Internal API ```@autodocs Modules = [IntegrationTests] Public = false ```
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
6679
# Integration Test Tool The public API `IntegrationTests.jl` provides a function called `depending_projects()`, which returns a vector of package names that depend on the package `package_name`. In addition to the package name, the function also requires a package name filter `package_filter` and a project dependency tree `project_tree`. The project dependency can be constructed from the currently active Julia project environment, which is highly recommended. ```@docs depending_projects(package_name::AbstractString, package_filter::Union{<:AbstractString,Regex}, project_tree::AbstractDict) ``` An example for using the `depending_projects()` function may look as follows: ```julia-repl julia> using IntegrationTests [ Info: Precompiling IntegrationTests [6be7cfa2-1838-408e-bc49-3a824ac3a1fb] julia> using Pkg julia> Pkg.activate(".ci/example_project/MetaTestPkg/") Activating project at `~/projects/IntegrationTests.jl/.ci/example_project/MetaTestPkg` julia> depending_projects("MyPkgFields", r"MyPkg*") 2-element Vector{String}: "MyPkgProcesses" "MyPkgMain" julia> ``` # Package Filter The `package_filter` is a string or a regular expression, which constrains the search space of the dependency graph. All packages and dependencies of packages must match the filter, otherwise they are ignored during searching. For instance, if we set the package filter to `r"^MyPkg*"`, the packages `MyPkgMain`, `MyPkgA`, `MyPkgB`, and `MyPkgC` are traversed in the following diagram. `ExternalDep1` and `ExternalDep2` are ignored. ```mermaid graph TD MyPkgMain -->|using| MyPkgA MyPkgMain -->|using| MyPkgB MyPkgMain -->|using| ExternDep1 MyPkgA -->|using| MyPkgC MyPkgA -->|using| ExternDep2 ``` The idea behind the package filter is that there are nodes in the dependency graph that can't be changed directly. Let's assume we are the maintainer of all packages starting with `MyPkg` and the following dependency graph is given: ```mermaid graph TD MyPkgMain -->|using| MyPkgA MyPkgMain -->|using| MyPkgB MyPkgMain -->|using| ExternDep1 -->|using| MyPkgA MyPkgA -->|using| MyPkgC MyPkgA -->|using| ExternDep2 ``` With the package filter `r"*"`, which means traversing all dependencies, the result would be `["MyPkgMain", "ExternDep1"]` if we are searching for `MyPkgA`. We are not the maintainer of `ExternDep1`, therefore we can not directly make changes in `ExternDep1` and it makes less sense to test `ExternDep1` with our code changes. ## Package Filter: Special Cases ### Dependencies of non matching packages In the following diagram, `MyPkgA` is not found with the package filter `r"^MyPkg*"`, because the traversing algorithm does not traverse `ExternDep1`. Therefore the dependencies of `ExternDep1` are not checked. ```mermaid graph TD MyPkgMain -->|using| ExternDep1 -->|using| MyPkgA ``` ### The top graph package Sometimes the top graph package does not have the same naming scheme as all other packages. The section [Project Dependency Tree](#Project-Dependency-Tree) contains examples of this. If the top package is not included in the package filter, the entire graph is not traversed and the result is empty. ```mermaid graph TD MetaTestPkg -->|using| MyPkgMain -->|using| MyPkgA MyPkgMain -->|using| MyPkgB ``` `depending_projects()` returns `[]` for the package filter `r"^MyPkg*"` and the package `MyPkgB`. The package filter `r"^MyPkg*|^MetaTestPkg$` returns `["MyPkgA"]`. # Project Dependency Tree We strongly recommend using a `Project.toml` of a package from the package ecosystem as input for `depending_projects()` instead of manually defining the project dependency graph. This is because a manually defined dependency tree can become obsolete. In contrast, the `Project.toml` must be up to date, otherwise, the Julia application will not work. The crucial question is which `Project.toml` should be used. The dependency graph of a `Project.toml` can only be constructed in one direction. You can only use the dependencies of the packages. From which package a package is used can only be determined if you came from the package before. Let's assume we have the following package ecosystem: ```mermaid graph TD MyPkgMain -->|using| MyPkgA MyPkgMain -->|using| MyPkgB -->|using| MyPkgD MyPkgB -->|using| MyPkgE -->|using| MyPkgF MyPkgMain -->|using| MyPkgC ``` If we take the `Project.toml`[\*] of `MyPkgMain`, we get the complete graph. If we take the `Project.toml` of `MyPkgB`, we get the following graph: ```mermaid graph TD MyPkgB -->|using| MyPkgD MyPkgB -->|using| MyPkgE -->|using| MyPkgF ``` !!! note The dependency tree created with the `Project.toml` of `MyPkgMain` does not contain `MyPkgMain` itself. This is a technical detail from Julia. It will contain the dependencies `MyPkgA` to `MyPkgF`. To solve the problem, an additional package is needed, which has only the dependency `MyPkgMain`: `Project.toml` ```yaml name = "MetaTestPkg" uuid = "b849e8ad-e76f-4e2e-b89d-52f4e57509ba" authors = ["Simeon Ehrig <[email protected]>"] version = "0.1.0" [deps] MyPkgMain = "679daff0-1f79-468a-9a2e-69c3994cafb1" ``` If we use the `Project.toml` of `MetaTestPkg`, we get the complete dependency graph with `MyPkgMain`. !!! note To select a package and create the dependency graph, you need to activate the Julia environment of the package with `Pkg.activate()`. For example, `Pkg.activate("path/to/MetaTestPkg")`. ## Project Dependency Tree: Special cases Let's assume we have the following package ecosystem structure: ```mermaid graph TD MyPkgA -->|using| MyPkgD MyPkgB -->|using| MyPkgD MyPkgB -->|using| MyPkgE MyPkgC -->|using| MyPkgE MyPkgC -->|using| MyPkgF MyPkgD -->|using| MyPkgG MyPkgD -->|using| MyPkgH MyPkgE -->|using| MyPkgI ``` There is no package we can use to build the entire dependency graph. Therefore, an auxiliary package is required to generate the integration tests for the whole ecosystem: ```mermaid graph TD MetaTestPkg -->|using| MyPkgA MetaTestPkg -->|using| MyPkgB MetaTestPkg -->|using| MyPkgC MyPkgA -->|using| MyPkgD MyPkgB -->|using| MyPkgD MyPkgB -->|using| MyPkgE MyPkgC -->|using| MyPkgE MyPkgC -->|using| MyPkgF MyPkgD -->|using| MyPkgG MyPkgD -->|using| MyPkgH MyPkgE -->|using| MyPkgI ``` If we use the `Project.toml` of `MetaTestPkg`, we can construct the entire graph. !!! note The "MetaTestPkg" does not need to be registered. It can be saved locally in the project repository or created dynamically during the generation of the integration tests.
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
1.0.0
836de2fec5b1ad79457e7614a36dc83e3b47e3dd
docs
5145
# Pipeline Tutorials This section shows how to set up CI tests for different platforms with `IntegrationTests.jl`. In general, any CI platform can use `IntegrationTests.jl` if it fulfills a requirement. It must be possible to generate new jobs during the runtime of a CI pipeline depending on the output of a Julia script. ## GitLab CI GitLab CI offers the [parent-child-pipeline](https://docs.gitlab.com/ee/ci/pipelines/downstream_pipelines.html#parent-child-pipelines) function. This allows you to generate GitLab CI job yaml code in a GitLab CI job and start the generated jobs in the same pipeline. For our example, let's assume that we use a Julia script called `generateIntegrationTests.jl` that uses `IntegrationTests::depending_projects()` to generate the integration tests. This script generates valid GitLab CI yaml code and outputs it to stdout. The GitLab CI code in `.gitlab-ci.yml` could look like this: ```yaml stages: - generator - runTests generateIntegrationTests: stage: generator image: "julia:1.10" script: - julia --project=. -e 'import Pkg; Pkg.instantiate()' - julia --project=. generateIntegrationTests.jl 2> /dev/null 1> jobs.yaml - cat jobs.yaml interruptible: true artifacts: paths: - jobs.yaml expire_in: 1 week runIntegrationTests: stage: runTests trigger: include: - artifact: jobs.yaml job: generateIntegrationTests strategy: depend ``` The content of the dynamically generated `jobs.yaml` could look as follows for the example packages `MyPkgA` and `MyPkgB`: ```yaml integrationTestMyPkgB: image: alpine:latest script: - echo "run Integration Test for package MyPkgB" integrationTestMyPkgA: image: alpine:latest script: - echo "run Integration Test for package MyPkgA" ``` ## GitHub Actions GitHub provides the [matrix](https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs) mechanism to automatically generate jobs from a given input. Normally, the input is hardcoded as one or more `JSON` arrays in the Github Actions `yaml` file. A small workaround allows the input of a `JSON` array to be generated during the runtime of a Github Actions job. This makes it possible to dynamically create new jobs during the runtime of the CI pipeline. For our example, let's assume that we use a Julia script named `generateIntegrationTests.jl` that uses `IntegrationTests::depending_projects()` to generate the integration tests. The GitHub Actions workflow looks like this: ```yaml name: IntegrationTest on: push: branches: - main - dev tags: ['*'] pull_request: workflow_dispatch: concurrency: # Skip intermediate builds: always. # Cancel intermediate builds: only if it is a pull request build. group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} jobs: generate: name: Github Action - Generator Integration Jobs runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: julia-actions/setup-julia@v1 with: version: "1.10" arch: x64 - uses: julia-actions/cache@v1 - uses: julia-actions/julia-buildpkg@v1 - id: set-matrix run: echo "matrix=$(julia --project=${GITHUB_WORKSPACE} generateIntegrationTests.jl 2> /dev/null)" >> $GITHUB_OUTPUT outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} run-matrix: needs: generate runs-on: ubuntu-latest strategy: matrix: package: ${{ fromJson(needs.generate.outputs.matrix) }} steps: # define the job body of your integration test here depending on the `matrix.package` parameter - run: echo "run Integration Test for package ${{ matrix.package }}" ``` The workflow contains two jobs. The first job is the `generate` job, which generates a list of package names to be tested as an integration test. The `run-matrix` job is a template that takes a package name and runs an integration test job for the specific package name. Therefore, the `run-matrix` is executed `N` times. !!! note `matrix: ${{ steps.set-matrix.outputs.matrix }}` expects a `JSON` array. Fortunately, when we print a Julia vector, the output is in the form of a `JSON` array. Therefore, you can simply use `print(depending_projects())` to generate the output of `generateIntegrationTests.jl`. But be careful not to print any other output, for example, the activation message of `Pkg.activate`. This output can be redirected to `2> /dev/null` for example. Source: https://tomasvotruba.com/blog/2020/11/16/how-to-make-dynamic-matrix-in-github-actions/ # Real World Example The `IntegrationTest.jl` package uses the GitLab CI `parent-child-pipeline` and the GitHub Action `matrix` function for its own CI tests to check the functionality. The generator scripts can be found in the `.ci` folder. The GitLab CI Job yaml code is written in the `.gitlab-ci.yml` and the GitHub Action Code is written in the `.github/workflows/integrationTests.yml`.
IntegrationTests
https://github.com/QEDjl-project/IntegrationTests.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
524
using Pkg Pkg.add([ PackageSpec( name = "BenchmarkConfigSweeps", url = "https://github.com/tkf/BenchmarkConfigSweeps.jl.git", ), PackageSpec( name = "BenchPerf", # path = dirname(@__DIR__), url = "https://github.com/tkf/BenchPerf.jl.git", ), PackageSpec( name = "BenchPerfConfigSweeps", # path = dirname(@__DIR__), url = "https://github.com/tkf/BenchPerf.jl.git", subdir = "lib/BenchPerfConfigSweeps", ), ]) Pkg.instantiate()
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
431
function preprocess_natural_comment(str) output = IOBuffer() input = IOBuffer(str) while !eof(input) ln = readline(input; keep = true) # Always treat indented comments as in-code comments m = match(r"^( +)# (.*)"s, ln) if m !== nothing print(output, m[1], "## ", m[2]) continue end print(output, ln) end return String(take!(output)) end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
723
import BenchmarkTools function set_quick_params!(bench) bench.params.seconds = 0.001 bench.params.evals = 1 bench.params.samples = 1 bench.params.gctrial = false bench.params.gcsample = false return bench end foreach_benchmark(f!, bench::BenchmarkTools.Benchmark) = f!(bench) function foreach_benchmark(f!, group::BenchmarkTools.BenchmarkGroup) for x in values(group) foreach_benchmark(f!, x) end end function quick!(suite) foreach_benchmark(set_quick_params!, suite) return suite end function maybe_quick!(suite) if lowercase(get(ENV, "QUICK", "false")) == "true" @info "Use quick-run benchmark parameters" quick!(suite) end return suite end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1418
import BenchPerf import Random using BenchmarkTools include("utils.jl") function increment_at!(xs, indices) for i in indices @inbounds xs[i] += 1 end end function threaded_increment_at!(xss, iss, nrepeats) Threads.@threads for j in eachindex(xss, iss) for _ in 1:nrepeats increment_at!(xss[j], iss[j]) end end end group = BenchmarkGroup() for e in 5:22 n = 2^e nrepeats = nrepeats_from_n(n) group["n=$n"] = bench = @benchmarkable( threaded_increment_at!(xss, iss, $nrepeats), setup = begin Random.seed!(43) # Iteration over nthreads can be done in a single process. But it's # done via BenchmarkConfigSweeps just for the demo. nt = Threads.nthreads() n = $n xss = [zeros(Int, n) for _ in 1:nt] iss = [rand(1:n, n) for _ in 1:nt] end, # Larger `samples` (than the default: 10_000) to bound the benchmark by # the time limit. samples = 1_000_000, ) # Not tuning it like ../random_increments/benchmarks.jl since `nrepeats` # already takes care of it. To verify this, uncomment the following line, # run the benchmarks, and then check `unique(df.evals)`. #= if e < 15 tune!(bench) end =# end include("../quick.jl") maybe_quick!(group) SUITE = BenchPerf.wrap(group; detailed = 1)
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
2629
using BenchPerfConfigSweeps using DataFrames using VegaLite include("utils.jl") sweepresult = BenchPerfConfigSweeps.load(joinpath(@__DIR__, "build")) df_raw = DataFrame(sweepresult) let global df = select(df_raw, Not(:trial)) df[:, :time_ns] = map(t -> minimum(t.benchmark).time, df_raw.trial) # df[:, :evals] = map(t -> t.benchmark.params.evals, df_raw.trial) df[:, :L1_miss_percent] = map(df_raw.trial) do t t.perf["L1-dcache-load-misses"] / t.perf["L1-dcache-loads"] * 100 end df[:, :LL_miss_percent] = map(df_raw.trial) do t get(t.perf, "LLC-load-misses", missing) / get(t.perf, "LLC-loads", missing) * 100 end nrepeats = nrepeats_from_n.(df.n) bytes = df.n .* 2 * sizeof(Int) global throughput_unit = "GiB/thread/sec" df[:, :throughput] = bytes .* nrepeats ./ 2^30 ./ (df.time_ns / 1e9) df[:, :MiB] = bytes ./ 2^20 df[:, :total_MiB] = df.nthreads .* bytes ./ 2^20 df end df |> [ @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) ] df |> [ @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, color = {:nthreads, type = :nominal}, ) ] df |> [ @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, color = {:nthreads, type = :nominal}, ) ]
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
270
using BenchmarkConfigSweeps if Sys.CPU_THREADS < 8 threads = [1, Sys.CPU_THREADS] else threads = [1, 4, 8] end BenchmarkConfigSweeps.run( joinpath(@__DIR__, "build"), joinpath(@__DIR__, "benchmarks.jl"), BenchmarkConfigSweeps.nthreads.(threads), )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
81
nrepeats_from_n(n) = if n < 2^22 2^22 ÷ n else 1 end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
1561
import BenchPerf import Random using BenchmarkTools include("utils.jl") function sum_gather(xs, indices) s = zero(eltype(xs)) for i in indices s += @inbounds xs[i] end return s end function threaded_sum_gather(xss, iss, nrepeats) sums = zeros(eltype(eltype(xss)), length(xss)) Threads.@threads for j in eachindex(xss, iss) s = sums[j] for _ in 1:nrepeats s += sum_gather(xss[j], iss[j]) end sums[j] = s end return sum(sums) end group = BenchmarkGroup() for e in 5:22 n = 2^e nrepeats = nrepeats_from_n(n) group["n=$n"] = bench = @benchmarkable( threaded_sum_gather(xss, iss, $nrepeats), setup = begin Random.seed!(43) # Iteration over nthreads can be done in a single process. But it's # done via BenchmarkConfigSweeps just for the demo. nt = Threads.nthreads() n = $n xss = [zeros(Int, n) for _ in 1:nt] iss = [rand(1:n, n) for _ in 1:nt] end, # Larger `samples` (than the default: 10_000) to bound the benchmark by # the time limit. samples = 1_000_000, ) # Not tuning it like ../random_increments/benchmarks.jl since `nrepeats` # already takes care of it. To verify this, uncomment the following line, # run the benchmarks, and then check `unique(df.evals)`. #= if e < 15 tune!(bench) end =# end include("../quick.jl") maybe_quick!(group) SUITE = BenchPerf.wrap(group; detailed = 1)
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
3861
import BenchPerfConfigSweeps import DisplayAs using DataFrames using VegaLite include("utils.jl") sweepresult = BenchPerfConfigSweeps.load(joinpath(@__DIR__, "build")) df_raw = DataFrame(sweepresult) let global df = select(df_raw, Not(:trial)) df[:, :time_ns] = map(t -> minimum(t.benchmark).time, df_raw.trial) # df[:, :evals] = map(t -> t.benchmark.params.evals, df_raw.trial) df[:, :L1_miss_percent] = map(df_raw.trial) do t t.perf["L1-dcache-load-misses"] / t.perf["L1-dcache-loads"] * 100 end df[:, :LL_miss_percent] = map(df_raw.trial) do t get(t.perf, "LLC-load-misses", missing) / get(t.perf, "LLC-loads", missing) * 100 end nrepeats = nrepeats_from_n.(df.n) bytes = df.n .* 2 * sizeof(Int) global throughput_unit = "GiB/thread/sec" df[:, :throughput] = bytes .* nrepeats ./ 2^30 ./ (df.time_ns / 1e9) df[:, :MiB] = bytes ./ 2^20 df[:, :total_MiB] = df.nthreads .* bytes ./ 2^20 df end resultdir = joinpath(@__DIR__, "result") mkpath(resultdir) saveresult(; plots...) = saveresult(:png, :svg; plots...) function saveresult(exts::Symbol...; plots...) for (k, v) in plots for e in exts save(joinpath(resultdir, "$k.$e"), v) end end end nothing # hide plt_throughput_cache_miss_vs_different_input_sizes = df |> [ @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) ] saveresult(; plt_throughput_cache_miss_vs_different_input_sizes) plt_throughput_cache_miss_vs_different_input_sizes plt_throughput_cache_miss_vs_different_input_sizes |> DisplayAs.PNG plt_throughput_cache_miss_vs_per_thread_size = df |> [ @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, color = {:nthreads, type = :nominal}, ) ] saveresult(; plt_throughput_cache_miss_vs_per_thread_size) plt_throughput_cache_miss_vs_per_thread_size plt_throughput_cache_miss_vs_per_thread_size |> DisplayAs.PNG #- plt_throughput_cache_miss_vs_total_size = df |> [ @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:throughput, title = throughput_unit}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:L1_miss_percent, title = "L1 cache miss [%]"}, color = {:nthreads, type = :nominal}, ) @vlplot( mark = {:line, point = true}, x = {:total_MiB, scale = {type = :log}}, y = {:LL_miss_percent, title = "LL cache miss [%]"}, color = {:nthreads, type = :nominal}, ) ] saveresult(; plt_throughput_cache_miss_vs_total_size) plt_throughput_cache_miss_vs_total_size plt_throughput_cache_miss_vs_total_size |> DisplayAs.PNG #- plt_throughput_cache_miss_vs_total_size #src
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
817
# # Multi-thread `sum_gather` include("plots.jl"); # ## Throughput, L1, and last-level (LL) cache misses # # (Note: the LL cache miss data may not be available in some machines.) # # The same set of data is plotted with two different metrics for the input size # (x-axis). # ### x-axis: input size per thread # The curves for L1 cache miss are virtually identical across benchmarks that # are run with different number of threads (color, `nthreads`). plt_throughput_cache_miss_vs_per_thread_size #- # ### x-axis: total input size # The rising part of the curves for LL cache miss for when the total input size # is large coincide across benchmarks with different number of threads (color, # `nthreads`). This is where the total input size crosses the LL cache size. plt_throughput_cache_miss_vs_total_size #-
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
270
using BenchmarkConfigSweeps if Sys.CPU_THREADS < 8 threads = [1, Sys.CPU_THREADS] else threads = [1, 4, 8] end BenchmarkConfigSweeps.run( joinpath(@__DIR__, "build"), joinpath(@__DIR__, "benchmarks.jl"), BenchmarkConfigSweeps.nthreads.(threads), )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
165
using Literate include("../literate_utlis.jl") Literate.notebook( joinpath(@__DIR__, "report.jl"), @__DIR__; preprocess = preprocess_natural_comment, )
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
81
nrepeats_from_n(n) = if n < 2^22 2^22 ÷ n else 1 end
BenchPerf
https://github.com/tkf/BenchPerf.jl.git
[ "MIT" ]
0.1.0
b42a1090f1929847055997b0803b0d5cf3e2177e
code
901
import BenchPerf import Random using BenchmarkTools function increment_at!(xs, indices) for i in indices @inbounds xs[i] += 1 end end CACHE = Dict() group = BenchmarkGroup() for e in 5:22 n = 2^e CACHE[e] = (xs = zeros(Int, n), indices = rand(1:n, n)) group["n=$n"] = bench = @benchmarkable( increment_at!(xs, indices), setup = begin inputs = CACHE[$e]::$(typeof(CACHE[e])) xs = inputs.xs indices = inputs.indices fill!(xs, 0) end, # Larger `samples` (than the default: 10_000) to bound the benchmark by # the time limit. samples = 1_000_000, ) # Manually tune the benchmark since `BenchmarkConfigSweeps` does not do it # ATM. if e < 15 tune!(bench) end end include("../quick.jl") maybe_quick!(group) SUITE = BenchPerf.wrap(group; detailed = 1)
BenchPerf
https://github.com/tkf/BenchPerf.jl.git