Utils
ElemCo.Utils — Module
various utilities
Exported functions
ElemCo.Utils.allocfree_permutedims! — Method
allocfree_permutedims!(dest::AbstractArray{T1,N}, src::AbstractArray{T2,N}, perm::NTuple{N,Int}) where {T1,T2,N}Copy data from src to dest with the dimensions permuted according to perm. The dest array is expected to be preallocated and have the same size as src after permutation. This function has the same functionality as permutedims!, but has much lower allocation overhead for views of arrays (there is still one allocation left somewhere...).
Example
julia> src = rand(3, 4)
julia> dest = zeros(10, 10)
julia> allocfree_permutedims!(@view(dest[1:4,2:4]), src, (2, 1))ElemCo.Utils.amdmkl — Function
amdmkl(reset::Bool=false)Create a modified libmkl_rt.so and libmkl_core.so to make MKL work fast on "Zen" AMD machines (e.g., Ryzen series). Solution is based on this forum post.
This function is only needed on AMD machines. In order to execute it, call amdmkl() in a separate Julia session (not in the same session where you want to run calculations). For example, your workflow could look like this:
> julia -e 'using ElemCo; ElemCo.amdmkl()'
> julia input.jlwhere input.jl is your script that uses ElemCo.jl. The changes can be reverted by calling amdmkl(true).
ElemCo.Utils.argmaxN — Method
argmaxN(vals, N; by::Function=identity)Return the indices of the N largest elements in vals.
The order of equal elements is preserved. The keyword argument by can be used to specify a function to compare the elements, i.e., the function is applied to the elements before comparison.
Example
julia> argmaxN([1,2,3,4,5,6,7,8,9,10], 3)
3-element Vector{Int64}:
10
9
8
julia> argmaxN([1,2,3,4,5,-6,-7,-8,-9,-10], 3; by=abs)
3-element Vector{Int64}:
10
9
8
julia> argmaxN([1.0, 1.10, 1.112, -1.113, 1.09], 3; by=x->round(abs(x),digits=2))
3-element Vector{Int64}:
3
4
2ElemCo.Utils.clean_exprstring — Method
clean_exprstring(expr)Return a clean string from an expression, i.e., without empty spaces and extra parentheses.
Examples
julia> clean_exprstring(:(SVD-CCSD))
"SVD-CCSD"
julia> clean_exprstring(:(eom-svd-df-ccsd(t)))
"eom-svd-df-ccsd(t)"ElemCo.Utils.draw_endline — Function
draw_endline()Print a line of ═.
ElemCo.Utils.draw_line — Function
draw_line(n = 63)Print a thick line of n characters.
ElemCo.Utils.free_memory — Method
free_memory()Return the amount of free memory in bytes.
ElemCo.Utils.get_spaceblocks — Function
get_spaceblocks(space, maxblocksize=128, strict=false)Generate ranges for block indices for space (for loop over blocks).
space is a range or an array of indices. Even if space is non-contiguous, the blocks will be contiguous. If strict is true, the blocks will be of size maxblocksize (except for the last block and non-contiguous index-ranges). Otherwise the actual block size will be as close as possible to blocksize such that the resulting blocks are of similar size.
ElemCo.Utils.is_options_block — Method
is_options_block(arg)Check if arg is a begin...end block for local options.
ElemCo.Utils.kwarg_provided_in_macro — Method
kwarg_provided_in_macro(kwargs, key::Symbol)Check whether key is in kwargs.
This is used in macros to check whether a keyword argument is passed. The keyword argument in question key is passed as a symbol, e.g. :thr. kwargs is the keyword argument list passed to the macro.
ElemCo.Utils.last_energy — Method
last_energy(energies::OutDict)Return the last energy in energies.
ElemCo.Utils.mainname — Method
mainname(file::String)Return the main name of a file, i.e. the part before the last dot and the extension.
Examples:
julia> mainname("~/test.xyz")
("test", "xyz")
julia> mainname("test")
("test", "")ElemCo.Utils.modifyvalueswith! — Method
modifyvalueswith!(combine, dict::AbstractDict, other::AbstractDict)Modify the values in dict using the values from other and the function combine.
For each key in other, if the key exists in dict, the value in dict is updated to combine(v1, v2), where v1 is the value in dict and v2 is the value in other.
Similar to mergewith!, but only merges existing keys in dict.
ElemCo.Utils.parse_options_block — Method
parse_options_block(block::Expr)Parse a begin...end block with local options and return code that constructs a NamedTuple for with_local_options.
Each line in the block should have one of these formats:
- Set-macro style:
@set option_name key1=val1 key2=val2 ... - Function-call style:
option_name(key1=val1, key2=val2, ...)
Multiple lines for the same option category are merged together.
For example:
begin
@set wf charge=-1 ms2=1
@set cc maxit=30
@set cc thr=1.e-10
end
# or equivalently:
begin
wf(charge=-1, ms2=1)
cc(maxit=30, thr=1.e-10)
endReturns an expression that creates: (wf=(charge=-1, ms2=1), cc=(maxit=30, thr=1.e-10))
ElemCo.Utils.print_info — Function
print_info(info::AbstractString, additional_info::AbstractString="")Print info between two lines.
If additional not empty: additional info after main.
ElemCo.Utils.print_memory — Method
print_memory(EC::AbstractECInfo, mem1, info::AbstractString, verb::Int)Print memory usage with message info if verbosity verb is smaller than PrintOptions.memory.
Note that memory is also used by other processes and the operating system, so the memory usage reported here is merely an estimate.
ElemCo.Utils.print_time — Method
print_time(EC::AbstractECInfo, t1, info::AbstractString, verb::Int)Print time with message info if verbosity verb is smaller than PrintOptions.time.
ElemCo.Utils.reshape_buf — Method
reshape_buf(buf::AbstractVector, dims...; offset=0)Reshape a buffer buf of type AbstractVector to the given dimensions dims..., starting from offset. The buffer is expected to be large enough to fit the reshaped data.
Example
julia> buf = zeros(1000)
julia> reshaped_buf = reshape_buf(buf, 10, 10)ElemCo.Utils.separate_kwargs — Method
separate_kwargs(args)Separate keyword arguments from positional arguments in macro input.
Returns (positional_args, kwargs) where:
positional_args: Vector of non-keyword argumentskwargs: Vector ofExpr(:kw, key, esc(value))for keyword arguments
Keyword arguments are expressions with head :(=).
Example
# In a macro definition:
macro mymacro(args...)
positional, kwargs = separate_kwargs(args)
# positional contains non-keyword args
# kwargs can be splatted: some_function(x; $(kwargs...))
endElemCo.Utils.setdiff4dict! — Method
setdiff4dict!(dict::AbstractDict, keys)Delete all keys from dict.
The same behavior as setdiff! for sets.
ElemCo.Utils.subspace_in_space — Method
subspace_in_space(subspace, space)Return the positions of subspace in space (with respect to space)
subspace and space are lists of indices with respect to the full space (e.g., 1:norb).
Examples
julia> get_subspace_of_space([1,3,5], [1,3,4,5])
3-element Array{Int64,1}:
1
2
4ElemCo.Utils.subspace_in_space — Method
subspace_in_space(subspace::UnitRange{Int}, space::UnitRange{Int})Return the positions of subspace in space (with respect to space)
subspace and space are ranges of indices with respect to the full space (e.g., 1:norb).
Examples
julia> get_subspace_of_space(4:6, 2:7)
3:5ElemCo.Utils.substr — Function
substr(string::AbstractString, start::Int, len::Int=-1)Return substring of string starting at start spanning len characters (including unicode). If len is not given, the substring spans to the end of string.
Example:
julia> substr("λabδcd", 2, 3)
"abδ"ElemCo.Utils.substr — Method
substr(string::AbstractString, range::UnitRange{Int})Return substring of string defined by range (including unicode).
Example:
julia> substr("λabδcd", 2:4)
"abδ"ElemCo.Utils.warnerror — Function
warnerror(msg::AbstractString, err=false)Print a warning message. If err is true, the message is printed as an error message.
The message is printed with a scull emoji.
Example
julia> warnerror("This is a warning message.")ElemCo.Utils.xpath — Method
xpath(xpath::AbstractString, node::Node)Search for nodes matching the XPath xpath in the XML node. Returns a vector of nodes that match the XPath expression. If xpath is an empty string, it returns the node itself.
Supports basic XPath 1.0 syntax:
/tag1/tag2- absolute path from root (here: root == current node)tag1/tag2- relative path from current node//tag- descendant-or-self axis (recursive search)/- root node (here: root == current node)*- any element nodetag[@attr=value]- elements with specific attribute values
Examples:
/node/child- child elements named 'child' under the root 'node'//item- all 'item' elements anywhere in the treeparent/child- 'child' elements that are direct children of 'parent'//variable[@name="x"]- variable elements with name attribute equal to "x"
ElemCo.Utils.BufVec — Type
BufVec{T,A<:AbstractVector{T}} <: AbstractVector{T}Type-stable buffered vector with pre-allocated storage and parametrized buffer type.
The buffer does NOT auto-grow. Attempting to push beyond capacity will error (unless @inbounds is used, which skips the check).
Type Parameters
T- Element typeA- Buffer type (e.g.,Vector{T},SubArray{T}, etc.)
Fields
data::A- Pre-allocated storage bufferlength::Int- Current number of elements in use
Example
# Create a buffer from a pre-allocated vector
data = Vector{Float64}(undef, 100)
buf = BufVec(data)
# Add elements (errors if exceeding capacity)
push!(buf, 1.0)
push!(buf, 2.0)
# Access elements
x = buf[1]
# Iterate with SIMD
s = 0.0
@inbounds @simd for i in 1:length(buf)
s += buf[i]
end
# Clear for reuse
empty!(buf)ElemCo.Utils.OutDict — Type
OutDictAn ordered descriptive dictionary that maps keys of type String to values of type Float64.
ElemCo.Utils.PairDict — Type
PairDictA very lightweight immutable Dict that is just a Tuple of two values, i.e., it can hold only one key-value pair.
Useful for merging results into a Dict without creating intermediate Dicts.
ElemCo.Utils.@assert_devel — Macro
@assert_devel(cond, text=nothing)Assert cond only in development mode.
If text is given, it is used as the assertion message. Development mode is determined by VersionInfo.devel().
Copied from ToggleableAsserts.jl.
ElemCo.Utils.@istoplevel — Macro
@istoplevelMacro to check if the current scope is the top level scope.
(from https://discourse.julialang.org/t/is-there-a-way-to-determine-whether-code-is-toplevel)
ElemCo.Utils.@pib — Macro
@pibAlias for Base.@propagate_inbounds
ElemCo.Utils.@var2string — Macro
@var2string(var, strvar="", type=AbstractString)Return string representation of var.
If var is a String (or type) variable, return the value of the variable. Otherwise, return the string representation of var (or strvar if provided).
Examples
julia> @var2string(CCSD)
"CCSD"
julia> CCSD = "UCCSD";
julia> @var2string(CCSD)
"UCCSD"Internal functions
ElemCo.Utils.add_kwarg! — Method
add_kwarg!(opts_dict, opt_name, item)Add a key=value pair item to opts_dict under category opt_name.
The item must be an expression with head :(=) or :kw. The value is escaped so variables are evaluated in the caller's scope.
ElemCo.Utils.draw_thin_line — Function
draw_thin_line(n = 63)Print a thin line of n characters.
ElemCo.Utils.evaluate_predicate — Method
evaluate_predicate(predicate::AbstractString, node::Node)Evaluate a predicate against a node. Currently supports:
- @attr=value
ElemCo.Utils.matches_predicates — Method
matches_predicates(node::Node, predicates::Vector{String})Check if a node matches all given predicates.
ElemCo.Utils.parse_call_options! — Method
parse_call_options!(opts_dict, arg)Parse a function-call style option expression (category(key=val, ...)) and add entries to opts_dict.
ElemCo.Utils.parse_macro_options! — Method
parse_macro_options!(opts_dict, arg)Parse a macro-style option expression (@set category key=val ...) and add entries to opts_dict.
ElemCo.Utils.parse_step_with_predicate — Method
parse_step_with_predicate(step::AbstractString)Parse a step that may contain predicates like "tag[@attr=value]". Returns (tag_name, predicates) where predicates is a vector of predicate strings.
ElemCo.Utils.xspyder — Method
xspyder(xtag::AbstractString, node::Node)Recursively search for nodes matching the xml tag xtag in the XML node. Returns a vector of nodes that match the tag. If xtag is an empty string, it returns the node itself.