licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.2 | 93eb72f6f145e0d1a48a6e61a794b1035d4f6951 | code | 3458 | module MoziFESection
export BeamSection
export RectangleSection,HSection,ISection,BoxSection,PipeSection,CircleSection
@enum SectionType begin
GENERAL_SECTION=0
ISECTION=1
HSECTION=2
BOX=3
PIPE=4
CIRCLE=5
RECTANGLE=6
end
struct BeamSection
id::String
hid::Int
A::Float64
I₂::Float64
I₃::Float64
J::Float64
As₂::Float64
As₃::Float64
W₂::Float64
W₃::Float64
sec_type::SectionType
sizes::Vector
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,sec_type=GENERAL_SECTION,sizes=[])=new(string(id),hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,sec_type,sizes)
end
# function BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃)
# id=string(id)
# end
function RectangleSection(id,hid,h,b)::BeamSection
id=string(id)
A=h*b
I₃=b*h^3/12
I₂=h*b^3/12
# bb,aa=sort([h,b])
# J=aa*bb^3*(1/3-0.21*bb/aa*(1-bb^4/12/aa^4))
β = MembraneMeta(h, b)
J = h * b * b * b * β
As₂=5.0 / 6 * h * b
As₃=5.0 / 6 * h * b
W₃=I₃/h*2
W₂=I₂/b*2
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,RECTANGLE,[h,b])
end
function HSection(id,hid,h,b,tw,tf)::BeamSection
id=string(id)
A=b*tf*2+tw*(h-2*tf)
β=MembraneMeta(tf, b)
J=tf * b * b * b * β * 2
β = MembraneMeta(tw, h - 2 * tf)
J+=tw * (h - 2 * tf)^3 * β
I₃=b*h^3/12-(b-tw)*(h-2*tf)^3/12
I₂=2*tf*b^3/12+(h-2*tf)*tw^3/12
As₂=tw * h
As₃=5.0 / 3 * tf * b
W₃=I₃/h*2
W₂=I₂/b*2
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,HSECTION,[h,b,tw,tf])
end
function ISection(id,hid,h,b1,b2,tw,tf1,tf2)::BeamSection
id=string(id)
hw=h-tf1-tf2
A=b1*tf1+b2*tf2+tw*hw
y0=(b1*tf1*(h-tf1/2)+b2*tf2*tf2/2+hw*tw*(hw/2+tf2))/A
β=MembraneMeta(tf1, b1)
J=tf1 * b1^3 * β
β=MembraneMeta(tf2, b2)
J+=tf2 * b2^3* β
β = MembraneMeta(tw, h - tf1 - tf2)
J+=tw * (h - tf1 - tf2)^3 * β
I₃=tw*hw^3/12
I₃+=b1*tf1^3/12+b1*tf1*(hw/2+tf1/2)^2
I₃+=b2*tf2^3/12+b2*tf2*(hw/2+tf2/2)^2
I₃-=A*(y0-h/2)^2
I₂=b1^3*tf1/12+b2^3*tf2/12+tw^3*hw/12
As₂=tw * h
As₃=5.0 / 6 * tf1 * b1 + 5.0 / 6 * tf2 * b2
W₃=I₃/max(y0,h-y0)
W₂=I₂/max(b1/2,b2/2)
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,ISECTION,[h,b1,b2,tw,tf1,tf2])
end
function BoxSection(id,hid,h,b,tw,tf)::BeamSection
id=string(id)
A=h*b-(h-2*tf)*(b-2*tw)
a = 2 * ((b - tw) / tf + (h - tf) / tw)
Ω= 2 * (h - tf) * (b - tw)
c=Ω/a
J=c*Ω
I₃=b*h^3/12-(b-2*tw)*(h-2*tf)^3/12
I₂=h*b^3/12-(h-2*tf)*(b-2*tw)^3/12
As₂=2 * tw * h
As₃=2 * tf * b
W₃=I₃/h*2
W₂=I₂/b*2
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,BOX,[h,b,tw,tf])
end
function PipeSection(id,hid,d,t)::BeamSection
id=string(id)
A=π*d^2/4-π*(d-2*t)^2/4
J=π*(d-t)/t*2*A
I₃=π*d^4/64*(1-((d-2*t)/d)^4)
I₂=I₃
As₂=π * t * (d - t) / 2
As₃=π * t * (d - t) / 2
W₃=I₃/d*2
W₂=W₃
r=d/2
J=π/32*(d^4-(d-2t)^4)
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,PIPE,[d,t])
end
function CircleSection(id,hid,d)::BeamSection
id=string(id)
A=π*d^2/4
J=π*d^4/32
I₃=π*d^4/64
I₂=I₃
As₂=π * d * d / 4 * 0.9
As₃=π * d * d / 4 * 0.9
W₃=I₃/d*2
W₂=W₃
J=π*d^4/32
BeamSection(id,hid,A,I₂,I₃,J,As₂,As₃,W₂,W₃,CIRCLE,[d])
end
function MembraneMeta(h, b)
s = 0
for i in 1:30
m = 1.0 + 2 * i
s += tanh(m * π * h / 2 / b) / m^5
end
β = 1.0 / 3 - b / (π^5 * h) * s
return β
end
end
| MoziFESection | https://github.com/zhuoju36/MoziFESection.jl.git |
|
[
"MIT"
] | 0.1.2 | 93eb72f6f145e0d1a48a6e61a794b1035d4f6951 | code | 254 | include("../src/MoziFESection.jl")
using .MoziFESection
sec=BeamSection(1,1,1,1,1,1,1,1,1,1)
sec=ISection(1,1,400,200,200,10,20,20)
sec=HSection(1,1,200,200,10,10)
sec=BoxSection(1,1,200,200,10,10)
sec=PipeSection(1,1,400,20)
sec=CircleSection(1,1,400) | MoziFESection | https://github.com/zhuoju36/MoziFESection.jl.git |
|
[
"MIT"
] | 0.1.2 | 93eb72f6f145e0d1a48a6e61a794b1035d4f6951 | docs | 550 | # MoziFESection.jl
This is a part of Project Mozi
This package provides convenient calculation of section properties of the project.
本包提供常见截面的几何形状属性计算。
## 技术笔记
### 1. 坐标系统定义
![csys](./img/csys.png)
### 2. 有效抗剪面积的近似计算
腹板:
$
A_s=\frac{5}{6}bh
$
圆形截面
$
A_s=0.9\frac{\pi d^2}{4}
$
圆管截面
$
A_s=0.5 \pi t(d-t)
$
### 3. 扭转惯性矩的近似计算
(1)单室闭口截面薄壁截面
$
J=\frac{\Omega^2}{\oint\frac{1}{t}\text{d}s}
$
其中$\Omega$为薄壁中线围合面积的2倍,$\text{d}s$为薄壁路径微分,$t$为壁厚
(2)矩形截面板件
扭转刚度采用薄膜比拟,默认取30阶,即$n=30$:
$
J=\sum_{i=1}^n\frac{1}{(1+2^n)^5}\tanh\frac{\pi (1+2^n)h}{2b}
$ | MoziFESection | https://github.com/zhuoju36/MoziFESection.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 630 | using Emporium
using Documenter
DocMeta.setdocmeta!(Emporium, :DocTestSetup, :(using Emporium); recursive = true)
makedocs(;
modules = [Emporium],
authors = "Abel Soares Siqueira <abel.s.siqueira@gmail.com> and contributors",
repo = "https://github.com/abelsiqueira/Emporium.jl/blob/{commit}{path}#{line}",
sitename = "Emporium.jl",
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
canonical = "https://abelsiqueira.github.io/Emporium.jl",
assets = String[],
),
pages = ["Home" => "index.md"],
)
deploydocs(; repo = "github.com/abelsiqueira/Emporium.jl", devbranch = "main")
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 226 | module Emporium
using Dates
using Formatting
using GitHub
include("create-test-project-from-main-project.jl")
include("folder-activities.jl")
include("git-aux.jl")
include("github.jl")
include("template-compliance.jl")
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 2268 | export create_test_project_from_main_project
using TOML
"""
create_test_project_from_main_project()
Create `test/Project.toml` from the sections [extras] and [targets] in `Project.toml`.
"""
function create_test_project_from_main_project()
# Initial checks
if !isfile("Project.toml")
error("File Project.toml doesn't exist")
end
if isfile("test/Project.toml")
error("File test/Project.toml already exists")
end
# Early return if there's nothing we can do. No error!
project = TOML.parsefile("Project.toml")
if ["targets", "extras"] ∩ keys(project) == [] || !("test" in keys(project["targets"]))
@info(
"Nothing to do, create test/Project.toml manually: just `pkg> activate test` and `add` things."
)
return
end
# Actual code
compat, deps, extras, targets = getindex.(Ref(project), ["compat", "deps", "extras", "targets"])
test_deps = Dict()
test_compat = Dict()
# We only unpack the "test" target
for pkg in targets["test"]
# Project.toml could be ill-written, so some checks are made
if pkg in keys(extras) # extras can be moved
test_deps[pkg] = extras[pkg]
delete!(extras, pkg)
elseif pkg in keys(deps) # deps are copied
test_deps[pkg] = deps[pkg]
else # shouldn't happen
error("Unknown package $pkg in target list")
end
if pkg in keys(compat) # copy compats too!
test_compat[pkg] = compat[pkg]
if !(pkg in keys(deps))
delete!(compat, pkg)
end
end
end
delete!(targets, "test")
for k in ["compat", "deps", "extras", "targets"]
if length(project[k]) == 0
delete!(project, k)
end
end
test_project = Dict("deps" => test_deps)
if length(test_compat) > 0
test_project["compat"] = test_compat
end
# Copied from Pkg.jl
_project_key_order = ["name", "uuid", "keywords", "license", "desc", "deps", "compat"]
project_key_order(key::String) =
something(findfirst(x -> x == key, _project_key_order), length(_project_key_order) + 1)
by = key -> (project_key_order(key), key)
mkpath("test")
open("test/Project.toml", "w") do io
TOML.print(io, test_project, sorted = true, by = by)
end
open("Project.toml", "w") do io
TOML.print(io, project, sorted = true, by = by)
end
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 2276 | export run_on_folders
"""
run_on_folders(action, folders)
run_on_folders(action, folders)
Run `action` into each folder in `folders`.
`action` must be either:
- a `Cmd` (like `ls`, or `git status`).
- a callable with no mandatory arguments with some keyword arguments, but that accepts arbitrary commands.
The following keyword arguments will be passed to `action`:
- `basename`: Folder name stripped of dirs before it.
- `dirname`: Complement of `basename`.
- `index`: Index of traversal in `folders`, obtained from `enumerate(folder_list)`.
If you think of something useful to add to this list, let me know.
## Options
- `dry_run = false`: Don't run the action, just print.
- `rethrow_exception = false`: If an exception is thrown by the action, rethrow it.
## Examples
### Updating a file throught your cloned repos
You want to have the same configuration in all your repos, that are cloned into folder "cloned-repos".
```julia-repl
julia> myfile = joinpath(pwd(), ".editorconfig")
julia> folders = readdir("cloned-repos", join=true)
julia> run_on_folders(`cp \$myfile .`, folders)
julia> run_on_folders((;kws...) ->
if git_has_to_commit() && run(`git commit -am "Add or update"`), folders)
julia> run_on_folders(`git push`, folders)
```
"""
function run_on_folders(action, folders; dry_run = false, rethrow_exception = false)
for (index, folder) in enumerate(folders)
cd(folder) do
if dry_run
println("Would run action inside $folder")
else
try
action(basename = basename(folder), dirname = dirname(folder), index = index)
catch ex
println("Running action on $folder threw $ex")
if rethrow_exception
rethrow(ex)
end
end
end
end
end
end
function run_on_folders(action, folder::String, args...; kwargs...)
if !isdir(folder)
error("$folder is not a folder nor a list of folders")
end
run_on_folders(action, readdir(folder, join = true))
end
function run_on_folders(action::Cmd, args...; kwargs...)
run_on_folders((; kwargs...) -> run(action), args...; kwargs...)
end
function run_on_folders(action::Cmd, folder::String, args...; kwargs...)
run_on_folders((; kwargs...) -> run(action), folder, args...; kwargs...)
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 670 | # Prepend function names with git_
export git_has_modifications_to_stage
export git_has_staged_to_commit
export git_has_to_commit
"""
git_has_modifications_to_stage()
Check for modified unstaged files.
"""
function git_has_modifications_to_stage()
length(read(`git diff --stat`)) != 0
end
"""
git_has_staged_to_commit()
Check for staged files
"""
function git_has_staged_to_commit()
length(read(`git diff --staged --stat`)) != 0
end
"""
git_has_to_commit()
Check for unstaged or staged modifications to commit.
Doesn't check for untracked files.
"""
function git_has_to_commit()
git_has_modifications_to_stage() || git_has_staged_to_commit()
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 2018 | export clone_organization_repos, create_pull_request
"""
clone_organization_repos(org; options...)
clone_organization_repos(org, dest; options...)
Clone all repos from the GitHub organization `org` into folder `dest`.
If `dest` is not specified, used `dest = org`.
Options:
- `auth = AnonymousAuth()`: Authentication token (`GitHub.authenticate(ENV["GITHUB_AUTH"])`)
- `dry_run = false`: Don't clone the repos, only list them.
- `exclude = []`: Exclude listed repos.
"""
function clone_organization_repos(
org,
dest = org;
auth = GitHub.AnonymousAuth(),
dry_run = false,
exclude = [],
)
isdir(dest) || mkdir(dest)
cloned = String[]
cd(dest) do
repos = GitHub.repos(org, true, auth = auth)[1]
for repo in repos
repo.name in exclude && continue
if dry_run
@info "Would clone $(repo.html_url) but dry_run is true"
else
run(`git clone $(repo.html_url)`)
push!(cloned, repo.name)
end
end
end
return cloned
end
"""
pr = create_pull_request(repo, title, body, head; options...)
Very thin layer over GitHub.create_pull_request.
Creates a pull request to `repo` from branch `head` to base `base` (defaults to `main`).
The `title` and `body` must be supplied.
## Options
- `auth = GitHub.AnonymousAuth()`: GitHub authentication token
- `base = "main"`: Main branch where you want to merge the changes
- `dry_run = false`: Test instead of actually running
"""
function create_pull_request(
repo,
title,
body,
head;
auth = GitHub.AnonymousAuth(),
base = "main",
dry_run = false,
)
params = Dict(
:title => title,
:body => body,
:head => head,
:base => base,
:maintainer_can_modify => true,
:draft => false,
)
pr = if dry_run
@info "Would create a pull request with params = $params"
GitHub.PullRequest()
else
pr = GitHub.create_pull_request(GitHub.repo(repo), auth = auth, params = params)
@info "Pull request created at $(pr.html_url)"
pr
end
return pr
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 6815 | export check_and_fix_compliance
"""
check_and_fix_compliance(template_folder, file_list, workdir = "cloned_repos"; options...)
Compares the list of files given in `file_list` for every package in `workdir` with the same files in `template_folder`.
If some cases, the template files have a package name placeholder that needs to be replaced by the actual package name. Set this with the keyword variable `template_pkg_name`.
## Keywords arguments
- `auth`: GitHub.jl authentication token (use `GitHub.authenticate(YOUR_TOKEN)`).
- `check_only::Bool`: If true, will display only the comparison, without fixing anything (default: `false`).
- `close_older_compliance_prs::Bool`: If `create_pr` is enabled, and this is true, it will look for other PRs with the same branch name prefix and close them (default: `true`).
- `create_pr::Bool`: Whether to create a pull request, or just the commits. Requires a valid `auth` key (default: `false`).
- `filter_jl_ending::Bool`: Whether to check only folders ending in `.jl` or all folders (default: `true`).
- `info_header_frequency::Int`: How often to show the header with the file names (default: `5`).
- `owner::String`: If `create_pr` is true, then this is the owner of the repo, and can't be empty. The full url of the repo is `https://github.com/\$owner/\$pkg`, where `pkg` is the folder name (default: "").
- `rename_these_files::Vector{Pair{String, String}}`: List of files to be renamed, if they exist. This will be done before fixing the content with new files. Each pair is of the form `old => new` (default: []).
- `template_pkg_name::String`: The placeholder for the package name in the files.
# Extended help
## Examples
```julia
julia> clone_organization_repos("MyOrg", "cloned_repos", exclude=["MyTemplate.jl"]) # Clone from my org into repos
julia> run(`git clone https://github.com/MyOrg/MyTemplate.jl`)
julia> auth = GitHub.authenticate(ENV["GITHUB_TOKEN"])
julia> check_and_fix_compliance(
"MyTemplate.jl",
[".JuliaFormatter.jl", ".github/workflows/CI.yml"],
"cloned_repos",
auth = auth,
check_only = false,
close_older_compliance_prs = true,
create_pr = true,
owner = "MyOrg",
rename_these_files = [".github/workflows/ci.yml" => ".github/workflows/CI.yml"],
template_pkg_name = "MyTemplate",
)
```
"""
function check_and_fix_compliance(
template_folder,
file_list,
workdir = "cloned_repos";
auth = GitHub.AnonymousAuth(),
check_only = false,
close_older_compliance_prs = true,
commit_message = ":bot: Template compliance update",
create_pr = false,
filter_jl_ending = true,
info_header_frequency::Int = 5,
owner = "",
pr_title = "[Emporium.jl] Template compliance update",
pr_body = "Created with Emporium.jl function `check_and_fix_compliance`",
rename_these_files = [],
template_pkg_name = "",
)
if create_pr && owner == ""
error("You must define the `owner` keyword argument to create the Pull Requests")
end
pkg_list = readdir(workdir)
if filter_jl_ending
pkg_list = filter(x -> x[(end - 2):end] == ".jl", pkg_list)
end
column_fmts = [
"%-$(maximum(length.(pkg_list)))s";
["%$(len)s" for len in length.(basename.(file_list))]...
]
table_line(V) = join(sprintf1.(column_fmts, V), " ")
@info "Checking simple files"
for (ipkg, pkg) in enumerate(pkg_list)
if ipkg % info_header_frequency == 1
@info table_line(["Package"; basename.(file_list)])
end
# Renaming file
if !check_only
cd(joinpath(workdir, pkg)) do
for (old_file, new_file) in rename_these_files
if isfile(old_file)
run(`git mv $old_file $new_file`)
end
end
end
end
success = fill(false, length(file_list))
for (ifile, file) in enumerate(file_list)
# Compare content
pkg_file_path = joinpath(workdir, pkg, file)
old_file_str = isfile(pkg_file_path) ? read(pkg_file_path, String) : ""
file_str = read(file, String)
if old_file_str == file_str
success[ifile] = true
end
# Fix the files by copying from template
if !check_only
open(pkg_file_path, "w") do out_stream
file_str = replace(file_str, template_pkg_name => pkg[1:(end - 3)])
print(out_stream, file_str)
end
end
end
success_str = [s ? "✓" : "⨉" for s in success]
@info table_line([pkg; success_str])
end
if check_only
return
end
branch_name = "emporium/compliance-" * Dates.format(now(), "yyyy-mm-dd-HH-MM-SS-sss")
run_on_folders(
(; basename = "", dirname = "", index = "") -> begin
for file in file_list
run(`git add $file`)
end
if git_has_to_commit()
@info "Creating commit in $basename"
run(`git checkout -b $branch_name`)
run(`git commit -m "$commit_message"`)
if create_pr
repo = "$owner/$basename"
@info "Creating pull request to $repo"
run(`git remote set-url origin https://$(auth.token)@github.com/$repo`)
@info "Checking for older compliance PRs"
prs, _ = GitHub.pull_requests(repo, auth = auth)
abort_pr = false
for pr in prs
if startswith(pr.head.ref, "emporium/compliance-") && pr.head.ref != branch_name
remote = if pr.head.user.login != owner
remote = pr.head.user.login
run(`git remote set-url $remote https://github.com/$remote/$basename`)
remore
else
"origin"
end
if length(read(`git diff $remote/$(pr.head.ref)`)) == 0
# No difference to existing PR
@info "PR#$(pr.number) already implements the proposed PR"
abort_pr = true
break
end
end
end
if !abort_pr
run(`git push -u origin $branch_name`)
new_pr = create_pull_request(
repo,
pr_title,
pr_body,
branch_name,
auth = auth,
)
if close_older_compliance_prs
for pr in prs
if startswith(pr.head.ref, "emporium/compliance-") && pr.head.ref != branch_name
@info "Closing PR $(pr.number)"
GitHub.create_comment(
repo,
pr,
"Closing in favor of #$(new_pr.number)",
auth = auth,
)
GitHub.close_pull_request(repo, pr, auth = auth)
end
end
end
end
end
end
end,
[joinpath(workdir, x) for x in pkg_list],
)
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 1197 | @testset "Create test/Project.toml from Project.toml" begin
project_before = joinpath(@__DIR__, "auxiliary-files/Project-with-extras-and-target.toml")
project_after = joinpath(@__DIR__, "auxiliary-files/Project-without-extras-and-target.toml")
project_inside_test = joinpath(@__DIR__, "auxiliary-files/Project-inside-test.toml")
cd(mktempdir()) do
@testset "Test Project.toml exist" begin
@test_throws ErrorException create_test_project_from_main_project()
end
cp(project_before, "Project.toml")
create_test_project_from_main_project()
@testset "Project.toml OK" begin
@test readlines("Project.toml") == readlines(project_after)
end
@testset "test/Project.toml OK" begin
@test isfile("test/Project.toml")
@test readlines("test/Project.toml") == readlines(project_inside_test)
end
@testset "Fail if test/Project.toml exists" begin
@test_throws ErrorException create_test_project_from_main_project()
end
rm("test/Project.toml")
@test_logs (
:info,
"Nothing to do, create test/Project.toml manually: just `pkg> activate test` and `add` things.",
) create_test_project_from_main_project()
end
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 1050 | @testset "Git auxiliary tests" begin
cd(mktempdir()) do
run(`git init`)
run(`git config --local user.name "Emporium"`)
run(`git config --local user.email "shop@emporium.com"`)
open("a.file", "w") do io
println(io, "TMP")
end
open("b.file", "w") do io
println(io, "TMP")
end
run(`git add a.file b.file`)
run(`git commit -m "First commit"`)
@testset "Clean work dir" begin
@test !git_has_to_commit()
end
open("a.file", "w") do io
println(io, "TMP2")
end
@testset "Modification on the work dir" begin
@test git_has_modifications_to_stage()
@test !git_has_staged_to_commit()
end
run(`git add a.file`)
@testset "Staged on the work dir" begin
@test !git_has_modifications_to_stage()
@test git_has_staged_to_commit()
end
open("b.file", "w") do io
println(io, "TMP2")
end
@testset "Staged on the work dir" begin
@test git_has_modifications_to_stage()
@test git_has_staged_to_commit()
end
end
end
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | code | 101 | using Emporium
using Test
include("create-test-project-from-main-project.jl")
include("git-aux.jl")
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | docs | 2026 | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog],
and this project adheres to [Semantic Versioning].
## [unreleased]
...
## [0.2.4] - 2023-07-23
### Changed
- Allow customized commit message, PR title, and PR body for compliance update.
- If an existing compliance update with the same content exists, don't create a new one.
## [0.2.3] - 2023-07-18
### Fixed
- Fixed the printed url when creating a pull request
## [0.2.2] - 2023-01-15
### Fixed
- Fix authentication on `check_and_fix_compliance` push.
## [0.2.1] - 2023-01-15
### Added
- `check_and_fix_compliance` to compare a list of files in a folder of packages against a template package.
### Changed
- `create_pull_request` now returns a `PullRequest` object. If `dry-run = true`, it returns an empty one, otherwise the created PR.
- Add option `rethrow_exception` to `run_on_folder` to allow propagating the exception.
### Fixed
- Added compat bounds
### Security
## [0.2.0] - 2022-03-07
### Added
- Git auxiliary function
- This CHANGELOG.md file
- Organization related functions
- Function to run on folders
## [0.1.0] - 2021-10-22
- initial release
### Added
- Package created using PkgTemplates.jl
- Function to create test/Project.toml from Project.toml
- Citation and Zenodo
<!-- Links -->
[keep a changelog]: https://keepachangelog.com/en/1.0.0/
[semantic versioning]: https://semver.org/spec/v2.0.0.html
<!-- Versions -->
[unreleased]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.2.4...HEAD
[0.2.4]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.2.3..v0.2.4
[0.2.3]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.2.2..v0.2.3
[0.2.2]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.2.1..v0.2.2
[0.2.1]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.2.0..v0.2.1
[0.2.0]: https://github.com/abelsiqueira/Emporium.jl/compare/v0.1.0..v0.2.0
[0.1.0]: https://github.com/abelsiqueira/Emporium.jl/releases/tag/v0.1.0
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | docs | 760 | # Emporium
[![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://abelsiqueira.github.io/Emporium.jl/stable)
[![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://abelsiqueira.github.io/Emporium.jl/dev)
[![Build Status](https://github.com/abelsiqueira/Emporium.jl/workflows/CI/badge.svg)](https://github.com/abelsiqueira/Emporium.jl/actions)
[![Coverage](https://codecov.io/gh/abelsiqueira/Emporium.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/abelsiqueira/Emporium.jl)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5579544.svg)](https://doi.org/10.5281/zenodo.5579544)
Welcome to the Julia _scripts_ Emporium.
You will find here an assorted selection of short snippets in the form of functions for specific tasks.
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MPL-2.0"
] | 0.2.4 | a315aacbef374b3d1ef5dc02b76e2cdafd169098 | docs | 180 | ```@meta
CurrentModule = Emporium
```
# Emporium
Documentation for [Emporium](https://github.com/abelsiqueira/Emporium.jl).
```@index
```
```@autodocs
Modules = [Emporium]
```
| Emporium | https://github.com/abelsiqueira/Emporium.jl.git |
|
[
"MIT"
] | 0.1.2 | eaa54cab9bcacd73a99d3412c0e6cad71bf90f72 | code | 2201 | module RandomBooleanMatrices
using Random
using RandomNumbers.Xorshifts
using SparseArrays
using StatsBase
include("curveball.jl")
@enum matrixrandomizations curveball
"""
randomize_matrix!(m; method = curveball)
Randomize the sparse boolean Matrix `m` while maintaining row and column sums
"""
function randomize_matrix!(m::SparseMatrixCSC{Bool, Int}, rng = Random.GLOBAL_RNG; method::matrixrandomizations = curveball)
if method == curveball
return _curveball!(m, rng)
end
error("undefined method")
end
SparseMatrixCSC{Bool, Int}
struct MatrixGenerator{R<:AbstractRNG, M}
m::M
method::matrixrandomizations
rng::R
end
show(io::IO, m::MatrixGenerator{R, SparseMatrixCSC{Bool, Int}}) where R = println(io, "Boolean MatrixGenerator with size $(size(m.m)) and $(nnz(m.m)) occurrences")
"""
matrixrandomizer(m [,rng]; method = curveball)
Create a matrix generator function that will return a random boolean matrix
every time it is called, maintaining row and column sums. Non-boolean input
matrix are interpreted as boolean, where values != 0 are `true`.
# Examples
```
m = rand(0:4, 5, 6)
rmg = matrixrandomizer(m)
random1 = rand(rmg)
random2 = rand(rmg)
``
"""
matrixrandomizer(m, rng) = error("No matrixrandomizer defined for $(typeof(m))")
matrixrandomizer(m) = error("No matrixrandomizer defined for $(typeof(m))")
matrixrandomizer(m::AbstractMatrix, rng = Xoroshiro128Plus(); method::matrixrandomizations = curveball) =
MatrixGenerator{typeof(rng), SparseMatrixCSC{Bool, Int}}(dropzeros!(sparse(m)), method, rng)
matrixrandomizer(m::SparseMatrixCSC{Bool, Int}, rng = Xoroshiro128Plus(); method::matrixrandomizations = curveball) =
MatrixGenerator{typeof(rng), SparseMatrixCSC{Bool, Int}}(dropzeros(m), method, rng)
Random.rand(r::MatrixGenerator{R, SparseMatrixCSC{Bool, Int}}; method::matrixrandomizations = curveball) where R = copy(randomize_matrix!(r.m, r.rng, method = r.method))
Random.rand!(r::MatrixGenerator{R, SparseMatrixCSC{Bool, Int}}; method::matrixrandomizations = curveball) where R = randomize_matrix!(r.m, r.rng, method = r.method)
export randomize_matrix!, matrixrandomizer, matrixrandomizations
export curveball
end
| RandomBooleanMatrices | https://github.com/EcoJulia/RandomBooleanMatrices.jl.git |
|
[
"MIT"
] | 0.1.2 | eaa54cab9bcacd73a99d3412c0e6cad71bf90f72 | code | 2369 |
function sortmerge!(v1, v2, ret, iend, jend)
retind = 0
i,j = firstindex(v1), firstindex(v2)
@inbounds while i <= iend || j <= jend
if j > jend
ret[retind += 1] = v1[i]
i+=1
continue
elseif i > iend
ret[retind += 1] = v2[j]
j+=1
continue
end
if v1[i] == v2[j]
error("The two vectors are not supposed to have overlapping values")
elseif j > lastindex(v2) || v1[i] < v2[j]
ret[retind += 1] = v1[i]
i+=1
elseif i > lastindex(v1) || v1[i] > v2[j]
ret[retind += 1] = v2[j]
j+=1
end
end
end
function _interdif!(v1, v2, inter, dif)
nshared, ndiff = 0, 0
i,j = firstindex(v1), firstindex(v2)
@inbounds while i <= lastindex(v1) || j <= lastindex(v2)
if j > lastindex(v2)
dif[ndiff += 1] = v1[i]
i+=1
continue
elseif i > lastindex(v1)
dif[ndiff += 1] = v2[j]
j+=1
continue
end
if v1[i] == v2[j]
inter[nshared += 1] = v1[i]
i += 1
j += 1
elseif j > lastindex(v2) || v1[i] < v2[j]
dif[ndiff += 1] = v1[i]
i+=1
elseif i > lastindex(v1) || v1[i] > v2[j]
dif[ndiff += 1] = v2[j]
j+=1
end
end
ndiff, nshared
end
function _curveball!(m::SparseMatrixCSC{Bool, Int}, rng = Random.GLOBAL_RNG)
R, C = size(m)
mcs = min(2maximum(diff(m.colptr)), size(m, 1))
not_shared, shared = Vector{Int}(undef, mcs), Vector{Int}(undef, mcs)
newa, newb = Vector{Int}(undef, mcs), Vector{Int}(undef, mcs)
for rep ∈ 1:5C
A, B = rand(rng, 1:C,2)
# use views directly into the sparse matrix to avoid copying
a, b = view(m.rowval, m.colptr[A]:m.colptr[A+1]-1), view(m.rowval, m.colptr[B]:m.colptr[B+1]-1)
l_a, l_b = length(a), length(b)
# an efficient algorithm since both a and b are sorted
l_dif, l_ab = _interdif!(a, b, shared, not_shared)
if !(l_ab ∈ (l_a, l_b))
L = l_a - l_ab
sample!(rng, view(not_shared, Base.OneTo(l_dif)), view(newa,Base.OneTo(L)), replace = false, ordered = true)
L2,_ = _interdif!(view(newa, 1:L), view(not_shared, Base.OneTo(l_dif)), newa, newb)
sortmerge!(shared, newa, a, l_ab, L)
sortmerge!(shared, newb, b, l_ab, L2)
end
end
return m
end
| RandomBooleanMatrices | https://github.com/EcoJulia/RandomBooleanMatrices.jl.git |
|
[
"MIT"
] | 0.1.2 | eaa54cab9bcacd73a99d3412c0e6cad71bf90f72 | code | 627 | using RandomBooleanMatrices
using SparseArrays
using Random
using Test
Random.seed!(1337)
@testset "curveball" begin
m = sprand(Bool, 8, 6, 0.2)
m_old = copy(m)
rsm = sum(m, dims = 1)
csm = sum(m, dims = 2)
randomize_matrix!(m, method = curveball)
@test rsm == sum(m, dims = 1)
@test csm == sum(m, dims = 2)
@test m_old != m
m2 = rand(0:1, 6, 5)
rsm = sum(m2, dims = 1)
csm = sum(m2, dims = 2)
rmg = matrixrandomizer(m2, method = curveball)
m3 = rand(rmg)
@test rsm == sum(m3, dims = 1)
@test csm == sum(m3, dims = 2)
m4 = rand(rmg)
@test m3 != m4
end
| RandomBooleanMatrices | https://github.com/EcoJulia/RandomBooleanMatrices.jl.git |
|
[
"MIT"
] | 0.1.2 | eaa54cab9bcacd73a99d3412c0e6cad71bf90f72 | docs | 1692 | # RandomBooleanMatrices
[![codecov](https://codecov.io/gh/EcoJulia/RandomBooleanMatrices.jl/graph/badge.svg?token=XdZckrNGI9)](https://app.codecov.io/gh/EcoJulia/RandomBooleanMatrices.jl)
## Work In Progress for a scientific publication
Create random boolean matrices that maintain row and column sums. This is a very
common use case for null models in ecology.
The package offers the newest and most efficient unbiased algorithms for generating
random matrices. Legacy approaches have used different forms of swapping, or some
alternative approaches like the `quasiswap` algorithm in R's vegan package. These
methods are neither efficient, nor are they guaranteed to sample the possible
distribution of boolean vectors with a given row and column sum equally.
Currently, the package only offers an implementation of the `curveball` algorithm
of Strona et al. (2014). There are two forms: a `randomize_matrix!` function
that will randomize a sparse boolean `Matrix` in-place, and a generator form:
```julia
using SparseArrays, RandomBooleanMatrices
# in-place
m = sprand(Bool, 1000, 1000, 0.1)
randomize_matrix!(m)
# using a Matrix generator object
m = sprand(Bool, 1000, 1000, 0.1)
rmg = matrixrandomizer(m)
m1 = rand(rmg) # creates a new random matrix
m2 = rand(rmg)
# You can also avoid copying by
m3 = rand!(rmg)
# but notice that this will not create a new copy of the Matrix, so generating multiple matrices at once with this is impossible
```
## References
Strona, G., Nappo, D., Boccacci, F., Fattorini, S. & San-Miguel-Ayanz, J. (2014)
A fast and unbiased procedure to randomize ecological binary matrices with fixed row and column totals.
Nature Communications, 5, 4114.
| RandomBooleanMatrices | https://github.com/EcoJulia/RandomBooleanMatrices.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 207 | module Nettle
using Nettle_jll, Libdl
include("hash_common.jl")
include("hash.jl")
include("hmac.jl")
include("cipher.jl")
# SnoopCompile acceleration
include("precompile.jl")
_precompile_()
end # module
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 10468 | ## Defines all cipher functionality
## As usual, check out
#http://www.lysator.liu.se/~nisse/nettle/nettle.html#Cipher-functions
import Base: show
export CipherType, get_cipher_types
export gen_key32_iv16, add_padding_PKCS5, trim_padding_PKCS5
export Encryptor, Decryptor, decrypt, decrypt!, encrypt, encrypt!
# This is a mirror of the nettle-meta.h:nettle_cipher struct
struct NettleCipher
name::Ptr{UInt8}
context_size::Cuint
block_size::Cuint
key_size::Cuint
set_encrypt_key::Ptr{Cvoid}
set_decrypt_key::Ptr{Cvoid}
encrypt::Ptr{Cvoid}
decrypt::Ptr{Cvoid}
end
# For much the same reasons as in hash_common.jl, we define a separate, more "Julia friendly" type
struct CipherType
name::String
context_size::Cuint
block_size::Cuint
key_size::Cuint
set_encrypt_key::Ptr{Cvoid}
set_decrypt_key::Ptr{Cvoid}
encrypt::Ptr{Cvoid}
decrypt::Ptr{Cvoid}
end
# These are the user-facing types that are used to actually {en,de}cipher stuff
struct Encryptor
cipher_type::CipherType
state::Vector{UInt8}
end
struct Decryptor
cipher_type::CipherType
state::Vector{UInt8}
end
# The function that maps from a NettleCipher to a CipherType
function CipherType(nc::NettleCipher)
CipherType( uppercase(unsafe_string(nc.name)),
nc.context_size, nc.block_size, nc.key_size,
nc.set_encrypt_key, nc.set_decrypt_key, nc.encrypt, nc.decrypt)
end
# The global dictionary of hash types we know how to construct
const _cipher_types = Dict{String,CipherType}()
# We're going to load in each NettleCipher struct individually, deriving
# HashAlgorithm types off of the names we find, and storing the output
# and context size from the data members in the C structures
function get_cipher_types()
# If we have already gotten the hash types from libnettle, don't query again
if isempty(_cipher_types)
cipher_idx = 1
# nettle_ciphers is an array of pointers ended by a NULL pointer, continue reading hash types until we hit it
while( true )
ncptr = unsafe_load(cglobal(("_nettle_ciphers",libnettle),Ptr{Ptr{Cvoid}}),cipher_idx)
if ncptr == C_NULL
break
end
cipher_idx += 1
nc = unsafe_load(convert(Ptr{NettleCipher}, ncptr))
cipher_type = CipherType(nc)
_cipher_types[cipher_type.name] = cipher_type
end
end
return _cipher_types
end
const _cipher_suites = [:CBC] # [:CBC, :GCM, :CCM]
function gen_key32_iv16(pw::Vector{UInt8}, salt::Vector{UInt8})
s1 = digest("MD5", [pw; salt])
s2 = digest("MD5", [s1; pw; salt])
s3 = digest("MD5", [s2; pw; salt])
return ([s1; s2], s3)
end
function add_padding_PKCS5(data::Vector{UInt8}, block_size::Int)
padlen = block_size - (sizeof(data) % block_size)
return [data; map(i -> UInt8(padlen), 1:padlen)]
end
function trim_padding_PKCS5(data::Vector{UInt8})
padlen = data[end]
if all(data[end-padlen+1:end-1] .== data[end])
return data[1:end-padlen]
else
throw(ArgumentError("Invalid PKCS5 padding"))
end
end
function Encryptor(name::String, key)
cipher_types = get_cipher_types()
name = uppercase(name)
if !haskey(cipher_types, name)
throw(ArgumentError("Invalid cipher type $name: call Nettle.get_cipher_types() to see available list"))
end
cipher_type = cipher_types[name]
if sizeof(key) != cipher_type.key_size
throw(ArgumentError("Key must be $(cipher_type.key_size) bytes long"))
end
state = Vector{UInt8}(undef, cipher_type.context_size)
ccall( cipher_type.set_encrypt_key, Cvoid, (Ptr{Cvoid}, Ptr{UInt8}), state, pointer(key))
return Encryptor(cipher_type, state)
end
function Decryptor(name::String, key)
cipher_types = get_cipher_types()
name = uppercase(name)
if !haskey(cipher_types, name)
throw(ArgumentError("Invalid cipher type $name: call Nettle.get_cipher_types() to see available list"))
end
cipher_type = cipher_types[name]
if sizeof(key) != cipher_type.key_size
throw(ArgumentError("Key must be $(cipher_type.key_size) bytes long"))
end
state = Vector{UInt8}(undef, cipher_type.context_size)
ccall( cipher_type.set_decrypt_key, Cvoid, (Ptr{Cvoid}, Ptr{UInt8}), state, pointer(key))
return Decryptor(cipher_type, state)
end
function decrypt!(state::Decryptor, e::Symbol, iv::Vector{UInt8}, result, data)
if sizeof(result) < sizeof(data)
throw(ArgumentError("Output array of length $(sizeof(result)) insufficient for input data length ($(sizeof(data)))"))
end
if sizeof(result) % state.cipher_type.block_size > 0
throw(ArgumentError("Output array of length $(sizeof(result)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(data) % state.cipher_type.block_size > 0
throw(ArgumentError("Input array of length $(sizeof(data)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(iv) != state.cipher_type.block_size
throw(ArgumentError("Iv must be $(state.cipher_type.block_size) bytes long"))
end
if ! (Symbol(uppercase(string(e))) in _cipher_suites)
throw(ArgumentError("now supports $(_cipher_suites) only but ':$(e)'"))
end
hdl = Libdl.dlopen_e(libnettle)
s = Symbol("nettle_", lowercase(string(e)), "_decrypt")
c = Libdl.dlsym(hdl, s)
if c == C_NULL
throw(ArgumentError("not found function '$(s)' for ':$(e)'"))
end
# c points (:nettle_***_decrypt, nettle) may be loaded as another instance
iiv = copy(iv)
ccall(c, Cvoid, (
Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{UInt8},
Csize_t, Ptr{UInt8}, Ptr{UInt8}),
state.state, state.cipher_type.decrypt, sizeof(iiv), iiv,
sizeof(data), pointer(result), pointer(data))
Libdl.dlclose(hdl)
return result
end
function decrypt!(state::Decryptor, result, data)
if sizeof(result) < sizeof(data)
throw(ArgumentError("Output array of length $(sizeof(result)) insufficient for input data length ($(sizeof(data)))"))
end
if sizeof(result) % state.cipher_type.block_size > 0
throw(ArgumentError("Output array of length $(sizeof(result)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(data) % state.cipher_type.block_size > 0
throw(ArgumentError("Input array of length $(sizeof(data)) must be N times $(state.cipher_type.block_size) bytes long"))
end
ccall(state.cipher_type.decrypt, Cvoid, (Ptr{Cvoid},Csize_t,Ptr{UInt8},Ptr{UInt8}),
state.state, sizeof(data), pointer(result), pointer(data))
return result
end
function decrypt(state::Decryptor, e::Symbol, iv::Vector{UInt8}, data)
result = Vector{UInt8}(undef, sizeof(data))
decrypt!(state, e, iv, result, data)
return result
end
function decrypt(state::Decryptor, data)
result = Vector{UInt8}(undef, sizeof(data))
decrypt!(state, result, data)
return result
end
function encrypt!(state::Encryptor, e::Symbol, iv::Vector{UInt8}, result, data)
if sizeof(result) < sizeof(data)
throw(ArgumentError("Output array of length $(sizeof(result)) insufficient for input data length ($(sizeof(data)))"))
end
if sizeof(result) % state.cipher_type.block_size > 0
throw(ArgumentError("Output array of length $(sizeof(result)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(data) % state.cipher_type.block_size > 0
throw(ArgumentError("Input array of length $(sizeof(data)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(iv) != state.cipher_type.block_size
throw(ArgumentError("Iv must be $(state.cipher_type.block_size) bytes long"))
end
if ! (Symbol(uppercase(string(e))) in _cipher_suites)
throw(ArgumentError("now supports $(_cipher_suites) only but ':$(e)'"))
end
hdl = Libdl.dlopen_e(libnettle)
s = Symbol("nettle_", lowercase(string(e)), "_encrypt")
c = Libdl.dlsym(hdl, s)
if c == C_NULL
throw(ArgumentError("not found function '$(s)' for ':$(e)'"))
end
# c points (:nettle_***_encrypt, nettle) may be loaded as another instance
iiv = copy(iv)
ccall(c, Cvoid, (
Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{UInt8},
Csize_t, Ptr{UInt8}, Ptr{UInt8}),
state.state, state.cipher_type.encrypt, sizeof(iiv), iiv,
sizeof(data), pointer(result), pointer(data))
Libdl.dlclose(hdl)
return result
end
function encrypt!(state::Encryptor, result, data)
if sizeof(result) < sizeof(data)
throw(ArgumentError("Output array of length $(sizeof(result)) insufficient for input data length ($(sizeof(data)))"))
end
if sizeof(result) % state.cipher_type.block_size > 0
throw(ArgumentError("Output array of length $(sizeof(result)) must be N times $(state.cipher_type.block_size) bytes long"))
end
if sizeof(data) % state.cipher_type.block_size > 0
throw(ArgumentError("Input array of length $(sizeof(data)) must be N times $(state.cipher_type.block_size) bytes long"))
end
ccall(state.cipher_type.encrypt, Cvoid, (Ptr{Cvoid},Csize_t,Ptr{UInt8},Ptr{UInt8}),
state.state, sizeof(data), pointer(result), pointer(data))
return result
end
function encrypt(state::Encryptor, e::Symbol, iv::Vector{UInt8}, data)
result = Vector{UInt8}(undef, sizeof(data))
encrypt!(state, e, iv, result, data)
return result
end
function encrypt(state::Encryptor, data)
result = Vector{UInt8}(undef, sizeof(data))
encrypt!(state, result, data)
return result
end
# The one-shot functions that make this whole thing so easy
decrypt(name::String, key, data) = decrypt(Decryptor(name, key), data)
encrypt(name::String, key, data) = encrypt(Encryptor(name, key), data)
decrypt(name::String, e::Symbol, iv::Vector{UInt8}, key, data) = decrypt(Decryptor(name, key), e, iv, data)
encrypt(name::String, e::Symbol, iv::Vector{UInt8}, key, data) = encrypt(Encryptor(name, key), e, iv, data)
# Custom show overrides make this package have a little more pizzaz!
function show(io::IO, x::CipherType)
write(io, "$(x.name) Cipher\n")
write(io, " Context size: $(x.context_size) bytes\n")
write(io, " Block size: $(x.block_size) bytes\n")
write(io, " Key size: $(x.key_size) bytes")
end
show(io::IO, x::Encryptor) = write(io, "$(x.cipher_type.name) Encryption state")
show(io::IO, x::Decryptor) = write(io, "$(x.cipher_type.name) Decryption state")
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 2188 | ## Defines all hashing functionality
## As usual, check out http://www.lysator.liu.se/~nisse/nettle/nettle.html#Hash-functions
import Base: show
export Hasher, update!, digest, digest!, hexdigest!, hexdigest
struct Hasher
hash_type::HashType
state::Vector{UInt8}
end
# Constructor for Hasher
function Hasher(name::String)
hash_types = get_hash_types()
name = uppercase(name)
if !haskey(hash_types, name)
throw(ArgumentError("Invalid hash type $name: call Nettle.get_hash_types() to see available list"))
end
# Construct Hasher object for this type and initialize using Nettle's init functions
hash_type = hash_types[name]
state = Vector{UInt8}(undef, hash_type.context_size)
ccall(hash_type.init, Cvoid, (Ptr{Cvoid},), state)
return Hasher(hash_type, state)
end
# Update hash state with new data
function update!(state::Hasher, data)
ccall(state.hash_type.update, Cvoid, (Ptr{Cvoid},Csize_t,Ptr{UInt8}), state.state, sizeof(data), pointer(data))
return state
end
# Spit out a digest of the current hash state and reset it
function digest!(state::Hasher)
digest = Vector{UInt8}(undef, state.hash_type.digest_size)
ccall(state.hash_type.digest, Cvoid, (Ptr{Cvoid},UInt32,Ptr{UInt8}), state.state, sizeof(digest), pointer(digest))
return digest
end
# Take a digest, and convert it to a printable hex representation
hexdigest!(state::Hasher) = bytes2hex(digest!(state))
# The one-shot functions that makes this whole thing so easy.
digest(hash_name::String, data) = digest!(update!(Hasher(hash_name), data))
digest(hash_name::String, io::IO) = digest(hash_name, readall(io))
hexdigest(hash_name::String, data) = hexdigest!(update!(Hasher(hash_name), data))
hexdigest(hash_name::String, io::IO) = hexdigest(hash_name, readall(io))
# Custom show overrides make this package have a little more pizzaz!
function show(io::IO, x::HashType)
write(io, "$(x.name) Hash\n")
write(io, " Context size: $(x.context_size) bytes\n")
write(io, " Digest size: $(x.digest_size) bytes\n")
write(io, " Block size: $(x.block_size) bytes")
end
show(io::IO, x::Hasher) = write(io, "$(x.hash_type.name) Hash state")
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 2374 | export get_hash_types
# This is a mirror of the nettle-meta.h:nettle_hash struct
struct NettleHash
name::Ptr{UInt8}
context_size::Cuint
digest_size::Cuint
block_size::Cuint
init::Ptr{Cvoid} # nettle_hash_init_func
update::Ptr{Cvoid} # nettle_hash_update_func
digest::Ptr{Cvoid} # nettle_hash_digest_func
end
# We convert from the above NettleHash to a HashType for two reasons:
# First, we need a way to keep the actual pointer address around
# Secondly, it's nice to convert the name from a pointer to an actual string
# This cuts down on the amount of work we have to do for some operations
# (especially HMAC operations) at the cost of a bit of memory. I'll take it.
struct HashType
name::String
context_size::Cuint
digest_size::Cuint
block_size::Cuint
init::Ptr{Cvoid} # nettle_hash_init_func
update::Ptr{Cvoid} # nettle_hash_update_func
digest::Ptr{Cvoid} # nettle_hash_digest_func
# This pointer member not actually in the original nettle struct
ptr::Ptr{Cvoid}
end
# The function that maps from a NettleHash to a HashType
function HashType(nh::NettleHash, nhptr::Ptr{Cvoid})
HashType( uppercase(unsafe_string(nh.name)),
nh.context_size, nh.digest_size, nh.block_size,
nh.init, nh.update, nh.digest, nhptr)
end
# The global dictionary of hash types we know how to construct
const _hash_types = Dict{String,HashType}()
# We're going to load in each NettleHash struct individually, deriving
# HashAlgorithm types off of the names we find, and storing the output
# and context size from the data members in the C structures
function get_hash_types()
# If we have already gotten the hash types from libnettle, don't query again
if isempty(_hash_types)
hash_idx = 1
# nettle_hashes is an array of pointers ended by a NULL pointer, continue reading hash types until we hit it
while( true )
nhptr = unsafe_load(cglobal(("_nettle_hashes",libnettle),Ptr{Ptr{Cvoid}}),hash_idx)
if nhptr == C_NULL
break
end
hash_idx += 1
nh = unsafe_load(convert(Ptr{NettleHash}, nhptr))
hash_type = HashType(nh, convert(Ptr{Cvoid},nhptr))
_hash_types[hash_type.name] = hash_type
end
end
return _hash_types
end
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 2229 | ## Defines all HMAC functionality
## Pretty much everything in here learned from http://www.lysator.liu.se/~nisse/nettle/nettle.html#Keyed-hash-functions
## Also from reading the header files from libnettle source tree
import Base: show
export HMACState, update!, digest, digest!, hexdigest!, hexdigest
struct HMACState
hash_type::HashType
outer::Vector{UInt8}
inner::Vector{UInt8}
state::Vector{UInt8}
end
# Constructor for HMACState
function HMACState(name::String, key)
hash_types = get_hash_types()
name = uppercase(name)
if !haskey(hash_types, name)
throw(ArgumentError("Invalid hash type $name: call Nettle.get_hash_types() to see available list"))
end
# Construct HMACState object for this type and initialize using Nettle's init functions
hash_type = hash_types[name]
outer = Vector{UInt8}(undef, hash_type.context_size)
inner = Vector{UInt8}(undef, hash_type.context_size)
state = Vector{UInt8}(undef, hash_type.context_size)
ccall((:nettle_hmac_set_key,libnettle), Cvoid, (Ptr{Cvoid},Ptr{Cvoid},Ptr{Cvoid},Ptr{Cvoid},Csize_t,Ptr{UInt8}),
outer, inner, state, hash_type.ptr, sizeof(key), key)
return HMACState(hash_type, outer, inner, state)
end
function update!(state::HMACState, data)
ccall((:nettle_hmac_update,libnettle), Cvoid, (Ptr{Cvoid},Ptr{Cvoid},Csize_t,Ptr{UInt8}), state.state,
state.hash_type.ptr, sizeof(data), data)
return state
end
function digest!(state::HMACState)
digest = Vector{UInt8}(undef, state.hash_type.digest_size)
ccall((:nettle_hmac_digest,libnettle), Cvoid, (Ptr{Cvoid},Ptr{Cvoid},Ptr{Cvoid},Ptr{Cvoid}, Csize_t,
Ptr{UInt8}), state.outer, state.inner, state.state, state.hash_type.ptr, sizeof(digest), digest)
return digest
end
# Take a digest, and convert it to a printable hex representation
hexdigest!(state::HMACState) = bytes2hex(digest!(state))
# The one-shot functions that makes this whole thing so easy
digest(hmac_name::String, key, data) = digest!(update!(HMACState(hmac_name, key), data))
hexdigest(hmac_name::String, key, data) = hexdigest!(update!(HMACState(hmac_name, key), data))
show(io::IO, x::HMACState) = write(io, "$(x.hash_type.name) HMAC state")
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 1554 | # This file autogenerated through https://github.com/timholy/SnoopCompile.jl. Precompile every day!
function _precompile_()
ccall(:jl_generating_output, Cint, ()) == 1 || return nothing
precompile(Nettle.Decryptor, (String, Vector{UInt8},))
precompile(Nettle.HMACState, (String, Vector{UInt8},))
precompile(Nettle.CipherType, (Nettle.NettleCipher,))
precompile(Nettle.HashType, (Nettle.NettleHash, Ptr{Cvoid},))
precompile(Nettle.Encryptor, (String, Vector{UInt8},))
precompile(Nettle.Hasher, (String,))
precompile(Nettle.HMACState, (String, String,))
precompile(Nettle.HashType, (String, UInt32, UInt32, UInt32, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid},))
precompile(Nettle.CipherType, (String, UInt32, UInt32, UInt32, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid}, Ptr{Cvoid},))
precompile(Nettle.encrypt!, (Nettle.Encryptor, Vector{UInt8}, Vector{UInt8},))
precompile(Nettle.decrypt!, (Nettle.Decryptor, Vector{UInt8}, Vector{UInt8},))
precompile(Nettle.digest!, (Nettle.HMACState,))
precompile(Nettle.get_cipher_types, ())
precompile(Nettle.get_hash_types, ())
precompile(Nettle.digest!, (Nettle.Hasher,))
precompile(Nettle.update!, (Nettle.HMACState, Vector{UInt8},))
precompile(Nettle.update!, (Nettle.Hasher, String,))
precompile(Nettle.decrypt, (String, Vector{UInt8}, Vector{UInt8},))
precompile(Nettle.update!, (Nettle.HMACState, String,))
precompile(Nettle.encrypt, (String, Vector{UInt8}, Vector{UInt8},))
precompile(Nettle.hexdigest!, (Nettle.Hasher,))
end
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 8399 | # -*- coding: utf-8 -*-
# AES tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/aes-test.c
# AES 128
for (key,text,encrypted) in [
(
"00010203050607080A0B0C0D0F101112",
"506812A45F08C889B97F5980038B8359",
"D8F532538289EF7D06B506A4FD5BE9C9"
),(
"14151617191A1B1C1E1F202123242526",
"5C6D71CA30DE8B8B00549984D2EC7D4B",
"59AB30F4D4EE6E4FF9907EF65B1FB68C"
),(
"28292A2B2D2E2F30323334353738393A",
"53F3F4C64F8616E4E7C56199F48F21F6",
"BF1ED2FCB2AF3FD41443B56D85025CB1",
),(
"A0A1A2A3A5A6A7A8AAABACADAFB0B1B2",
"F5F4F7F684878689A6A7A0A1D2CDCCCF",
"CE52AF650D088CA559425223F4D32694",
),(
"2b7e151628aed2a6abf7158809cf4f3c",
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
"3ad77bb40d7a3660a89ecaf32466ef97f5d3d58503b9699de785895a96fdbaaf43b1cd7f598ece23881b00e3ed0306887b0c785e27e8ad3f8223207104725dd4",
)
]
@test encrypt("aes128", hex2bytes(key), hex2bytes(text)) == hex2bytes(encrypted)
@test decrypt("aes128", hex2bytes(key), hex2bytes(encrypted)) == hex2bytes(text)
end
# AES192
for (key,text,encrypted) in [
(
"00010203050607080A0B0C0D0F10111214151617191A1B1C",
"2D33EEF2C0430A8A9EBF45E809C40BB6",
"DFF4945E0336DF4C1C56BC700EFF837F",
),(
"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
"bd334f1d6e45f25ff712a214571fa5cc974104846d0ad3ad7734ecb3ecee4eefef7afd2270e2e60adce0ba2face6444e9a4b41ba738d6c72fb16691603c18e0e",
)
]
@test encrypt("aes192", hex2bytes(key), hex2bytes(text)) == hex2bytes(encrypted)
@test decrypt("aes192", hex2bytes(key), hex2bytes(encrypted)) == hex2bytes(text)
end
# AES256
for (key,text,encrypted) in [
(
"00010203050607080A0B0C0D0F10111214151617191A1B1C1E1F202123242526",
"834EADFCCAC7E1B30664B1ABA44815AB",
"1946DABF6A03A2A2C3D0B05080AED6FC",
),(
"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
"f3eed1bdb5d2a03c064b5a7e3db181f8591ccb10d410ed26dc5ba74a31362870b6ed21b99ca6f4f9f153e7b1beafed1d23304b7a39f9f3ff067d8d8f9e24ecc7",
)
]
@test encrypt("aes256", hex2bytes(key), hex2bytes(text)) == hex2bytes(encrypted)
@test decrypt("aes256", hex2bytes(key), hex2bytes(encrypted)) == hex2bytes(text)
end
# Test lower-level API
key = "this key's exactly 32 bytes long"
enc = Encryptor("AES256", key)
plaintext = "this is 16 chars"
ciphertext = encrypt(enc, Vector{UInt8}(plaintext))
dec = Decryptor("AES256", key)
deciphertext = decrypt(dec, ciphertext)
@test Vector{UInt8}(plaintext) == deciphertext # no bytestring
willcauseassertion = "this is 16 (∀).." # case of length(::String) == 16
@test length(willcauseassertion) == 16
@test sizeof(willcauseassertion) == 18
# @test_throws AssertionError Vector{UInt8}(willcauseassertion) == decrypt(dec, encrypt(enc, Vector{UInt8}(willcauseassertion))) # can not catch this c assertion
@test_throws ArgumentError Vector{UInt8}(willcauseassertion) == decrypt(dec, encrypt(enc, Vector{UInt8}(willcauseassertion)))
# @test_throws AssertionError Vector{UInt8}(willcauseassertion) == decrypt(dec, encrypt(enc, Vector{UInt8}(willcauseassertion))) # can not catch this c assertion
@test_throws ArgumentError Vector{UInt8}(willcauseassertion) == decrypt(dec, encrypt(enc, Vector{UInt8}(willcauseassertion)))
willbebroken = "this is 16 (∀)" # case of length(::String) != 16
@test length(willbebroken) == 14
@test sizeof(willbebroken) == 16
@test Vector{UInt8}(willbebroken) == decrypt(dec, encrypt(enc, Vector{UInt8}(willbebroken)))
@test willbebroken == String(decrypt(dec, encrypt(enc, Vector{UInt8}(willbebroken))))
@test Vector{UInt8}(willbebroken) == decrypt(dec, encrypt(enc, Vector{UInt8}(willbebroken)))
@test willbebroken == String(decrypt(dec, encrypt(enc, Vector{UInt8}(willbebroken))))
criticalbytes = hex2bytes("6e6f74555446382855aa552de2888029")
@test length(criticalbytes) == 16
@test sizeof(criticalbytes) == 16
@test criticalbytes == decrypt(dec, encrypt(enc, criticalbytes))
# This one will pass, but may be caught UnicodeError exception when evaluate it by julia ide.
dummy = String(decrypt(dec, encrypt(enc, criticalbytes)))
@test isa(dummy, AbstractString)
if !isdefined(Core, :String) || !isdefined(Core, :AbstractString)
@test !isa(dummy, ASCIIString)
end
@test isa(dummy, String) # gray zone
@test sizeof(dummy) == 16
@test length(Vector{UInt8}(dummy)) == 16
@test length(dummy) != 16
# Test errors
@test_throws ArgumentError Encryptor("this is not a cipher", key)
@test_throws ArgumentError Decryptor("this is not a cipher either", key)
@test_throws ArgumentError Encryptor("AES256", "bad key length")
@test_throws ArgumentError Decryptor("AES256", "bad key length")
enc = Encryptor("AES256", key)
dec = Decryptor("AES256", key)
result = Vector{UInt8}(undef, sizeof(plaintext) - 1)
@test_throws ArgumentError encrypt!(enc, result, plaintext)
@test_throws ArgumentError decrypt!(dec, result, plaintext)
# Test show methods
println("Testing cipher show methods:")
println(get_cipher_types()["AES256"])
println(Encryptor("AES256", key))
println(Decryptor("AES256", key))
println("Testing cipher AES256CBC:")
# AES256CBC
for (pw,salt,iv,key,text,encrypted) in [
(
Vector(b"Secret Passphrase"),
"a3e550e89e70996c",
"7c7ed9434ddb9c2d1e1fcc38b4bf4667",
"e299ff9d8e4831f07e5323913c53e5f0fec3a040a211d6562fa47607244d0051",
"4d657373616765",
"da8aab1b904205a7e49c1ecc7118a8f4",
),(
Vector(b"Secret Passphrase"),
"a3e550e89e70996c",
"7c7ed9434ddb9c2d1e1fcc38b4bf4667",
"e299ff9d8e4831f07e5323913c53e5f0fec3a040a211d6562fa47607244d0051",
"4d657373616765090909090909090909",
"da8aab1b904205a7e49c1ecc7118a8f4804bef7be79216196739de7845da182d",
)
]
(key32, iv16) = (hex2bytes(key), hex2bytes(iv))
@test gen_key32_iv16(pw, hex2bytes(salt)) == (key32, iv16)
@test encrypt("aes256", :CBC, iv16, key32, add_padding_PKCS5(hex2bytes(text), 16)) == hex2bytes(encrypted)
@test trim_padding_PKCS5(decrypt("aes256", :CBC, iv16, key32, hex2bytes(encrypted))) == hex2bytes(text)
end
# Test errors
badkey = "this key's exactly 32(∪∩∀ДЯ)...."
@test length(badkey) == 32
@test sizeof(badkey) == 40
@test_throws ArgumentError Encryptor("AES256", badkey)
@test_throws ArgumentError Decryptor("AES256", badkey)
iv = Vector(b"this is 16 chars")
key = Vector(b"this key's exactly 32 bytes long")
enc = Encryptor("AES256", key)
dec = Decryptor("AES256", key)
shortresult = Vector{UInt8}(undef, sizeof(plaintext) - 1)
@test_throws ArgumentError encrypt!(enc, :CBC, iv, shortresult, plaintext)
@test_throws ArgumentError decrypt!(dec, :CBC, iv, shortresult, plaintext)
result = Vector{UInt8}(undef, sizeof(plaintext))
shorttext = Vector{UInt8}(undef, sizeof(plaintext) - 1)
@test_throws ArgumentError encrypt!(enc, :CBC, iv, result, shorttext)
@test_throws ArgumentError decrypt!(dec, :CBC, iv, result, shorttext)
longresult = Vector{UInt8}(undef, sizeof(plaintext) + 1)
longtext = Vector{UInt8}(undef, sizeof(plaintext) + 1)
@test_throws ArgumentError encrypt!(enc, :CBC, iv, longresult, longtext)
@test_throws ArgumentError decrypt!(dec, :CBC, iv, longresult, longtext)
shortiv = Vector{UInt8}(undef, sizeof(iv) - 1)
@test_throws ArgumentError encrypt!(enc, :CBC, shortiv, result, plaintext)
@test_throws ArgumentError decrypt!(dec, :CBC, shortiv, result, plaintext)
longiv = Vector{UInt8}(undef, sizeof(iv) + 1)
@test_throws ArgumentError encrypt!(enc, :CBC, longiv, result, plaintext)
@test_throws ArgumentError decrypt!(dec, :CBC, longiv, result, plaintext)
# encrypt!(enc, :GCM, iv, result, plaintext)
# decrypt!(dec, :CCM, iv, result, plaintext)
@test_throws ArgumentError encrypt!(enc, :UNKNOWN, iv, result, plaintext)
@test_throws ArgumentError decrypt!(dec, :UNKNOWN, iv, result, plaintext)
@test_throws ArgumentError trim_padding_PKCS5(UInt8[0x01, 0x03, 0x0a, 0x03, 0x03, 0x02, 0x03])
println("Cipher AES256CBC OK.")
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 4329 | # -*- coding: utf-8 -*-
# MD5 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/md5-test.c
for (text, hash) in [
(
"",
"d41d8cd98f00b204e9800998ecf8427e"
),(
"a",
"0cc175b9c0f1b6a831c399e269772661"
),(
"abc",
"900150983cd24fb0d6963f7d28e17f72"
),(
"message digest",
"f96b697d7cb7938d525a2f31aaf161d0"
),(
"abcdefghijklmnopqrstuvwxyz",
"c3fcd3d76192e4007dfb496cca67e13b"
),(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef" *
"ghijklmnopqrstuvwxyz0123456789",
"d174ab98d277d9f5a5611c2c9f419d9f"
),(
"12345678901234567890123456789012" *
"34567890123456789012345678901234" *
"5678901234567890",
"57edf4a22be3c955ac49da2e2107b67a"
),(
"UTF8String(∀)",
"cb2e2ce95d88a414ccd3773c1108f489"
),(
"UTF8String(\xe2\x88\x80)",
"cb2e2ce95d88a414ccd3773c1108f489"
),(
hex2bytes("6e6f74555446382855aa5529"), # "notUTF8(\x55\xaa\x55)".data
"b0672a2efe1f1d2906e236687ae0153c"
)
]
@test digest("md5", text) == hex2bytes(hash)
end
# SHA1 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/sha1-test.c
for (text, hash) in [
(
"",
"da39a3ee5e6b4b0d3255bfef95601890afd80709",
),(
"a",
"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8",
),(
"abc",
"a9993e364706816aba3e25717850c26c9cd0d89d",
),(
"abcdefghijklmnopqrstuvwxyz",
"32d10c7b8cf96570ca04ce37f2a19d84240d3a89",
),(
"message digest",
"c12252ceda8be8994d5fa0290a47231c1d16aae3",
),(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn" *
"opqrstuvwxyz0123456789",
"761c457bf73b14d27e9e9265c46f4b4dda11f940",
),(
"1234567890123456789012345678901234567890" *
"1234567890123456789012345678901234567890",
"50abf5706a150990a08b2c5ea40fa0e585554732",
),(
"38",
"5b384ce32d8cdef02bc3a139d4cac0a22bb029e8"
)
]
@test hexdigest("sha1", text) == hash
end
# SHA256 hash tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/sha256-test.c
for (text,hash) in [
(
"abc",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
),(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
),(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" *
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"
),(
"",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
),(
"a",
"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
),(
"38",
"aea92132c4cbeb263e6ac2bf6c183b5d81737f179f21efdc5863739672f0f470"
),(
"message digest",
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"
),(
"abcdefghijklmnopqrstuvwxyz",
"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"
),(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0"
),(
"1234567890123456789012345678901234567890123456789012345678901234" *
"5678901234567890",
"f371bc4a311f2b009eef952dd83ca80e2b60026c8e935592d0f9c308453c813e"
)
]
h = Hasher("sha256")
update!(h, text)
@test hexdigest!(h) == hash
end
# Test that digest!() actually resets the HashState
h = Hasher("SHA1")
update!(h,"")
@test hexdigest!(h) == "da39a3ee5e6b4b0d3255bfef95601890afd80709"
update!(h,"The quick brown fox jumps over the lazy dog")
@test hexdigest!(h) == "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
h = Hasher("SHA256")
update!(h,"The quick brown fox jumps over the lazy dog")
@test hexdigest!(h) == "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
# Test invalid parameters
@test_throws ArgumentError Hasher("this is not a hash name")
# Test show methods
println("Testing hash show methods:")
println(get_hash_types()["SHA256"])
println(Hasher("SHA256"))
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 7085 | # MD5 HMAC tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/hmac-test.c
for (key,text,true_digest) in [
(
"",
"",
"74e6f7298a9c2d168935f58c001bad88"
),(
"key",
"The quick brown fox jumps over the lazy dog",
"80070713463e7749b90c2dc24911e275"
),(
hex2bytes(
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
"Hi There",
"9294727a3638bb1c13f48ef8158bfc9d"
),(
"Jefe",
"what do ya want for nothing?",
"750c783e6ab0b503eaa86e310a5db738"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
hex2bytes(
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddd"),
"56be34521d144c88dbb8c733f0e8b3f6"
),(
hex2bytes(
"0102030405060708090a0b0c0d0e0f10" *
"111213141516171819"),
hex2bytes(
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcd"),
"697eaf0aca3a3aea3a75164746ffaa79"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
"Test Using Larger Than Block-Size Key - Hash Key First",
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
"Test Using Larger Than Block-Size Key and Larger " *
"Than One Block-Size Data",
"6f630fad67cda0ee1fb1f562db3aa53e"
)
]
@test digest("md5", key, text) == hex2bytes(true_digest)
end
# SHA1 HMAC tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/hmac-test.c
for (key,text,true_digest) in [
(
"",
"",
"fbdb1d1b18aa6c08324b7d64b71fb76370690e1d"
),(
"key",
"The quick brown fox jumps over the lazy dog",
"de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
),(
hex2bytes(
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
"Hi There",
"b617318655057264e28bc0b6fb378c8ef146be00"
),(
"Jefe",
"what do ya want for nothing?",
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
hex2bytes(
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddd"),
"125d7342b9ac11cd91a39af48aa17b4f63f175d3"
),(
hex2bytes(
"0102030405060708090a0b0c0d0e0f10" *
"111213141516171819"),
hex2bytes(
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcd"),
"4c9007f4026250c6bc8414f9bf50c86c2d7235da"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
"Test Using Larger Than Block-Size Key - Hash Key First",
"aa4ae5e15272d00e95705637ce8a3b55ed402112"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
"Test Using Larger Than Block-Size Key and Larger " *
"Than One Block-Size Data",
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91"
)
]
@test hexdigest("sha1", key, text) == true_digest
end
# SHA256 HMAC tests from:
# https://git.lysator.liu.se/nettle/nettle/blob/master/testsuite/hmac-test.c
for (key,text,true_digest) in [
(
"",
"",
"b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"
),(
"key",
"The quick brown fox jumps over the lazy dog",
"f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
),(
hex2bytes(
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" *
"0b0b0b0b"),
"Hi There",
"b0344c61d8db38535ca8afceaf0bf12b" *
"881dc200c9833da726e9376c2e32cff7"
),(
"Jefe",
"what do ya want for nothing?",
"5bdcc146bf60754e6a042426089575c7" *
"5a003f089d2739839dec58b964ec3843"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaa"),
hex2bytes(
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddddddddddddddddddddddddddddddd" *
"dddd"),
"773ea91e36800e46854db8ebd09181a7" *
"2959098b3ef8c122d9635514ced565fe"
),(
hex2bytes(
"0102030405060708090a0b0c0d0e0f10" *
"111213141516171819"),
hex2bytes(
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" *
"cdcd"),
"82558a389a443c0ea4cc819899f2083a" *
"85f0faa3e578f8077a2e3ff46729665b"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaa"),
"Test Using Larger Than Block-Size Key - Hash Key First",
"60e431591ee0b67f0d8a26aacbf5b77f" *
"8e0bc6213728c5140546040f0ee37f54"
),(
hex2bytes(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" *
"aaaaaa"),
"This is a test using a larger than block-size ke" *
"y and a larger than block-size data. The key nee" *
"ds to be hashed before being used by the HMAC al" *
"gorithm.",
"9b09ffa71b942fcb27635fbcd5b0e944" *
"bfdc63644f0713938a7f51535c3a35e2"
)
]
local h = HMACState("sha256", key)
update!(h, text)
@test hexdigest!(h) == true_digest
end
# Test invalid parameters
@test_throws ArgumentError HMACState("this is not a cipher", "")
# Test show methods
println("Testing HMAC show methods:")
println(HMACState("SHA256", ""))
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | code | 102 | using Nettle
using Test
include("hash_tests.jl")
include("hmac_tests.jl")
include("cipher_tests.jl")
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | docs | 3517 | Nettle.jl
=========
[![Build Status](https://travis-ci.org/staticfloat/Nettle.jl.svg?branch=master)](https://travis-ci.org/staticfloat/Nettle.jl) [![Build status](https://ci.appveyor.com/api/projects/status/auhjpg59nw3a3aij?svg=true)](https://ci.appveyor.com/project/staticfloat/nettle-jl)
`libnettle` supports a wide array of hashing algorithms. This package interrogates `libnettle` to determine the available hash types, which are then available from `Nettle.get_hash_types()`. Typically these include `SHA1`, `SHA224`, `SHA256`, `SHA384`, `SHA512`, `MD2`, `MD5` and `RIPEMD160`.
Typical usage of these hash algorithms is to create a `Hasher`, `update!` it, and finally get a `digest`:
```julia
h = Hasher("sha256")
update!(h, "this is a test")
hexdigest!(h)
#or...
hexdigest("sha256", "this is a test")
```
Outputs:
```
2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c
```
A `digest!` function is also available to return the digest as an `Array(UInt8,1)`. Note that both the `digest!` function and the `hexdigest!` function reset the internal `Hasher` object to a pristine state, ready for further `update!` calls.
HMAC Functionality
==================
[HMAC](http://en.wikipedia.org/wiki/Hash-based_message_authentication_code) functionality revolves around the `HMACState` type, created by the function of the same name. Arguments to this constructor are the desired hash type, and the desired key used to authenticate the hashing:
```julia
h = HMACState("sha256", "mykey")
update!(h, "this is a test")
hexdigest!(h)
#or...
hexdigest("sha256", "mykey", "this is a test")
```
Outputs:
```
"ca1dcafe1b5fb329256248196c0f92a95fbe3788db6c5cb0775b4106db437ba2"
```
A `digest!` function is also available to return the digest as an `Array(UInt8,1)`. Note that both the `digest!` function and the `hexdigest!` function reset the internal `HMACState` object to a pristine state, ready for further `update!` calls.
Encryption/Decryption Functionality
==================================
Nettle also provides encryption and decryption functionality, using the `Encryptor` and `Decryptor` objects. Cipher types are available through `get_cipher_types()`. Create a pair of objects with a shared key, and `encrypt()`/`decrypt()` to your heart's content:
```julia
key = "this key's exactly 32 bytes long"
enc = Encryptor("AES256", key)
plaintext = "this is 16 chars"
ciphertext = encrypt(enc, plaintext)
dec = Decryptor("AES256", key)
deciphertext = decrypt(dec, ciphertext)
Vector{UInt8}(plaintext) == deciphertext # no bytestring
# or...
decrypt("AES256", key, encrypt("AES256", key, plaintext)) == Vector{UInt8}(plaintext)
```
For AES256CBC encrypt/decrypt, generate a pair of key32 and iv16 with salt.
(And add or trim padding yourself.)
```julia
passwd = "Secret Passphrase"
salt = hex2bytes("a3e550e89e70996c") # use random 8 bytes
(key32, iv16) = gen_key32_iv16(Vector{UInt8}(passwd), salt)
enc = Encryptor("AES256", key32)
plaintext = "Message"
ciphertext = encrypt(enc, :CBC, iv16, add_padding_PKCS5(Vector{UInt8}(plaintext), 16))
dec = Decryptor("AES256", key32)
deciphertext = decrypt(dec, :CBC, iv16, ciphertext)
Vector{UInt8}(plaintext) == trim_padding_PKCS5(deciphertext) # no bytestring
# or...
plainbytes = hex2bytes("414155aa5541416162")
cipherbytes = encrypt("AES256", :CBC, iv16, key32, add_padding_PKCS5(plainbytes, 16))
decipherbytes = decrypt("AES256", :CBC, iv16, key32, cipherbytes)
plainbytes == trim_padding_PKCS5(decipherbytes) # no bytestring
```
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | docs | 248 | When opening an issue, please ping `@staticfloat`.
He does not receive emails automatically when new issues are created.
Without this ping, your issue may slip through the cracks!
If no response is garnered within a week, feel free to ping again.
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 1.0.0 | 6fa48cbae828267848ee32c1bb31d1652e210d7d | docs | 248 | When opening an issue, please ping `@staticfloat`.
He does not receive emails automatically when new issues are created.
Without this ping, your issue may slip through the cracks!
If no response is garnered within a week, feel free to ping again.
| Nettle | https://github.com/JuliaCrypto/Nettle.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 1418 | using QuantumESPRESSOBase
using Documenter
DocMeta.setdocmeta!(
QuantumESPRESSOBase,
:DocTestSetup,
:(using QuantumESPRESSOBase, QuantumESPRESSOBase.PWscf, QuantumESPRESSOBase.PHonon);
recursive=true,
)
makedocs(;
modules=[QuantumESPRESSOBase],
authors="singularitti <singularitti@outlook.com> and contributors",
repo="https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/blob/{commit}{path}#{line}",
sitename="QuantumESPRESSOBase.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://MineralsCloud.github.io/QuantumESPRESSOBase.jl",
edit_link="main",
assets=String[],
),
pages=[
"Home" => "index.md",
"Manual" => [
"Installation Guide" => "installation.md",
],
"Public API" => [
"`QuantumESPRESSOBase` module" => "api/QuantumESPRESSOBase.md",
"`PWscf` module" => "api/PWscf.md",
"`PHonon` module" => "api/PHonon.md",
],
"Developer Docs" => [
"Contributing" => "developers/contributing.md",
"Style Guide" => "developers/style-guide.md",
"Design Principles" => "developers/design-principles.md",
],
"Troubleshooting" => "troubleshooting.md",
],
)
deploydocs(;
repo="github.com/MineralsCloud/QuantumESPRESSOBase.jl",
devbranch="main",
)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 491 | module ChemicalFormulaExt
using ChemicalFormula: sumformula
using QuantumESPRESSOBase.PWscf: AtomicPositionsCard, PWInput
import ChemicalFormula: Formula
function Formula(card::AtomicPositionsCard)
atoms = map(card.data) do position
filter(isletter, position.atom)
end
str = join(symbol^count(atom == symbol for atom in atoms) for symbol in unique(atoms))
return Formula(sumformula(Formula(str)))
end
Formula(input::PWInput) = Formula(input.atomic_positions)
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 1020 | module CrystallographyExt
using CrystallographyBase: Lattice, Cell
using QuantumESPRESSOBase.PWscf: PWInput
using Unitful: ustrip, @u_str
using UnitfulAtomic
import Crystallography: findsymmetry
function findsymmetry(input::PWInput, symprec=1e-5)
lattice = Lattice(input)
option = input.atomic_positions.option
data = Iterators.map(input.atomic_positions.data) do atomic_position
atom, position = atomic_position.atom, atomic_position.pos
# `position` is a `Vector` in unit of "bohr"
if option == :alat
position *= input.system.celldm[1]
elseif option == :bohr
position
elseif option == :angstrom
ustrip.(u"bohr", position .* u"angstrom")
elseif option == :crystal
lattice(position)
else # option == :crystal_sg
error("unimplemented!") # FIXME
end
position, atom
end
cell = Cell(lattice, first.(data), last.(data))
return findsymmetry(cell, symprec)
end
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 853 | module StructTypesExt
using QuantumESPRESSOBase.PWscf:
ControlNamelist,
SystemNamelist,
ElectronsNamelist,
IonsNamelist,
CellNamelist,
DosNamelist,
BandsNamelist,
PWInput
using QuantumESPRESSOBase.PHonon: PhNamelist, Q2rNamelist, MatdynNamelist, DynmatNamelist
using StructTypes: Struct
import StructTypes: StructType
StructType(::Type{ControlNamelist}) = Struct()
StructType(::Type{SystemNamelist}) = Struct()
StructType(::Type{ElectronsNamelist}) = Struct()
StructType(::Type{IonsNamelist}) = Struct()
StructType(::Type{CellNamelist}) = Struct()
StructType(::Type{DosNamelist}) = Struct()
StructType(::Type{BandsNamelist}) = Struct()
StructType(::Type{PhNamelist}) = Struct()
StructType(::Type{Q2rNamelist}) = Struct()
StructType(::Type{MatdynNamelist}) = Struct()
StructType(::Type{DynmatNamelist}) = Struct()
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 160 | module QuantumESPRESSOBase
include("inputs.jl")
include("crystallography.jl")
include("PWscf/PWscf.jl")
# include("CP/CP.jl")
include("PHonon/PHonon.jl")
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 3938 | using StaticArrays: MVector, SVector
@enum Ibrav begin
PrimitiveCubic = 1
FaceCenteredCubic = 2
BodyCenteredCubic = 3
BodyCenteredCubic2 = -3
PrimitiveHexagonal = 4
RCenteredHexagonal = 5
RCenteredHexagonal2 = -5
PrimitiveTetragonal = 6
BodyCenteredTetragonal = 7
PrimitiveOrthorhombic = 8
BCenteredOrthorhombic = 9
BCenteredOrthorhombic2 = -9
ACenteredOrthorhombic = 91 # New in QE 6.5=91
FaceCenteredOrthorhombic = 10
BodyCenteredOrthorhombic = 11
PrimitiveMonoclinic = 12
PrimitiveMonoclinic2 = -12
CCenteredMonoclinic = 13
BCenteredMonoclinic2 = -13 # New in QE 6.5=-13
PrimitiveTriclinic = 14
end
latticevectors(p, ibrav::Ibrav) = latticevectors(p, Val(Int(ibrav)))
latticevectors(p, ::Val{1}) = p[1] * [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
latticevectors(p, ::Val{2}) = p[1] / 2 * [[-1, 0, 1], [0, 1, 1], [-1, 1, 0]]
latticevectors(p, ::Val{3}) = p[1] / 2 * [[1, 1, 1], [-1, 1, 1], [-1, -1, 1]]
latticevectors(p, ::Val{-3}) = p[1] / 2 * [[-1, 1, 1], [1, -1, 1], [1, 1, -1]]
latticevectors(p, ::Val{4}) = p[1] * [[1, 0, 0], [-1 / 2, √3 / 2, 0], [0, 0, p[3]]]
function latticevectors(p, ::Val{5})
cosγ = p[4]
ty = sqrt((1 - cosγ) / 6)
tz = sqrt((1 + 2cosγ) / 3)
tx = sqrt((1 - cosγ) / 2)
return p[1] * [[tx, -ty, tz], [0, 2ty, tz], [-tx, -ty, tz]]
end
function latticevectors(p, ::Val{-5})
cosγ = p[4]
ty = sqrt((1 - cosγ) / 6)
tz = sqrt((1 + 2cosγ) / 3)
a′ = p[1] / √3
u = tz - 2 * √2 * ty
v = tz + √2 * ty
return a′ * [[u, v, v], [v, u, v], [v, v, u]]
end
latticevectors(p, ::Val{6}) = p[1] * [[1, 0, 0], [0, 1, 0], [0, 0, p[3]]]
function latticevectors(p, ::Val{7})
r = p[3]
return p[1] / 2 * [[1, -1, r], [1, 1, r], [-1, -1, r]]
end
latticevectors(p, ::Val{8}) = p[1] * [[1, 0, 0], [0, p[2], 0], [0, 0, p[3]]]
function latticevectors(p, ::Val{9})
a, b, c = p[1] .* (1, p[2], p[3])
return [[a / 2, b / 2, 0], [-a / 2, b / 2, 0], [0, 0, c]]
end
function latticevectors(p, ::Val{-9})
a, b, c = p[1] .* (1, p[2], p[3])
return [[a / 2, -b / 2, 0], [a / 2, b / 2, 0], [0, 0, c]]
end
function latticevectors(p, ::Val{91})
a, r1, r2 = p[1:3]
return a * [[1, 0, 0], [0, r1 / 2, -r2 / 2], [0, r1 / 2, r2 / 2]]
end # New in QE 6.4
function latticevectors(p, ::Val{10})
a, b, c = p[1], p[1] * p[2], p[1] * p[3]
return [[a, 0, c], [a, b, 0], [0, b, c]] / 2
end
function latticevectors(p, ::Val{11})
a, b, c = p[1] .* (1, p[2], p[3])
return [[a, b, c], [-a, b, c], [-a, -b, c]] / 2
end
function latticevectors(p, ::Val{12})
a, r1, r2, cosγ = p[1:4]
return a * [[1, 0, 0], [r1 * cosγ, r1 * sin(acos(cosγ)), 0], [0, 0, r2]]
end
function latticevectors(p, ::Val{-12})
a, r1, r2, _, cosβ = p[1:5]
return a * [[1, 0, 0], [0, r1, 0], [r2 * cosβ, 0, r2 * sin(acos(cosβ))]]
end
function latticevectors(p, ::Val{13})
a, r1, r2, cosγ = p[1:4]
return a *
[[1 / 2, 0, -r2 / 2], [r1 * cosγ, r1 * sin(acos(cosγ)), 0], [1 / 2, 0, r2 / 2]]
end
function latticevectors(p, ::Val{-13})
a, r1, r2, _, cosβ = p[1:3]
return a *
[[1 / 2, r1 / 2, 0], [-1 / 2, r1 / 2, 0], [r2 * cosβ, 0, r2 * sin(acos(cosβ))]]
end
function latticevectors(p, ::Val{14})
a, r1, r2, cosα, cosβ, cosγ = p[1:6] # Every `p` that is an iterable can be used
sinγ = sin(acos(cosγ))
δ = r2 * sqrt(1 + 2 * cosα * cosβ * cosγ - cosα^2 - cosβ^2 - cosγ^2) / sinγ
return a * [
[1, 0, 0],
[r1 * cosγ, r1 * sinγ, 0],
[r2 * cosβ, r2 * (cosα - cosβ * cosγ) / sinγ, δ],
]
end
"""
SpecialPoint(x, y, z, w)
Represent a special point in the irreducible Brillouin zone with weight `w`.
"""
struct SpecialPoint{T}
coordinates::SVector{3,T}
weight::Float64
end
SpecialPoint(coordinates, weight) =
SpecialPoint(SVector{3,eltype(coordinates)}(coordinates), weight)
SpecialPoint(x, y, z, w) = SpecialPoint((x, y, z), w)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 1972 | using AbInitioSoftwareBase: Input, InputEntry, Namelist, Card, Setter, groupname
using OrderedCollections: OrderedDict
export QuantumESPRESSOInput, hasoption, getoption, optionpool, groupname
"""
dropdefault(nml::Namelist)
Return an [`OrderedDict`](https://juliacollections.github.io/OrderedCollections.jl/latest/ordered_containers.html#OrderedDicts-and-OrderedSets-1) of non-default values of a `Namelist`.
"""
function dropdefault(nml::Namelist)
default = typeof(nml)() # Create a `Namelist` with all default values
# Compare `default` with `nml`, discard the same values
result = Iterators.filter(item -> item.second != getfield(default, item.first), nml)
# for (drivingarg, passivearg) in _coupledargs(typeof(nml))
# rule
# end
if isempty(result)
@info "Every entry in the namelist is the default value!"
end
return OrderedDict{Symbol,Any}(result)
end
"""
getoption(card::Card)
Return a `String` representing the option of a `Card`.
!!! warning
Do not use `card.option` to access the option since it may not exist.
"""
getoption(card::Card) = hasoption(card) ? card.option : nothing
hasoption(::Type{T}) where {T} = hasfield(T, :option)
hasoption(card::Card) = hasproperty(card, :option)
"""
optionpool(card::Card)
optionpool(T::Type{<:Card})
Return the allowed options for a `Card` or a `Card` type.
# Examples
```jldoctest
julia> optionpool(AtomicPositionsCard)
("alat", "bohr", "angstrom", "crystal", "crystal_sg")
julia> optionpool(CellParametersCard)
("alat", "bohr", "angstrom")
julia> optionpool(SpecialPointsCard)
("tpiba", "crystal", "tpiba_b", "crystal_b", "tpiba_c", "crystal_c")
```
"""
function optionpool end
"Represent input files of executables (such as `pw.x` and `cp.x`)."
abstract type QuantumESPRESSOInput <: Input end
struct VerbositySetter <: Setter
v::String
function VerbositySetter(v)
@assert v in ("high", "low")
return new(v)
end
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 9096 | module CP
using LinearAlgebra: det
using Parameters: @with_kw
using Accessors: get, set, @lens, @set
using StaticArrays: SVector, SMatrix, FieldVector
using Unitful
using UnitfulAtomic
using ..QuantumESPRESSOBase:
Namelist,
QuantumESPRESSOInput,
Card,
optionof,
optionpool,
allnamelists,
allcards,
required_namelists,
optional_namelists,
required_cards,
optional_cards
import AbInitioSoftwareBase: asstring, groupname
import Crystallography: Bravais, Lattice
# import Pseudopotentials: pseudoformat
import ..QuantumESPRESSOBase:
optionpool,
allnamelists,
allcards,
optionof,
required_namelists,
optional_namelists,
required_cards,
optional_cards
using ..Formatter: delimiter, newline, indent, floatfmt, intfmt
export ControlNamelist,
SystemNamelist,
ElectronsNamelist,
IonsNamelist,
CellNamelist,
PressAiNamelist,
WannierNamelist,
AtomicSpecies,
AtomicSpeciesCard,
AtomicPosition,
AtomicPositionsCard,
CellParametersCard,
RefCellParametersCard,
AtomicVelocity,
AtomicVelocitiesCard,
AtomicForce,
AtomicForcesCard,
CPInput,
optconvert
include("namelists.jl")
include("cards.jl")
"""
CPInput <: QuantumESPRESSOInput
CPInput(control, system, electrons, ions, cell, press_ai, wannier, atomic_species, atomic_positions, atomic_velocities, cell_parameters, ref_cell_parameters, constraints, occupations, atomic_forces, plot_wannier, autopilot)
Construct a `CPInput` which represents the input of program `cp.x`.
# Arguments
- `control::ControlNamelist=ControlNamelist()`: the `CONTROL` namelist of the input. Optional.
- `system::SystemNamelist=SystemNamelist()`: the `SYSTEM` namelist of the input. Optional.
- `electrons::ElectronsNamelist=ElectronsNamelist()`: the `ELECTRONS` namelist of the input. Optional.
- `ions::IonsNamelist=IonsNamelist()`: the `IONS` namelist of the input. Optional.
- `cell::CellNamelist=CellNamelist()`: the `CELL` namelist of the input. Optional.
- `press_ai::PressAiNamelist=PressAiNamelist()`: the `PRESS_AI` namelist of the input. Optional.
- `wannier::WannierNamelist=WannierNamelist()`: the `WANNIER` namelist of the input. Optional.
- `atomic_species::AtomicSpeciesCard`: the `ATOMIC_SPECIES` card of the input. Must be provided explicitly.
- `atomic_positions::AtomicPositionsCard`: the `ATOMIC_POSITIONS` card of the input. Must be provided explicitly.
- `atomic_velocities::AtomicVelocitiesCard`: the `ATOMIC_VELOCITIES` card of the input. Must be provided explicitly.
- `cell_parameters::Union{Nothing,CellParametersCard}`: the `CELL_PARAMETERS` card of the input. Must be either `nothing` or a `CellParametersCard`.
- `ref_cell_parameters::Union{Nothing,RefCellParametersCard}`: the `REF_CELL_PARAMETERS` card of the input. Must be either `nothing` or a `CellParametersCard`.
"""
@with_kw struct CPInput <: QuantumESPRESSOInput
control::ControlNamelist = ControlNamelist()
system::SystemNamelist = SystemNamelist()
electrons::ElectronsNamelist = ElectronsNamelist()
ions::IonsNamelist = IonsNamelist()
cell::CellNamelist = CellNamelist()
press_ai::PressAiNamelist = PressAiNamelist()
wannier::WannierNamelist = WannierNamelist()
atomic_species::AtomicSpeciesCard
atomic_positions::AtomicPositionsCard
atomic_velocities::AtomicVelocitiesCard
cell_parameters::Union{Nothing,CellParametersCard} = nothing
ref_cell_parameters::Union{Nothing,RefCellParametersCard} = nothing
constraints::Union{Nothing,Float64} = nothing
occupations::Union{Nothing,Float64} = nothing
atomic_forces::Union{Nothing,AtomicForcesCard} = nothing
plot_wannier::Union{Nothing,Float64} = nothing
autopilot::Union{Nothing,Float64} = nothing
@assert(
!(isnothing(cell_parameters) && system.ibrav == 0),
"Cannot specify `ibrav = 0` with an empty `cell_parameters`!"
)
end # struct CPInput
"""
optconvert(new_option::AbstractString, card::AbstractCellParametersCard)
Convert the option of an `AbstractCellParametersCard` from "bohr" to "angstrom", or its reverse.
!!! warning
It does not support conversion between `"alat"` and the others.
"""
function optconvert(new_option::AbstractString, card::AbstractCellParametersCard)
old_option = optionof(card)
if new_option == old_option
return card # No conversion is needed
else
return typeof(card)(
if (old_option => new_option) == ("bohr" => "angstrom")
@. ustrip(u"angstrom", card.data * u"bohr")
elseif (old_option => new_option) == ("angstrom" => "bohr")
@. ustrip(u"bohr", card.data * u"angstrom")
else
error("unknown conversion rule $(old_option => new_option)!")
end,
)
end
end # function optconvert
groupname(::Type{ControlNamelist}) = "CONTROL"
groupname(::Type{SystemNamelist}) = "SYSTEM"
groupname(::Type{ElectronsNamelist}) = "ELECTRONS"
groupname(::Type{IonsNamelist}) = "IONS"
groupname(::Type{CellNamelist}) = "CELL"
groupname(::Type{AtomicSpeciesCard}) = "ATOMIC_SPECIES"
groupname(::Type{AtomicPositionsCard}) = "ATOMIC_POSITIONS"
groupname(::Type{<:CellParametersCard}) = "CELL_PARAMETERS"
"""
Bravais(nml::SystemNamelist)
Return a `Bravais` from a `SystemNamelist`.
"""
Bravais(nml::SystemNamelist) = Bravais(nml.ibrav)
"""
Lattice(nml::SystemNamelist)
Return a `Lattice` from a `SystemNamelist`.
"""
Lattice(nml::SystemNamelist) = Lattice(Bravais(nml), nml.celldm)
"""
cellvolume(nml::SystemNamelist)
Return the volume of the cell based on the information given in a `SystemNamelist`, in atomic unit.
"""
cellvolume(nml::SystemNamelist) = cellvolume(Lattice(nml))
"""
cellvolume(card)
Return the cell volume of a `CellParametersCard` or `RefCellParametersCard`, in atomic unit.
!!! warning
It will throw an error if the option is `"alat"`.
"""
function cellvolume(card::AbstractCellParametersCard)
option = optionof(card)
if option == :bohr
abs(det(card.data))
elseif option == :angstrom
ustrip(u"bohr^3", abs(det(card.data)) * u"angstrom^3")
else # option == :alat
error("information not enough! Parameter `celldm[1]` needed!")
end
end # function cellvolume
function asstring(data::AtomicSpecies)
return join(
(sprintf1("%3s", data.atom), sprintf1(floatfmt(data), data.mass), data.pseudopot),
delimiter(data),
)
end
function asstring(card::AtomicSpeciesCard)
# Using generator expressions in `join` is faster than using `Vector`s.
return "ATOMIC_SPECIES" *
newline(card) *
join((indent(card) * asstring(x) for x in unique(card.data)), newline(card))
end
function asstring(data::AtomicPosition)
f(x) = x ? "" : "0"
return join(
[
sprintf1("%3s", data.atom)
map(x -> sprintf1(floatfmt(data), x), data.pos)
map(f, data.if_pos)
],
delimiter(data),
)
end
function asstring(card::AtomicPositionsCard)
return "ATOMIC_POSITIONS { $(optionof(card)) }" *
newline(card) *
join((indent(card) * asstring(x) for x in card.data), newline(card))
end
function asstring(card::CellParametersCard)
it = (
indent * join((sprintf1(floatfmt(card), x) for x in row), delimiter(card)) for
row in eachrow(card.data)
)
return "CELL_PARAMETERS { $(optionof(card)) }" * newline(card) * join(it, newline)
end
optionof(::AtomicVelocitiesCard) = "a.u"
optionpool(::Type{<:AtomicPositionsCard}) =
("alat", "bohr", "angstrom", "crystal", "crystal_sg")
optionpool(::Type{<:CellParametersCard}) = ("alat", "bohr", "angstrom")
optionpool(::Type{<:AtomicVelocity}) = ("a.u",)
optionpool(::Type{<:RefCellParametersCard}) = ("bohr", "angstrom")
allnamelists(::Type{CPInput}) =
(:control, :system, :electrons, :ions, :cell, :press_ai, :wannier)
allnamelists(x::CPInput) = (getfield(x, f) for f in allnamelists(typeof(x)))
allcards(::Type{CPInput}) = (
:atomic_species,
:atomic_positions,
:atomic_velocities,
:cell_parameters,
:ref_cell_parameters,
:constraints,
:occupations,
:atomic_forces,
:plot_wannier,
:autopilot,
)
allcards(x::CPInput) = (getfield(x, f) for f in allcards(typeof(x)))
required_namelists(::Type{CPInput}) = (:control, :system, :electrons)
required_namelists(x::CPInput) = (getfield(x, f) for f in required_namelists(typeof(x)))
optional_namelists(::Type{CPInput}) = (:ions, :cell, :press_ai, :wannier)
optional_namelists(x::CPInput) = (getfield(x, f) for f in optional_namelists(typeof(x)))
required_cards(::Type{CPInput}) = (:atomic_species, :atomic_positions)
required_cards(x::CPInput) = (getfield(x, f) for f in required_cards(typeof(x)))
optional_cards(::Type{CPInput}) = (
:atomic_velocities,
:cell_parameters,
:ref_cell_parameters,
:constraints,
:occupations,
:atomic_forces,
:plot_wannier,
:autopilot,
)
optional_cards(x::CPInput) = (getfield(x, f) for f in optional_cards(typeof(x)))
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 8107 | """
AtomicSpecies(atom::Union{AbstractChar,String}, mass::Float64, pseudopot::String)
AtomicSpecies(x::AtomicPosition, mass, pseudopot)
Represent each line of the `ATOMIC_SPECIES` card in QE.
The `atom` field accepts at most 3 characters.
# Examples
```julia
julia> using QuantumESPRESSOBase.Cards.PWscf
julia> AtomicSpecies("C1", 12, "C.pbe-n-kjpaw_psl.1.0.0.UPF")
AtomicSpecies("C1", 12.0, "C.pbe-n-kjpaw_psl.1.0.0.UPF")
julia> AtomicSpecies(
AtomicPosition('S', [0.500000000, 0.288675130, 1.974192764]),
32.066,
"S.pz-n-rrkjus_psl.0.1.UPF",
)
AtomicSpecies("S", 32.066, "S.pz-n-rrkjus_psl.0.1.UPF")
```
"""
struct AtomicSpecies
"Label of the atom. Max total length cannot exceed 3 characters."
atom::String
"""
Mass of the atomic species in atomic unit.
Used only when performing molecular dynamics (MD) run
or structural optimization runs using damped MD.
Not actually used in all other cases (but stored
in data files, so phonon calculations will use
these values unless other values are provided).
"""
mass::Float64
"""
File containing pseudopotential for this species.
See also: [`pseudoformat`](@ref)
"""
pseudopot::String
function AtomicSpecies(atom::Union{AbstractChar,AbstractString}, mass, pseudopot)
@assert(length(atom) <= 3, "Max total length of `atom` cannot exceed 3 characters!")
return new(string(atom), mass, pseudopot)
end
end
"""
pseudoformat(data::AtomicSpecies)
Return the pseudopotential format of the `AtomicSpecies`.
"""
# pseudoformat(data::AtomicSpecies) = pseudoformat(data.pseudopot)
"""
AtomicSpeciesCard <: Card
Represent the `ATOMIC_SPECIES` card in QE. It does not have an "option".
"""
struct AtomicSpeciesCard <: Card
data::Vector{AtomicSpecies}
end
AtomicSpeciesCard(cell::Cell) = AtomicSpeciesCard(map(AtomicSpecies ∘ string, cell.numbers))
"""
AtomicPosition(atom::Union{AbstractChar,String}, pos::Vector{Float64}[, if_pos::Vector{Int}])
AtomicPosition(x::AtomicSpecies, pos, if_pos)
Represent each line of the `ATOMIC_POSITIONS` card in QE.
The `atom` field accepts at most 3 characters.
# Examples
```julia
julia> using QuantumESPRESSOBase.Cards.PWscf
julia> AtomicPosition('O', [0, 0, 0])
AtomicPosition("O", [0.0, 0.0, 0.0], Bool[1, 1, 1])
julia> AtomicPosition(
AtomicSpecies('S', 32.066, "S.pz-n-rrkjus_psl.0.1.UPF"),
[0.500000000, 0.288675130, 1.974192764],
)
AtomicPosition("S", [0.5, 0.28867513, 1.974192764], Bool[1, 1, 1])
```
"""
struct AtomicPosition
"Label of the atom as specified in `AtomicSpecies`."
atom::String
"Atomic positions. A three-element vector of floats."
pos::SVector{3,Float64}
"""
Component `i` of the force for this atom is multiplied by `if_pos(i)`,
which must be either `0` or `1`. Used to keep selected atoms and/or
selected components fixed in MD dynamics or structural optimization run.
With `crystal_sg` atomic coordinates the constraints are copied in all equivalent
atoms.
"""
if_pos::SVector{3,Bool}
function AtomicPosition(atom::Union{AbstractChar,AbstractString}, pos, if_pos)
@assert(length(atom) <= 3, "the max length of `atom` cannot exceed 3 characters!")
return new(string(atom), pos, if_pos)
end
end
AtomicPosition(atom, pos) = AtomicPosition(atom, pos, trues(3))
AtomicPosition(x::AtomicSpecies, pos, if_pos) = AtomicPosition(x.atom, pos, if_pos)
# Introudce mutual constructors since they share the same atoms.
AtomicSpecies(x::AtomicPosition, mass, pseudopot) = AtomicSpecies(x.atom, mass, pseudopot)
"""
AtomicPositionsCard <: Card
Represent the `ATOMIC_POSITIONS` card in QE.
# Arguments
- `data::AbstractVector{AtomicPosition}`: A vector containing `AtomicPosition`s.
- `option::String="alat"`: allowed values are: "alat", "bohr", "angstrom", "crystal", and "crystal_sg".
"""
struct AtomicPositionsCard <: Card
data::Vector{AtomicPosition}
option::String
function AtomicPositionsCard(data, option="alat")
@assert option in optionpool(AtomicPositionsCard)
return new(data, option)
end
end
AtomicPositionsCard(cell::Cell, option) = AtomicPositionsCard(
[
AtomicPosition(string(atom), pos) for
(atom, pos) in zip(cell.numbers, cell.positions)
],
option,
)
# Introudce mutual constructors since they share the same atoms.
function validate(x::AtomicSpeciesCard, y::AtomicPositionsCard)
lens = @lens _.data.atom
@assert(
isempty(symdiff(map(Base.Fix2(get, lens) ∘ unique, (x, y)))),
"labels of the atoms are different in `ATOMIC_SPECIES` and `ATOMIC_POSITIONS` card!",
)
end # function validate
validate(y::AtomicPositionsCard, x::AtomicSpeciesCard) = validate(x, y)
"Represent the abstraction of `CELL_PARAMETERS` and `REF_CELL_PARAMETERS` cards in QE."
abstract type AbstractCellParametersCard <: Card end
"""
CellParametersCard{T<:Real} <: AbstractCellParametersCard
CellParametersCard(data::AbstractMatrix, option::String)
Represent the `CELL_PARAMETERS` cards in `PWscf` and `CP` packages.
"""
struct CellParametersCard{T<:Real} <: AbstractCellParametersCard
data::SMatrix{3,3,T}
option::String
function CellParametersCard{T}(data, option="alat") where {T<:Real}
@assert option in optionpool(CellParametersCard)
return new(data, option)
end
end
CellParametersCard(data::AbstractMatrix{T}, option="alat") where {T} =
CellParametersCard{T}(data, option)
CellParametersCard(lattice::Lattice{T}, option) where {T} =
CellParametersCard(convert(Matrix{T}, lattice), option)
CellParametersCard(cell::Cell, option) = CellParametersCard(cell.lattice, option)
struct AtomicForce
atom::String
force::SVector{3,Float64}
function AtomicForce(atom::Union{AbstractChar,AbstractString}, force)
@assert(length(atom) <= 3, "the max length of `atom` cannot exceed 3 characters!")
return new(string(atom), force)
end
end
struct AtomicForcesCard <: Card
data::Vector{AtomicForce}
end
"""
AtomicVelocity(atom::Union{AbstractChar,String}, velocity::Vector{Float64})
AtomicVelocity(x::AtomicPosition, velocity)
Represent each line of the `ATOMIC_VELOCITIES` card in QE's `CP` package.
The `atom` field accepts at most 3 characters.
# Examples
```julia
julia> using QuantumESPRESSOBase.Cards.CP
julia> AtomicVelocity("H", [0.140374e-04, -0.333683e-04, 0.231834e-04])
AtomicVelocity("H", [1.40374e-5, -3.33683e-5, 2.31834e-5])
```
"""
struct AtomicVelocity
atom::String
velocity::SVector{3,Float64}
function AtomicVelocity(atom::Union{AbstractChar,AbstractString}, velocity)
@assert(length(atom) <= 3, "the max length of `atom` cannot exceed 3 characters!")
return new(string(atom), velocity)
end
end
AtomicVelocity(x::AtomicSpecies, velocity) = AtomicVelocity(x.atom, velocity)
AtomicVelocity(x::AtomicPosition, velocity) = AtomicVelocity(x.atom, velocity)
# Introudce mutual constructors since they share the same atoms.
"""
AtomicSpecies(x::AtomicVelocity, mass, pseudopot)
Construct an `AtomicSpecies` from an `AtomicVelocity` instance.
"""
AtomicSpecies(x::AtomicVelocity, mass, pseudopot) = AtomicSpecies(x.atom, mass, pseudopot)
"""
AtomicPosition(x::AtomicVelocity, pos, if_pos)
Construct an `AtomicPosition` from an `AtomicVelocity` instance.
"""
AtomicPosition(x::AtomicVelocity, pos, if_pos) = AtomicPosition(x.atom, pos, if_pos)
"""
AtomicVelocitiesCard <: Card
Represent the `ATOMIC_VELOCITIES` card in QE's `CP` package which does not have an "option".
"""
struct AtomicVelocitiesCard <: Card
data::Vector{AtomicVelocity}
end
struct RefCellParametersCard <: AbstractCellParametersCard
data::SMatrix{3,3,Float64}
option::String
function RefCellParametersCard(data, option="bohr")
@assert option in optionpool(RefCellParametersCard)
return new(data, option)
end
end
RefCellParametersCard(data::AbstractMatrix, option="bohr") =
RefCellParametersCard(data, option)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 10186 | # From https://discourse.julialang.org/t/aliases-for-union-t-nothing-and-union-t-missing/15402/4
const Maybe{T} = Union{T,Nothing}
# The following default values are picked from `<QE source>/Modules/read_namelists.f90`
"""
ControlNamelist <: Namelist
Represent the `CONTROL` namelist of `cp.x`.
"""
@with_kw struct ControlNamelist <: Namelist
calculation::String = "cp"
title::String = "MD Simulation"
verbosity::String = "low"
isave::Int = 100
restart_mode::String = "restart"
nstep::Int = 50
iprint::Int = 10
tstress::Bool = false
tprnfor::Bool = false
dt::Float64 = 1.0
outdir::String = "./"
saverho::Bool = true
prefix::String = "cp"
ndr::Int = 50
ndw::Int = 50
tabps::Bool = false
max_seconds::Float64 = 1e7
etot_conv_thr::Float64 = 1e-4
forc_conv_thr::Float64 = 1e-3
ekin_conv_thr::Float64 = 1e-6
disk_io::String = "default"
memory::String = "default"
pseudo_dir::String = raw"$HOME/espresso/pseudo/"
tefield::Bool = false
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1282-L1369.
@assert(
calculation in
("cp", "scf", "nscf", "relax", "vc-relax", "vc-cp", "cp-wf", "vc-cp-wf")
)
@assert verbosity in ("high", "low", "debug", "medium", "default", "minimal")
@assert isave >= 1
@assert nstep >= 0
@assert iprint >= 1
@assert dt >= 0
@assert ndr >= 50
@assert ndw <= 0 || ndw >= 50
@assert max_seconds >= 0
@assert etot_conv_thr >= 0
@assert forc_conv_thr >= 0
@assert ekin_conv_thr >= 0
@assert memory in ("small", "default", "large")
end # struct ControlNamelist
"""
SystemNamelist <: Namelist
Represent the `SYSTEM` namelist of `cp.x`.
"""
@with_kw struct SystemNamelist <: Namelist
ibrav::Int = -1
celldm::Vector{Maybe{Float64}} = zeros(6) # Must specify
A::Float64 = 0.0
B::Float64 = 0.0
C::Float64 = 0.0
cosAB::Float64 = 0.0
cosAC::Float64 = 0.0
cosBC::Float64 = 0.0
nat::Int = 0
ntyp::Int = 0
nbnd::Int = 0
tot_charge::Float64 = 0.0
tot_magnetization::Float64 = -1.0
ecutwfc::Float64 = 0.0
ecutrho::Float64 = 0.0
nr1::Int = 0
nr2::Int = 0
nr3::Int = 0
nr1s::Int = 0
nr2s::Int = 0
nr3s::Int = 0
nr1b::Int = 0
nr2b::Int = 0
nr3b::Int = 0
occupations::String = "fixed"
degauss::Float64 = 0.0
smearing::String = "gaussian"
nspin::Int = 1
ecfixed::Float64 = 0.0
qcutz::Float64 = 0.0
q2sigma::Float64 = 0.1 # The default value in QE's source code is 0.01
input_dft::String = "none"
exx_fraction::Float64 = 0.25
lda_plus_u::Bool = false
Hubbard_U::Vector{Union{Nothing,Float64}} = []
vdw_corr::String = "none"
london_s6::Float64 = 0.75
london_rcut::Float64 = 200.0
ts_vdw::Bool = false
ts_vdw_econv_thr::Float64 = 1e-6
ts_vdw_isolated::Bool = false
assume_isolated::String = "none"
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1378-L1499.
@assert ibrav in union(-1:1:14, (-3, -5, -9, -12, -13))
@assert(
if ibrav in -1:0
true # Skip the check, cannot use `nothing`
else
celldm[1] != 0 || A != 0 # Cannot use `iszero` to compare now!
end,
"invalid lattice parameters (`celldm` $celldm or `A` $A)!"
)
@assert(
if ibrav == 14
length(celldm) == 6
elseif ibrav in (5, -5, 12, 13)
4 <= length(celldm) <= 6
elseif ibrav in (4, 6, 7, 8, 9, -9, 10, 11)
3 <= length(celldm) <= 6
elseif ibrav == -13 # `-13` is new from QE 6.4
5 <= length(celldm) <= 6
else
1 <= length(celldm) <= 6
end,
"`celldm` must have length between 1 to 6! See `ibrav`'s doc!"
)
@assert nat >= 0
@assert(0 <= ntyp <= 10, "`ntyp` $ntyp is either less than zero or too large!")
@assert nspin in (1, 2, 4)
@assert ecutwfc >= 0
@assert ecutrho >= 0
@assert(iszero(degauss), "`degauss` is not used in CP!")
@assert ecfixed >= 0
@assert qcutz >= 0
@assert q2sigma >= 0
end # struct SystemNamelist
"""
ElectronsNamelist <: Namelist
Represent the `ELECTRONS` namelist of `cp.x`.
"""
@with_kw struct ElectronsNamelist <: Namelist
electron_maxstep::Int = 100
electron_dynamics::String = "none"
conv_thr::Float64 = 1e-6
niter_cg_restart::Int = 20
efield::Float64 = 0.0
epol::Int = 3
emass::Float64 = 400.0
emass_cutoff::Float64 = 2.5
orthogonalization::String = "ortho"
ortho_eps::Float64 = 1e-8
ortho_max::Int = 20
ortho_para::Int = 0
electron_damping::Float64 = 0.1
electron_velocities::String = "default"
electron_temperature::String = "not_controlled"
ekincw::Float64 = 0.001
fnosee::Float64 = 1.0
startingwfc::String = "random"
tcg::Bool = false
maxiter::Int = 100
passop::Float64 = 0.3
n_inner::Int = 2
ninter_cold_restart::Int = 1
lambda_cold::Float64 = 0.03
grease::Float64 = 1.0
ampre::Float64 = 0.0
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1508-L1543.
@assert electron_dynamics in ("none", "sd", "damp", "verlet", "cg") # Different from code
@assert emass > 0
@assert emass_cutoff > 0
@assert orthogonalization in ("ortho", "Gram-Schmidt")
@assert ortho_eps > 0
@assert ortho_max >= 1
@assert electron_velocities in ("zero", "default", "change_step") # New in 6.4
@assert electron_temperature in ("nose", "rescaling", "not_controlled")
@assert ekincw > 0
@assert fnosee > 0
@assert startingwfc in ("atomic", "random")
end # struct ElectronsNamelist
"""
IonsNamelist <: Namelist
Represent the `IONS` namelist of `cp.x`.
Input this namelist only if `calculation` is `"cp"`, `"relax"`, `"vc-relax"`, `"vc-cp"`, `"cp-wf"`, or `"vc-cp-wf"`.
"""
@with_kw struct IonsNamelist <: Namelist
ion_dynamics::String = "none"
ion_positions::String = "default"
ion_velocities::String = "default"
ion_damping::Float64 = 0.2
ion_radius::Vector{Union{Nothing,Float64}} = [0.5] # The default value in QE's source code is just one 0.5
iesr::Int = 1
ion_nstepe::Int = 1
remove_rigid_rot::Bool = false
ion_temperature::String = "not_controlled"
tempw::Float64 = 300.0
fnosep::Float64 = 1.0
tolp::Float64 = 100.0
nhpcl::Int = 1
nhptyp::Int = 0
nhgrp::Vector{Union{Nothing,Int}} = [0]
fnhscl::Vector{Union{Nothing,Float64}} = zeros(1)
ndega::Int = 0
tranp::Vector{Union{Nothing,Bool}} = falses(1)
amprp::Vector{Union{Nothing,Float64}} = zeros(1)
greasp::Float64 = 1.0
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1552-L1585.
@assert ion_dynamics in ("none", "sd", "cg", "damp", "verlet")
@assert ion_positions in ("default", "from_input")
@assert ion_velocities in ("default", "change_step", "random", "from_input", "zero")
@assert ion_nstepe > 0
@assert ion_temperature in ("nose", "rescaling", "not_controlled")
@assert tempw > 0
@assert fnosep > 0
@assert 0 <= nhpcl <= 4
end # struct IonsNamelist
"""
CellNamelist <: Namelist
Represent the `CELL` namelist of `cp.x`.
Input this namelist only if `calculation` is `"vc-relax"`, `"vc-cp"`, or `"vc-cp-wf"`.
"""
@with_kw struct CellNamelist <: Namelist
cell_parameters::String = "default"
cell_dynamics::String = "none"
cell_velocities::String = "default"
cell_damping::Float64 = 0.1
press::Float64 = 0.0
wmass::Float64 = 0.0
cell_factor::Float64 = 1.2
cell_temperature::String = "not_controlled"
temph::Float64 = 0.0
fnoseh::Float64 = 1.0
greash::Float64 = 1.0
cell_dofree::String = "all"
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1596-L1625.
@assert cell_parameters in ("default", "from_input")
@assert cell_dynamics in ("none", "sd", "damp-pr", "pr")
@assert cell_velocities in ("zero", "default")
@assert wmass >= 0
@assert cell_temperature in ("nose", "rescaling", "not_controlled")
@assert(
cell_dofree in (
"all",
"x",
"y",
"z",
"xy",
"xz",
"yz",
"xyz",
"shape",
"2Dxy",
"2Dshape",
"volume",
)
)
end # struct CellNamelist
"""
PressAiNamelist <: Namelist
Represent the `PRESS_AI` namelist of `cp.x`.
Input this namelist only when `tabps` is `true`.
"""
@with_kw struct PressAiNamelist <: Namelist
abivol::Bool = false
abisur::Bool = false
P_ext::Float64 = 0.0
pvar::Bool = false
P_in::Float64 = 0.0
P_fin::Float64 = 0.0
Surf_t::Float64 = 0.0
rho_thr::Float64 = 0.0
dthr::Float64 = 0.0
end # struct PressAiNamelist
"""
WannierNamelist <: Namelist
Represent the `WANNIER` namelist of `cp.x`.
Input this namelist only if `calculation` is `"cp-wf"` or `"vc-cp-wf"`.
"""
@with_kw struct WannierNamelist <: Namelist
wf_efield::Bool = false
wf_switch::Bool = false
sw_len::Int = 1
efx0::Float64 = 0.0
efy0::Float64 = 0.0
efz0::Float64 = 0.0
efx1::Float64 = 0.0
efy1::Float64 = 0.0
efz1::Float64 = 0.0
wfsd::Int = 1
wfdt::Float64 = 5.0
maxwfdt::Float64 = 0.3
nit::Int = 10
nsd::Int = 10
wf_q::Float64 = 1500.0
wf_friction::Float64 = 0.3
nsteps::Int = 20
tolw::Float64 = 1e-8
adapt::Bool = true
calwf::Int = 3
nwf::Int = 0
wffort::Int = 40
writev::Bool = false
exx_neigh::Int = 60
exx_dis_cutoff::Float64 = 8.0
exx_poisson_eps::Float64 = 1e-6
exx_ps_rcut_self::Float64 = 6.0
exx_ps_rcut_pair::Float64 = 5.0
exx_me_rcut_self::Float64 = 10.0
exx_me_rcut_pair::Float64 = 7.0
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1634-L1650.
@assert 1 <= calwf <= 5
@assert 1 <= wfsd <= 3
end # struct WannierNamelist
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 648 | module PHonon
using Accessors: @reset
using StructEquality: @struct_hash_equal
using ..QuantumESPRESSOBase: SpecialPoint, Card
import ..QuantumESPRESSOBase: VerbositySetter, groupname
export QPointsCard,
PhInput,
Q2rInput,
MatdynInput,
DynmatInput,
PhNamelist,
Q2rNamelist,
MatdynNamelist,
DynmatNamelist,
VerbositySetter
export relayinfo
include("namelists.jl")
@struct_hash_equal struct QPointsCard <: Card
data::Vector{SpecialPoint}
end
function QPointsCard(data::AbstractMatrix)
@assert size(data, 2) == 4
return QPointsCard(map(SpecialPoint, eachrow(data)))
end
include("inputs.jl")
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 2896 | using ..QuantumESPRESSOBase: QuantumESPRESSOInput
using ..PWscf: PWInput
@struct_hash_equal struct PhInput <: QuantumESPRESSOInput
title_line::String
inputph::PhNamelist
q_points::Union{Nothing,QPointsCard}
end
PhInput(inputph::PhNamelist, qpts::QPointsCard) = PhInput(inputph.prefix, inputph, qpts)
PhInput(inputph::PhNamelist) = PhInput(inputph.prefix, inputph, nothing)
PhInput() = PhInput(PhNamelist().prefix, PhNamelist(), nothing)
struct Q2rInput <: QuantumESPRESSOInput
input::Q2rNamelist
end
Q2rInput() = Q2rInput(Q2rNamelist())
@struct_hash_equal struct MatdynInput <: QuantumESPRESSOInput
input::MatdynNamelist
q_points::Union{Nothing,QPointsCard}
end
MatdynInput(input) = MatdynInput(input, nothing)
MatdynInput() = MatdynInput(MatdynNamelist(), nothing)
@struct_hash_equal struct DynmatInput <: QuantumESPRESSOInput
input::DynmatNamelist
end
DynmatInput() = DynmatInput(DynmatNamelist())
function (x::VerbositySetter)(template::PhInput)
@reset template.inputph.verbosity = x.v
return template
end
"""
relayinfo(from::PWInput, to::PhInput)
Relay shared information from a `PWInput` to a `PhInput`.
A `PWInput` before a `PhInput` has the information of `outdir` and `prefix`. They must keep the same in a
phonon calculation.
"""
function relayinfo(pw::PWInput, ph::PhInput)
@reset ph.inputph.outdir = pw.control.outdir
@reset ph.inputph.prefix = pw.control.prefix
return ph
end
"""
relayinfo(from::PhInput, to::Q2rInput)
Relay shared information from a `PhInput` to a `Q2rInput`.
A `PhInput` before a `Q2rInput` has the information of `fildyn`. It must keep the same in a q2r calculation.
"""
function relayinfo(ph::PhInput, q2r::Q2rInput)
@reset q2r.input.fildyn = ph.inputph.fildyn
return q2r
end
"""
relayinfo(from::Q2rInput, to::MatdynInput)
Relay shared information from a `Q2rInput` to a `MatdynInput`.
A `Q2rInput` before a `MatdynInput` has the information of `fildyn`, `flfrc` and `loto_2d`. They must keep the same
in a matdyn calculation.
"""
function relayinfo(q2r::Q2rInput, matdyn::MatdynInput)
@reset matdyn.input.flfrc = q2r.input.flfrc
@reset matdyn.input.loto_2d = q2r.input.loto_2d
return matdyn
end
function relayinfo(ph::PhInput, matdyn::MatdynInput)
@reset matdyn.input.amass = ph.inputph.amass
@reset matdyn.input.q_in_band_form = ph.inputph.q_in_band_form
return matdyn
end
"""
relayinfo(from::PhInput, to::DynmatInput)
Relay shared information from a `PhInput` to a `DynmatInput`.
A `PhInput` before a `DynmatInput` has the information of `asr`, `fildyn` and `amass`. They must keep the same
in a dynmat calculation.
"""
function relayinfo(ph::PhInput, dynmat::DynmatInput)
# @reset dynmat.input.asr = ph.inputph.asr # TODO
@reset dynmat.input.fildyn = ph.inputph.fildyn
@reset dynmat.input.amass = ph.inputph.amass
return dynmat
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 8536 | using AbInitioSoftwareBase: Namelist
using ConstructionBase: setproperties
const DVSCF_STAR = @NamedTuple begin
open::Bool
dir::String
ext::String
basis::String
pat::Bool
end
const DRHO_STAR = @NamedTuple begin
open::Bool
dir::String
ext::String
basis::String
pat::Bool
end
# The following default values are picked from `<QE source>/test-suite/not_epw_comp/phq_readin.f90`
"""
PhNamelist(amass, outdir, prefix, niter_ph, tr2_ph, alpha_mix, nmix_ph, verbosity, reduce_io, max_seconds, fildyn, fildrho, fildvscf, epsil, lrpa, lnoloc, trans, lraman, eth_rps, eth_ns, dek, recover, low_directory_check, only_init, qplot, q2d, q_in_band_form, electron_phonon, lshift_q, zeu, zue, elop, fpol, ldisp, nogg, asr, ldiag, lqdir, search_sym, nq1, nq2, nq3, nk1, nk2, nk3, k1, k2, k3, start_irr, last_irr, nat_todo, modenum, start_q, last_q, dvscf_star, drho_star)
PhNamelist(; kwargs...)
PhNamelist(::PhNamelist; kwargs...)
Represent the `INPUTPH` namelist of `ph.x`.
"""
@struct_hash_equal struct PhNamelist <: Namelist
amass::Vector{Union{Nothing,Float64}}
outdir::String
prefix::String
niter_ph::Int
tr2_ph::Float64
alpha_mix::Vector{Union{Nothing,Float64}}
nmix_ph::Int
verbosity::String
reduce_io::Bool
max_seconds::Float64
fildyn::String
fildrho::String
fildvscf::String
epsil::Bool
lrpa::Bool
lnoloc::Bool
trans::Bool
lraman::Bool
eth_rps::Float64
eth_ns::Float64
dek::Float64
recover::Bool
low_directory_check::Bool
only_init::Bool
qplot::Bool
q2d::Bool
q_in_band_form::Bool
electron_phonon::String
lshift_q::Bool
zeu::Bool # The default value in QE's source code is `true`
zue::Bool
elop::Bool
fpol::Bool
ldisp::Bool
nogg::Bool
asr::Bool
ldiag::Bool
lqdir::Bool
search_sym::Bool
nq1::Int
nq2::Int
nq3::Int
nk1::Int
nk2::Int
nk3::Int
k1::Int
k2::Int
k3::Int
start_irr::Int # The default value in QE's source code is 0
last_irr::Int
nat_todo::Int
modenum::Int
start_q::Int
last_q::Int
dvscf_star::DVSCF_STAR
drho_star::DRHO_STAR
end # struct PhNamelist
function PhNamelist(;
amass=[0.0],
outdir="./",
prefix="pwscf",
niter_ph=100,
tr2_ph=1e-12,
alpha_mix=0.7 * ones(niter_ph),
nmix_ph=4,
verbosity="default",
reduce_io=false,
max_seconds=1e7,
fildyn="matdyn",
fildrho=" ",
fildvscf=" ",
epsil=false,
lrpa=false,
lnoloc=false,
trans=true,
lraman=false,
eth_rps=1e-9,
eth_ns=1e-12,
dek=1e-3,
recover=false,
low_directory_check=false,
only_init=false,
qplot=false,
q2d=false,
q_in_band_form=false,
electron_phonon=" ",
lshift_q=false,
zeu=epsil, # The default value in QE's source code is `true`
zue=false,
elop=false,
fpol=false,
ldisp=false,
nogg=false,
asr=false,
ldiag=false,
lqdir=false,
search_sym=true,
nq1=0,
nq2=0,
nq3=0,
nk1=0,
nk2=0,
nk3=0,
k1=0,
k2=0,
k3=0,
start_irr=1, # The default value in QE's source code is 0
last_irr=-1000,
nat_todo=0,
modenum=0,
start_q=1,
last_q=-1000,
dvscf_star=(open=false, dir="./", ext="dvscf", basis="cartesian", pat=false),
drho_star=(open=false, dir="./", ext="drho", basis="modes", pat=true),
)
return PhNamelist(
amass,
outdir,
prefix,
niter_ph,
tr2_ph,
alpha_mix,
nmix_ph,
verbosity,
reduce_io,
max_seconds,
fildyn,
fildrho,
fildvscf,
epsil,
lrpa,
lnoloc,
trans,
lraman,
eth_rps,
eth_ns,
dek,
recover,
low_directory_check,
only_init,
qplot,
q2d,
q_in_band_form,
electron_phonon,
lshift_q,
zeu,
zue,
elop,
fpol,
ldisp,
nogg,
asr,
ldiag,
lqdir,
search_sym,
nq1,
nq2,
nq3,
nk1,
nk2,
nk3,
k1,
k2,
k3,
start_irr,
last_irr,
nat_todo,
modenum,
start_q,
last_q,
dvscf_star,
drho_star,
)
end
PhNamelist(nml::PhNamelist; kwargs...) = setproperties(nml, kwargs...)
function (x::VerbositySetter)(control::PhNamelist)
@reset control.verbosity = x.v
return control
end
# The following default values are picked from `<QE source>/PHonon/PH/q2r.f90`
"""
Q2rNamelist(fildyn, flfrc, loto_2d, zasr)
Q2rNamelist(; kwargs...)
Q2rNamelist(::Q2rNamelist; kwargs...)
Represent the `INPUT` namelist of `q2r.x`.
"""
@struct_hash_equal struct Q2rNamelist <: Namelist
fildyn::String
flfrc::String
loto_2d::Bool
zasr::String
end # struct Q2rNamelist
function Q2rNamelist(; fildyn=" ", flfrc=" ", loto_2d=false, zasr="no")
return Q2rNamelist(fildyn, flfrc, loto_2d, zasr)
end
Q2rNamelist(nml::Q2rNamelist; kwargs...) = setproperties(nml, kwargs...)
# The following default values are picked from `<QE source>/PHonon/PH/matdyn.f90`
"""
MatdynNamelist(dos, deltaE, ndos, nk1, nk2, nk3, asr, readtau, flfrc, fldos, flfrq, flvec, fleig, fldyn, fltau, amass, at, ntyp, l1, l2, l3, la2F, q_in_band_form, eigen_similarity, q_in_cryst_coord, na_ifc, fd, nosym, loto_2d)
MatdynNamelist(; kwargs...)
MatdynNamelist(::MatdynNamelist; kwargs...)
Represent the `INPUT` namelist of `matdyn.x`.
"""
@struct_hash_equal struct MatdynNamelist <: Namelist
dos::Bool
deltaE::Float64
ndos::Int
nk1::Int
nk2::Int
nk3::Int
asr::String
readtau::Bool
flfrc::String
fldos::String
flfrq::String
flvec::String
fleig::String
fldyn::String
fltau::String
amass::Vector{Union{Nothing,Float64}}
at::Matrix{Union{Nothing,Float64}} # FIXME: not very sure
ntyp::Int
l1::Int
l2::Int
l3::Int
la2F::Bool
q_in_band_form::Bool
eigen_similarity::Bool
q_in_cryst_coord::Bool
na_ifc::Bool
fd::Bool
nosym::Bool
loto_2d::Bool
end # struct MatdynNamelist
function MatdynNamelist(;
dos=false,
deltaE=1.0,
ndos=1,
nk1=0,
nk2=0,
nk3=0,
asr="no",
readtau=false,
flfrc=" ",
fldos="matdyn.dos",
flfrq="matdyn.freq",
flvec="matdyn.modes",
fleig="matdyn.eig",
fldyn=" ",
fltau=" ",
amass=zeros(1),
at=zeros(3, 3), # FIXME: not very sure
ntyp=0,
l1=1,
l2=1,
l3=1,
la2F=false,
q_in_band_form=false,
eigen_similarity=false,
q_in_cryst_coord=false,
na_ifc=false,
fd=false,
nosym=false,
loto_2d=false,
)
return MatdynNamelist(
dos,
deltaE,
ndos,
nk1,
nk2,
nk3,
asr,
readtau,
flfrc,
fldos,
flfrq,
flvec,
fleig,
fldyn,
fltau,
amass,
at,
ntyp,
l1,
l2,
l3,
la2F,
q_in_band_form,
eigen_similarity,
q_in_cryst_coord,
na_ifc,
fd,
nosym,
loto_2d,
)
end
MatdynNamelist(nml::MatdynNamelist; kwargs...) = setproperties(nml, kwargs...)
"""
DynmatNamelist(asr, axis, fildyn, filout, filmol, filxsf, fileig, amass, q, lperm, lplasma)
DynmatNamelist(; kwargs...)
DynmatNamelist(::DynmatNamelist; kwargs...)
Represent the `INPUT` namelist of `dynmat.x`.
"""
@struct_hash_equal struct DynmatNamelist <: Namelist
asr::String
axis::Int
fildyn::String
filout::String
filmol::String
filxsf::String
fileig::String
amass::Vector{Union{Nothing,Float64}}
q::Vector{Union{Nothing,Float64}}
lperm::Bool
lplasma::Bool
end # struct DynmatNamelist
function DynmatNamelist(;
asr="no",
axis=3,
fildyn="matdyn",
filout="dynmat.out",
filmol="dynmat.mold",
filxsf="dynmat.axsf",
fileig=" ",
amass=zeros(1),
q=zeros(3),
lperm=false,
lplasma=false,
)
return DynmatNamelist(
asr, axis, fildyn, filout, filmol, filxsf, fileig, amass, q, lperm, lplasma
)
end
DynmatNamelist(nml::DynmatNamelist; kwargs...) = setproperties(nml, kwargs...)
groupname(::Type{PhNamelist}) = "INPUTPH"
groupname(::Type{Q2rNamelist}) = "INPUT"
groupname(::Type{MatdynNamelist}) = "INPUT"
groupname(::Type{DynmatNamelist}) = "INPUT"
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 603 | module PWscf
using AbInitioSoftwareBase: InputEntry, Namelist, Card, Setter
using Accessors: @reset
using StructEquality: @struct_hash_equal
using Unitful: AbstractQuantity, Length, Temperature, ustrip, @u_str
using UnitfulAtomic
using ..QuantumESPRESSOBase: QuantumESPRESSOInput, VerbositySetter
import AbInitioSoftwareBase: groupname, getpseudodir
import CrystallographyBase: Lattice, cellvolume
# import Pseudopotentials: pseudoformat
export groupname
include("namelists.jl")
include("cards.jl")
include("inputs.jl")
include("crystallography.jl")
include("set.jl")
include("validation.jl")
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 10389 | using AbInitioSoftwareBase: EachPotential
using ConstructionBase: constructorof
using CrystallographyBase: Cell, MonkhorstPackGrid, EachAtom
using StaticArrays: FieldVector, SMatrix, Size
import AbInitioSoftwareBase: eachpotential
import CrystallographyBase: eachatom
import StaticArrays: similar_type
import ..QuantumESPRESSOBase: SpecialPoint, getoption, optionpool
export AtomicSpecies,
AtomicSpeciesCard,
AtomicPosition,
AtomicPositionsCard,
AtomicForce,
AtomicForcesCard,
AtomicVelocity,
AtomicVelocitiesCard,
KPointsCard,
KMeshCard,
GammaPointCard,
SpecialPointsCard,
CellParametersCard
export getoption, convertoption, optionpool, eachpotential
abstract type AtomicData end
"""
AtomicSpecies(atom::Union{Char,String}, mass, pseudopot)
AtomicSpecies(x::AtomicPosition, mass, pseudopot)
Represent each line in the `ATOMIC_SPECIES` card in `pw.x` input files.
The `atom` field accepts no more than 3 characters.
# Examples
```jldoctest
julia> AtomicSpecies("C1", 12, "C.pbe-n-kjpaw_psl.1.0.0.UPF")
AtomicSpecies("C1", 12.0, "C.pbe-n-kjpaw_psl.1.0.0.UPF")
julia> AtomicSpecies(
AtomicPosition('S', [0.500000000, 0.288675130, 1.974192764]),
32.066,
"S.pz-n-rrkjus_psl.0.1.UPF",
)
AtomicSpecies("S", 32.066, "S.pz-n-rrkjus_psl.0.1.UPF")
```
"""
struct AtomicSpecies <: AtomicData
"Label of the atom. Max total length cannot exceed 3 characters."
atom::String
"""
Mass of the atomic species in atomic unit.
Used only when performing molecular dynamics (MD) run
or structural optimization runs using damped MD.
Not actually used in all other cases (but stored
in data files, so phonon calculations will use
these values unless other values are provided).
"""
mass::Float64
"""
File containing pseudopotential for this species.
See also: [`pseudoformat`](@ref)
"""
pseudopot::String
function AtomicSpecies(atom, mass, pseudopot)
@assert length(atom) <= 3 "`atom` accepts no more than 3 characters!"
return new(string(atom), mass, pseudopot)
end
end
"""
pseudoformat(data::AtomicSpecies)
Return the pseudopotential format of the `AtomicSpecies`.
"""
# pseudoformat(data::AtomicSpecies) = pseudoformat(data.pseudopot)
"""
AtomicSpeciesCard <: Card
Represent the `ATOMIC_SPECIES` card in QE. It does not have an "option".
"""
@struct_hash_equal struct AtomicSpeciesCard <: Card
data::Vector{AtomicSpecies}
end
eachpotential(card::AtomicSpeciesCard) = EachPotential(
Tuple(datum.atom for datum in card.data),
Tuple(datum.pseudopot for datum in card.data),
)
struct Position{T} <: FieldVector{3,T}
x::T
y::T
z::T
end
struct IfPosition{T} <: FieldVector{3,T}
x::T
y::T
z::T
end
# See https://juliaarrays.github.io/StaticArrays.jl/dev/pages/api/#StaticArraysCore.FieldVector
similar_type(::Type{<:Position}, ::Type{T}, s::Size{(3,)}) where {T} = Position{T}
similar_type(::Type{<:IfPosition}, ::Type{T}, s::Size{(3,)}) where {T} = IfPosition{T}
"""
AtomicPosition(atom::Union{Char,String}, pos[, if_pos])
AtomicPosition(x::AtomicSpecies, pos, if_pos)
Represent each line in the `ATOMIC_POSITIONS` card in `pw.x` input files.
The `atom` field accepts no more than 3 characters.
# Examples
```jldoctest
julia> AtomicPosition('O', [0, 0, 0])
AtomicPosition("O", [0.0, 0.0, 0.0], Bool[1, 1, 1])
julia> AtomicPosition(
AtomicSpecies('S', 32.066, "S.pz-n-rrkjus_psl.0.1.UPF"),
[0.500000000, 0.288675130, 1.974192764],
)
AtomicPosition("S", [0.5, 0.28867513, 1.974192764], Bool[1, 1, 1])
```
"""
struct AtomicPosition <: AtomicData
"Label of the atom as specified in `AtomicSpecies`."
atom::String
"Atomic positions. A three-element vector of floats."
pos::Position{Float64}
"""
Component `i` of the force for this atom is multiplied by `if_pos(i)`,
which must be either `0` or `1`. Used to keep selected atoms and/or
selected components fixed in MD dynamics or structural optimization run.
With `crystal_sg` atomic coordinates the constraints are copied in all equivalent
atoms.
"""
if_pos::IfPosition{Bool}
function AtomicPosition(atom, pos, if_pos=trues(3))
@assert length(atom) <= 3 "`atom` accepts no more than 3 characters!"
return new(string(atom), pos, if_pos)
end
end
AtomicPosition(x::AtomicSpecies, pos, if_pos) = AtomicPosition(x.atom, pos, if_pos)
# Introudce mutual constructors since they share the same atoms.
AtomicSpecies(x::AtomicPosition, mass, pseudopot) = AtomicSpecies(x.atom, mass, pseudopot)
"""
AtomicPositionsCard <: Card
Represent the `ATOMIC_POSITIONS` card in `pw.x` input files.
# Arguments
- `data::AbstractVector{AtomicPosition}`: A vector containing `AtomicPosition`s.
- `option::Symbol="alat"`: allowed values are: "alat", "bohr", "angstrom", "crystal", and "crystal_sg".
"""
@struct_hash_equal struct AtomicPositionsCard <: Card
data::Vector{AtomicPosition}
option::Symbol
function AtomicPositionsCard(data, option=:alat)
@assert option in optionpool(AtomicPositionsCard)
return new(data, option)
end
end
AtomicPositionsCard(cell::Cell, option=:alat) = AtomicPositionsCard(
map(eachatom(cell)) do (atom, position)
AtomicPosition(string(atom), position)
end,
option,
)
"Represent the abstraction of `CELL_PARAMETERS` and `REF_CELL_PARAMETERS` cards in QE."
abstract type AbstractCellParametersCard <: Card end
"""
CellParametersCard(data::AbstractMatrix, option::Symbol)
Represent the `CELL_PARAMETERS` cards in `PWscf` and `CP` packages.
"""
struct CellParametersCard <: AbstractCellParametersCard
data::SMatrix{3,3,Float64,9}
option::Symbol
function CellParametersCard(data, option=:alat)
@assert option in optionpool(CellParametersCard)
return new(data, option)
end
end
CellParametersCard(lattice::Lattice, option=:alat) =
CellParametersCard(transpose(parent(lattice)), option)
function CellParametersCard(lattice::Lattice{<:Length}, option=:alat)
option = option == :alat ? :bohr : option
return CellParametersCard(Lattice(Base.Fix1(ustrip, u"bohr").(parent(lattice))), :bohr)
end
CellParametersCard(cell::Cell, option=:alat) = CellParametersCard(Lattice(cell), option)
struct Force{T} <: FieldVector{3,T}
x::T
y::T
z::T
end
struct Velocity{T} <: FieldVector{3,T}
x::T
y::T
z::T
end
similar_type(::Type{<:Force}, ::Type{T}, s::Size{(3,)}) where {T} = Force{T}
similar_type(::Type{<:Velocity}, ::Type{T}, s::Size{(3,)}) where {T} = Velocity{T}
struct AtomicForce <: AtomicData
atom::String
force::Force{Float64}
function AtomicForce(atom, force)
@assert length(atom) <= 3 "`atom` accepts no more than 3 characters!"
return new(string(atom), force)
end
end
@struct_hash_equal struct AtomicForcesCard <: Card
data::Vector{AtomicForce}
end
struct AtomicVelocity <: AtomicData
atom::String
velocity::Velocity{Float64}
function AtomicVelocity(atom, velocity)
@assert length(atom) <= 3 "`atom` accepts no more than 3 characters!"
return new(string(atom), velocity)
end
end
@struct_hash_equal struct AtomicVelocitiesCard <: Card
data::Vector{AtomicVelocity}
end
eachatom(card::AtomicPositionsCard) = EachAtom(
Tuple(datum.atom for datum in card.data), Tuple(datum.pos for datum in card.data)
)
"""
convertoption(card::AbstractCellParametersCard, new_option::AbstractString)
Convert the option of an `AbstractCellParametersCard` from "bohr" to "angstrom", etc.
!!! warning
It does not support conversions between `"alat"` and others.
"""
function convertoption(card::AbstractCellParametersCard, new_option::AbstractString)
old_option = getoption(card)
if new_option == old_option
return card # No conversion is needed
else
constructor = constructorof(typeof(card))
if old_option == :bohr && new_option == :angstrom
return constructor(ustrip.(u"angstrom", card.data .* u"bohr"))
elseif old_option == :angstrom && new_option == :bohr
return constructor(ustrip.(u"bohr", card.data .* u"angstrom"))
else
error("unknown conversion rule $(old_option => new_option)!")
end
end
end
"Represent the general `K_POINTS` card in Quantum ESPRESSO."
abstract type KPointsCard <: Card end
"""
KMeshCard(data::MonkhorstPackGrid)
Represent the `K_POINTS` card in Quantum ESPRESSO with Monkhorst–Pack grid.
"""
struct KMeshCard <: KPointsCard
data::MonkhorstPackGrid
end
"""
GammaPointCard()
Represent the `K_POINTS` card in Quantum ESPRESSO with only Γ-point.
"""
struct GammaPointCard <: KPointsCard end
"""
SpecialPointsCard(data, option)
Represent the `K_POINTS` card in Quantum ESPRESSO with a list of k-points.
# Arguments
- `data::Vector{SpecialPoint}`: a vector containing `SpecialPoint`s.
- `option::String="tpiba"`: allowed values are: "tpiba", "automatic", "crystal", "gamma", "tpiba_b", "crystal_b", "tpiba_c" and "crystal_c".
"""
@struct_hash_equal struct SpecialPointsCard <: KPointsCard
data::Vector{SpecialPoint}
option::Symbol
function SpecialPointsCard(data, option=:tpiba)
@assert option in optionpool(SpecialPointsCard)
return new(data, option)
end
end
struct AdditionalKPointsCard <: Card end
struct ConstraintsCard <: Card end
struct OccupationsCard <: Card end
struct SolventsCard <: Card end
struct HubbardCard <: Card end
getoption(::KMeshCard) = :automatic
getoption(::GammaPointCard) = :gamma
optionpool(card::Card) = optionpool(typeof(card))
optionpool(::Type{AtomicPositionsCard}) = (:alat, :bohr, :angstrom, :crystal, :crystal_sg)
optionpool(::Type{CellParametersCard}) = (:alat, :bohr, :angstrom)
optionpool(::Type{KMeshCard}) = (:automatic,)
optionpool(::Type{GammaPointCard}) = (:gamma,)
optionpool(::Type{SpecialPointsCard}) =
(:tpiba, :crystal, :tpiba_b, :crystal_b, :tpiba_c, :crystal_c)
groupname(::Type{AtomicSpeciesCard}) = "ATOMIC_SPECIES"
groupname(::Type{AtomicPositionsCard}) = "ATOMIC_POSITIONS"
groupname(::Type{CellParametersCard}) = "CELL_PARAMETERS"
groupname(::Type{KMeshCard}) = "K_POINTS"
groupname(::Type{GammaPointCard}) = "K_POINTS"
groupname(::Type{SpecialPointsCard}) = "K_POINTS"
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 3679 | using LinearAlgebra: det
using ..QuantumESPRESSOBase: Ibrav, latticevectors
import CrystallographyBase: Cell, crystaldensity
struct InsufficientInfoError <: Exception
msg::AbstractString
end
"""
Lattice(nml::SystemNamelist)
Create a `Lattice` from a `SystemNamelist`.
"""
Lattice(nml::SystemNamelist) = Lattice(latticevectors(nml.celldm, Ibrav(nml.ibrav)))
"""
Lattice(card::CellParametersCard)
Create a `Lattice` from a `CellParametersCard`.
"""
function Lattice(card::CellParametersCard)
data, option = transpose(card.data), getoption(card)
if option == :alat
throw(InsufficientInfoError("parameter `celldm[1]` needed!"))
elseif option == :bohr
return Lattice(data)
else # option == :angstrom
return Lattice(data * ustrip(u"bohr", 1u"angstrom"))
end
end
"""
Lattice(card::PWInput)
Create a `Lattice` from a `PWInput`.
"""
function Lattice(input::PWInput)
if isnothing(input.cell_parameters)
return Lattice(input.system)
else
if getoption(input.cell_parameters) == "alat"
return Lattice(
transpose(input.cell_parameters.data) * first(input.system.celldm)
)
else
return Lattice(input.cell_parameters)
end
end
end
function Cell(cell_parameters::CellParametersCard, atomic_positions::AtomicPositionsCard)
lattice = Lattice(cell_parameters)
positions = [position for (_, position) in eachatom(atomic_positions)]
atoms = [atom for (atom, _) in eachatom(atomic_positions)]
return Cell(lattice, positions, atoms)
end
Cell(atomic_positions::AtomicPositionsCard, cell_parameters::CellParametersCard) =
Cell(cell_parameters, atomic_positions)
Cell(input::PWInput) = Cell(input.cell_parameters, input.atomic_positions)
"""
cellvolume(card)
Return the cell volume of a `CellParametersCard` or `RefCellParametersCard`, in atomic unit.
!!! warning
It will throw an error if the option is `"alat"`.
"""
function cellvolume(card::AbstractCellParametersCard)
option = getoption(card)
if option == :bohr
return abs(det(card.data))
elseif option == :angstrom
return ustrip(u"bohr^3", abs(det(card.data)) * u"angstrom^3")
else # option == :alat
throw(InsufficientInfoError("parameter `celldm[1]` needed!"))
end
end
"""
cellvolume(nml::SystemNamelist)
Return the volume of the cell based on the information given in a `SystemNamelist`, in atomic unit.
"""
cellvolume(nml::SystemNamelist) = cellvolume(Lattice(nml))
"""
cellvolume(input::PWInput)
Return the volume of the cell based on the information given in a `PWInput`, in atomic unit.
"""
function cellvolume(input::PWInput)
if input.system.ibrav == 0
if isnothing(input.cell_parameters)
throw(InsufficientInfoError("`ibrav` is 0, must read cell parameters!"))
else
if getoption(input.cell_parameters) == :alat
# If no value of `celldm` is changed...
if isnothing(input.system.celldm[1])
throw(InsufficientInfoError("parameter `celldm[1]` needed!"))
else
return input.system.celldm[1]^3 * abs(det(input.cell_parameters.data))
end
else # "bohr" or "angstrom"
return cellvolume(input.cell_parameters)
end
end
else
return cellvolume(Lattice(input.system))
end
end
function crystaldensity(input::PWInput)
lattice = Lattice(input) * 1u"bohr"
atoms = (Symbol(uppercasefirst(atom)) for (atom, _) in eachatom(input.atomic_positions))
return crystaldensity(lattice, atoms)
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 4331 | export PWInput, isrequired, isoptional
"""
PWInput(control, system, electrons, ions, cell, atomic_species, atomic_positions, k_points, cell_parameters)
Construct a `PWInput` which represents the input of program `pw.x`.
# Arguments
- `control::ControlNamelist=ControlNamelist()`: the `CONTROL` namelist of the input. Optional.
- `system::SystemNamelist=SystemNamelist()`: the `SYSTEM` namelist of the input. Optional.
- `electrons::ElectronsNamelist=ElectronsNamelist()`: the `ELECTRONS` namelist of the input. Optional.
- `ions::IonsNamelist=IonsNamelist()`: the `IONS` namelist of the input. Optional.
- `cell::CellNamelist=CellNamelist()`: the `CELL` namelist of the input. Optional.
- `atomic_species::AtomicSpeciesCard`: the `ATOMIC_SPECIES` card of the input. Must be provided explicitly.
- `atomic_positions::AtomicPositionsCard`: the `ATOMIC_POSITIONS` card of the input. Must be provided explicitly.
- `k_points::AbstractKPointsCard`: the `K_POINTS` card of the input. Must be provided explicitly.
- `cell_parameters::Union{Nothing,CellParametersCard}`: the `CELL_PARAMETERS` card of the input. Must be either `nothing` or a `CellParametersCard`.
"""
@struct_hash_equal struct PWInput <: QuantumESPRESSOInput
control::ControlNamelist
system::SystemNamelist
electrons::ElectronsNamelist
ions::IonsNamelist
cell::CellNamelist
fcp::FcpNamelist
rism::RismNamelist
atomic_species::AtomicSpeciesCard
atomic_positions::AtomicPositionsCard
k_points::KPointsCard
cell_parameters::Maybe{CellParametersCard}
occupations::Maybe{OccupationsCard}
constraints::Maybe{ConstraintsCard}
atomic_velocities::Maybe{AtomicVelocitiesCard}
atomic_forces::Maybe{AtomicForcesCard}
additional_k_points::Maybe{AdditionalKPointsCard}
solvents::Maybe{SolventsCard}
hubbard::Maybe{HubbardCard}
end
function PWInput(;
control=ControlNamelist(),
system,
electrons=ElectronsNamelist(),
ions=IonsNamelist(),
cell=CellNamelist(),
fcp=FcpNamelist(),
rism=RismNamelist(),
atomic_species,
atomic_positions,
k_points,
cell_parameters=nothing,
occupations=nothing,
constraints=nothing,
atomic_velocities=nothing,
atomic_forces=nothing,
additional_k_points=nothing,
solvents=nothing,
hubbard=nothing,
)
@assert !isnothing(cell_parameters) || system.ibrav != 0 "`cell_parameters` is empty with `ibrav = 0`!"
foreach(eachpotential(atomic_species)) do (_, potential)
path = joinpath(expanduser(control.pseudo_dir), potential)
if !isfile(path)
@warn "pseudopotential file \"$path\" does not exist!"
end
end
return PWInput(
control,
system,
electrons,
ions,
cell,
fcp,
rism,
atomic_species,
atomic_positions,
k_points,
cell_parameters,
occupations,
constraints,
atomic_velocities,
atomic_forces,
additional_k_points,
solvents,
hubbard,
)
end
exitfile(input::PWInput) = exitfile(input.control)
mkexitfile(input::PWInput) = mkexitfile(input.control)
"""
isrequired(nml::Namelist)
isrequired(card::Card)
Test whether a `Namelist` or a `Card` is required in `PWInput`.
"""
isrequired(nml::Namelist) = nml isa Union{ControlNamelist,SystemNamelist,ElectronsNamelist}
isrequired(card::Card) = card isa Union{AtomicSpeciesCard,AtomicPositionsCard,KPointsCard}
"""
isoptional(nml::Namelist)
isoptional(card::Card)
Test whether a `Namelist` or a `Card` is optional in `PWInput`.
"""
isoptional(nml::Namelist) =
nml isa Union{IonsNamelist,CellNamelist,FcpNamelist,RismNamelist}
isoptional(card::Card) =
card isa Union{
CellParametersCard,
OccupationsCard,
ConstraintsCard,
AtomicVelocitiesCard,
AtomicForcesCard,
AdditionalKPointsCard,
SolventsCard,
HubbardCard,
}
"""
eachpotential(input::PWInput)
Iterate the pseudopotentials in a `PWInput`.
"""
eachpotential(input::PWInput) = eachpotential(input.atomic_species)
"""
getpseudodir(input::PWInput)
Get the directory storing the pseudopotential files.
"""
getpseudodir(input::PWInput) = getpseudodir(input.control)
getxmldir(input::PWInput) = getxmldir(input.control)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 26362 | using ConstructionBase: setproperties
using Unitful: Temperature, Energy, Frequency, Wavenumber
using UnitfulEquivalences: Thermal, Spectral
export ControlNamelist,
SystemNamelist,
ElectronsNamelist,
IonsNamelist,
CellNamelist,
DosNamelist,
BandsNamelist,
ElectronicTemperatureSetter,
ElecTempSetter
export exitfile, mkexitfile, getxmldir, listwfcfiles, getpseudodir
# From https://discourse.julialang.org/t/aliases-for-union-t-nothing-and-union-t-missing/15402/4
const Maybe{T} = Union{T,Nothing}
# The default values are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90.
"""
ControlNamelist(calculation, title, verbosity, restart_mode, wf_collect, nstep, iprint, tstress, tprnfor, dt, outdir, wfcdir, prefix, lkpoint_dir, max_seconds, etot_conv_thr, forc_conv_thr, disk_io, pseudo_dir, tefield, dipfield, lelfield, nberrycyc, lorbm, lberry, gdir, nppstr, lfcpopt, gate)
ControlNamelist(; kwargs...)
ControlNamelist(::ControlNamelist; kwargs...)
Represent the `CONTROL` namelist of `pw.x`.
"""
@struct_hash_equal struct ControlNamelist <: Namelist
calculation::String
title::String
verbosity::String
restart_mode::String
wf_collect::Bool
nstep::UInt
iprint::UInt
tstress::Bool
tprnfor::Bool
dt::Float64
outdir::String
wfcdir::String
prefix::String
lkpoint_dir::Bool
max_seconds::Float64
etot_conv_thr::Float64
forc_conv_thr::Float64
disk_io::String
pseudo_dir::String
tefield::Bool
dipfield::Bool
lelfield::Bool
nberrycyc::UInt
lorbm::Bool
lberry::Bool
gdir::UInt8
nppstr::UInt
lfcpopt::Bool
gate::Bool
end # struct ControlNamelist
function ControlNamelist(;
calculation="scf",
title=" ",
verbosity="low",
restart_mode="from_scratch",
wf_collect=true,
nstep=50,
iprint=100000,
tstress=false,
tprnfor=false,
dt=20.0,
outdir="./",
wfcdir="./",
prefix="pwscf",
lkpoint_dir=true,
max_seconds=10000000.0,
etot_conv_thr=1e-4,
forc_conv_thr=1e-3,
disk_io=ifelse(calculation == "scf", "low", "medium"),
pseudo_dir=raw"$HOME/espresso/pseudo/",
tefield=false,
dipfield=false,
lelfield=false,
nberrycyc=1,
lorbm=false,
lberry=false,
gdir=1, # The QE default value is `0`!
nppstr=0,
lfcpopt=false,
gate=false,
)
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1282-L1369.
@assert calculation in ("scf", "nscf", "bands", "relax", "md", "vc-relax", "vc-md")
@assert verbosity in ("high", "low", "debug", "medium", "default", "minimal")
@assert restart_mode in ("from_scratch", "restart")
@assert iprint >= 1
@assert disk_io in ("high", "medium", "low", "none", "default")
@assert dt >= 0
# @assert !(lkpoint_dir && wf_collect) "`lkpoint_dir` currently doesn't work together with `wf_collect`!"
@assert max_seconds >= 0
@assert etot_conv_thr >= 0
@assert forc_conv_thr >= 0
@assert gdir in 1:3
@assert !all((gate, tefield, !dipfield)) "`gate` cannot be used with `tefield` if dipole correction is not active!"
@assert !all((gate, dipfield, !tefield)) "dipole correction is not active if `tefield = false`!"
return ControlNamelist(
calculation,
title,
verbosity,
restart_mode,
wf_collect,
nstep,
iprint,
tstress,
tprnfor,
dt,
outdir,
wfcdir,
prefix,
lkpoint_dir,
max_seconds,
etot_conv_thr,
forc_conv_thr,
disk_io,
pseudo_dir,
tefield,
dipfield,
lelfield,
nberrycyc,
lorbm,
lberry,
gdir,
nppstr,
lfcpopt,
gate,
)
end
ControlNamelist(nml::ControlNamelist; kwargs...) = setproperties(nml; kwargs...)
exitfile(nml::ControlNamelist) =
abspath(expanduser(joinpath(nml.outdir, nml.prefix * ".EXIT")))
function mkexitfile(nml::ControlNamelist)
path = exitfile(nml)
if !isfile(path)
mkpath(dirname(path))
touch(path)
end
return path
end
"""
getxmldir(nml::ControlNamelist)
Return the path to directory storing the XML files.
"""
getxmldir(nml::ControlNamelist) =
abspath(expanduser(joinpath(nml.outdir, nml.prefix * ".save")))
"""
listwfcfiles(nml::ControlNamelist, n=1)
List all wave function files.
"""
listwfcfiles(nml::ControlNamelist, n=1) =
[joinpath(getxmldir(nml), nml.prefix * ".wfc$i") for i in 1:n]
"""
getpseudodir(nml::ControlNamelist)
Get the directory storing the pseudopotential files.
"""
getpseudodir(nml::ControlNamelist) = abspath(expanduser(nml.pseudo_dir))
"""
SystemNamelist(ibrav, celldm, A, B, C, cosAB, cosAC, cosBC, nat, ntyp, nbnd, tot_charge, starting_charge, tot_magnetization, starting_magnetization, ecutwfc, ecutrho, ecutfock, nr1, nr2, nr3, nr1s, nr2s, nr3s, nosym, nosym_evc, noinv, no_t_rev, force_symmorphic, use_all_frac, occupations, one_atom_occupations, starting_spin_angle, degauss, smearing, nspin, noncolin, ecfixed, qcutz, q2sigma, input_dft, exx_fraction, screening_parameter, exxdiv_treatment, x_gamma_extrapolation, ecutvcut, nqx1, nqx2, nqx3, localization_thr, lda_plus_u, lda_plus_u_kind, Hubbard_U, Hubbard_J0, Hubbard_alpha, Hubbard_beta, starting_ns_eigenvalue, U_projection_type, edir, emaxpos, eopreg, eamp, angle1, angle2, constrained_magnetization, fixed_magnetization, lambda, report, lspinorb, assume_isolated, esm_bc, esm_w, esm_efield, esm_nfit, fcp_mu, vdw_corr, london, london_s6, london_c6, london_rvdw, london_rcut, ts_vdw_econv_thr, ts_vdw_isolated, xdm, xdm_a1, xdm_a2, space_group, uniqueb, origin_choice, rhombohedral, zgate, relaxz, block, block_1, block_2, block_height)
SystemNamelist(; kwargs...)
SystemNamelist(::SystemNamelist; kwargs...)
Represent the `SYSTEM` namelist of `pw.x`.
"""
@struct_hash_equal struct SystemNamelist <: Namelist
ibrav::Int8
celldm::Vector{Maybe{Float64}}
A::Float64
B::Float64
C::Float64
cosAB::Float64
cosAC::Float64
cosBC::Float64
nat::UInt
ntyp::UInt8
nbnd::UInt
tot_charge::Float64
starting_charge::Vector{Maybe{Float64}}
tot_magnetization::Float64
starting_magnetization::Vector{Maybe{Float64}}
ecutwfc::Float64
ecutrho::Float64
ecutfock::Float64
nr1::UInt
nr2::UInt
nr3::UInt
nr1s::UInt
nr2s::UInt
nr3s::UInt
nosym::Bool
nosym_evc::Bool
noinv::Bool
no_t_rev::Bool
force_symmorphic::Bool
use_all_frac::Bool
occupations::String
one_atom_occupations::Bool
starting_spin_angle::Bool
degauss::Float64
smearing::String
nspin::UInt8
noncolin::Bool
ecfixed::Float64
qcutz::Float64
q2sigma::Float64
input_dft::String
exx_fraction::Float64
screening_parameter::Float64
exxdiv_treatment::String
x_gamma_extrapolation::Bool
ecutvcut::Float64
nqx1::UInt
nqx2::UInt
nqx3::UInt
localization_thr::Float64
lda_plus_u::Bool
lda_plus_u_kind::UInt8
Hubbard_U::Vector{Maybe{Float64}}
Hubbard_J0::Vector{Maybe{Float64}}
Hubbard_alpha::Vector{Maybe{Float64}}
Hubbard_beta::Vector{Maybe{Float64}}
# Hubbard_J::Vector{Vector{Maybe{Float64}}}
starting_ns_eigenvalue::Float64
U_projection_type::String
edir::UInt8
emaxpos::Float64
eopreg::Float64
eamp::Float64
angle1::Vector{Maybe{Float64}}
angle2::Vector{Maybe{Float64}}
constrained_magnetization::String
fixed_magnetization::Vector{Maybe{Float64}}
lambda::Float64
report::UInt
lspinorb::Bool
assume_isolated::String
esm_bc::String
esm_w::Float64
esm_efield::Float64
esm_nfit::UInt
fcp_mu::Float64
vdw_corr::String
london::Bool
london_s6::Float64
london_c6::Vector{Maybe{Float64}}
london_rvdw::Vector{Maybe{Float64}}
london_rcut::Float64
ts_vdw_econv_thr::Float64
ts_vdw_isolated::Bool
xdm::Bool
xdm_a1::Float64
xdm_a2::Float64
space_group::UInt8
uniqueb::Bool
origin_choice::UInt8
rhombohedral::Bool
zgate::Float64
relaxz::Bool
block::Bool
block_1::Float64
block_2::Float64
block_height::Float64
end # struct SystemNamelist
function SystemNamelist(;
ibrav=127,
celldm=zeros(6), # Must specify
A=0.0,
B=0.0,
C=0.0,
cosAB=0.0,
cosAC=0.0,
cosBC=0.0,
nat=0,
ntyp=0,
nbnd=0,
tot_charge=0.0,
starting_charge=[],
tot_magnetization=-1.0,
starting_magnetization=[],
ecutwfc=0.0,
ecutrho=4ecutwfc,
ecutfock=ecutrho,
nr1=0,
nr2=0,
nr3=0,
nr1s=0,
nr2s=0,
nr3s=0,
nosym=false,
nosym_evc=false,
noinv=false,
no_t_rev=false,
force_symmorphic=false,
use_all_frac=false,
occupations="fixed",
one_atom_occupations=false,
starting_spin_angle=false,
degauss=0.0,
smearing="gaussian",
nspin=1,
noncolin=false,
ecfixed=0.0,
qcutz=0.0,
q2sigma=0.1, # The default value in QE's source code is 0.01
input_dft="none",
exx_fraction=0.25,
screening_parameter=0.106,
exxdiv_treatment="gygi-baldereschi",
x_gamma_extrapolation=true,
ecutvcut=0.0,
nqx1=1,
nqx2=1,
nqx3=1,
localization_thr=0.0, # This is only for QE 6.4
lda_plus_u=false,
lda_plus_u_kind=0,
Hubbard_U=[],
Hubbard_J0=[],
Hubbard_alpha=[],
Hubbard_beta=[],
# Hubbard_J = [zeros(ntyp)] , # The default value in QE's source code is just one 0.0
starting_ns_eigenvalue=-1.0, # It's actually a multidimensional array.
U_projection_type="atomic",
edir=1,
emaxpos=0.5,
eopreg=0.1,
eamp=0.001, # The default value in QE's source code is 0.0
angle1=[],
angle2=[],
constrained_magnetization="none",
fixed_magnetization=zeros(3), # The default value in QE's source code is just one 0.0
lambda=1.0,
report=100,
lspinorb=false,
assume_isolated="none",
esm_bc="pbc",
esm_w=0.0,
esm_efield=0.0,
esm_nfit=4,
fcp_mu=0.0,
vdw_corr="none",
london=false,
london_s6=0.75,
london_c6=[],
london_rvdw=[],
london_rcut=200.0,
ts_vdw_econv_thr=1e-06,
ts_vdw_isolated=false,
xdm=false,
xdm_a1=0.6836, # The default value in QE's source code is 0.0
xdm_a2=1.5045, # The default value in QE's source code is 0.0
space_group=0,
uniqueb=false,
origin_choice=1,
rhombohedral=true,
zgate=0.5,
relaxz=false,
block=false,
block_1=0.45,
block_2=0.55,
block_height=0.1, # The default value in QE's source code is 0.0
)
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1378-L1499.
@assert ibrav in union(0:1:14, (-3, -5, -9, 91, -12, -13), 127)
@assert ntyp <= 10 && ntyp <= nat
@assert smearing in (
"gaussian",
"gauss",
"methfessel-paxton",
"m-p",
"mp",
"marzari-vanderbilt",
"cold",
"m-v",
"mv",
"fermi-dirac",
"f-d",
"fd",
)
@assert nspin in (1, 2, 4)
@assert ecutwfc >= 0 # From `set_cutoff` in https://github.com/QEF/q-e/blob/7573301/PW/src/input.f90#L1597-L1639
@assert ecutrho >= ecutwfc # From `set_cutoff`
@assert ecfixed >= 0
@assert qcutz >= 0
@assert q2sigma >= 0
@assert lda_plus_u_kind in 0:1
@assert edir in 1:3
@assert space_group in 0:230
@assert origin_choice in 1:2
@assert length(starting_charge) <= ntyp
@assert length(starting_magnetization) <= ntyp
@assert length(Hubbard_U) <= ntyp
@assert length(Hubbard_J0) <= ntyp
@assert length(Hubbard_alpha) <= ntyp
@assert length(Hubbard_beta) <= ntyp
# @assert all(length(x) <= ntyp for x in Hubbard_J)
@assert length(angle1) <= ntyp
@assert length(angle2) <= ntyp
@assert length(fixed_magnetization) <= 3
@assert length(london_c6) <= ntyp
@assert length(london_rvdw) <= ntyp
@assert exxdiv_treatment in
("gygi-baldereschi", "gygi-bald", "g-b", "vcut_ws", "vcut_spherical", "none")
@assert !(x_gamma_extrapolation && exxdiv_treatment in ("vcut_ws", "vcut_spherical")) "`x_gamma_extrapolation` cannot be used with `vcut`!"
return SystemNamelist(
ibrav,
celldm,
A,
B,
C,
cosAB,
cosAC,
cosBC,
nat,
ntyp,
nbnd,
tot_charge,
starting_charge,
tot_magnetization,
starting_magnetization,
ecutwfc,
ecutrho,
ecutfock,
nr1,
nr2,
nr3,
nr1s,
nr2s,
nr3s,
nosym,
nosym_evc,
noinv,
no_t_rev,
force_symmorphic,
use_all_frac,
occupations,
one_atom_occupations,
starting_spin_angle,
degauss,
smearing,
nspin,
noncolin,
ecfixed,
qcutz,
q2sigma,
input_dft,
exx_fraction,
screening_parameter,
exxdiv_treatment,
x_gamma_extrapolation,
ecutvcut,
nqx1,
nqx2,
nqx3,
localization_thr,
lda_plus_u,
lda_plus_u_kind,
Hubbard_U,
Hubbard_J0,
Hubbard_alpha,
Hubbard_beta,
starting_ns_eigenvalue,
U_projection_type,
edir,
emaxpos,
eopreg,
eamp,
angle1,
angle2,
constrained_magnetization,
fixed_magnetization,
lambda,
report,
lspinorb,
assume_isolated,
esm_bc,
esm_w,
esm_efield,
esm_nfit,
fcp_mu,
vdw_corr,
london,
london_s6,
london_c6,
london_rvdw,
london_rcut,
ts_vdw_econv_thr,
ts_vdw_isolated,
xdm,
xdm_a1,
xdm_a2,
space_group,
uniqueb,
origin_choice,
rhombohedral,
zgate,
relaxz,
block,
block_1,
block_2,
block_height,
)
end
SystemNamelist(nml::SystemNamelist; kwargs...) = setproperties(nml; kwargs...)
"""
ElectronsNamelist(electron_maxstep, scf_must_converge, conv_thr, adaptive_thr, conv_thr_init, conv_thr_multi, mixing_mode, mixing_beta, mixing_ndim, mixing_fixed_ns, diagonalization, ortho_para, diago_thr_init, diago_cg_maxiter, diago_david_ndim, diago_full_acc, efield, efield_cart, efield_phase, startingpot, startingwfc, tqr)
ElectronsNamelist(; kwargs...)
ElectronsNamelist(::ElectronsNamelist; kwargs...)
Represent the `ELECTRONS` namelist of `pw.x`.
"""
@struct_hash_equal struct ElectronsNamelist <: Namelist
electron_maxstep::UInt
scf_must_converge::Bool
conv_thr::Float64
adaptive_thr::Bool
conv_thr_init::Float64
conv_thr_multi::Float64
mixing_mode::String
mixing_beta::Float64
mixing_ndim::UInt
mixing_fixed_ns::UInt
diagonalization::String
ortho_para::UInt
diago_thr_init::Float64
diago_cg_maxiter::UInt
diago_david_ndim::UInt
diago_full_acc::Bool
efield::Float64
efield_cart::Vector{Maybe{Float64}}
efield_phase::String
startingpot::String # This depends on `calculation`
startingwfc::String # This depends on `calculation`
tqr::Bool
end # struct ElectronsNamelist
function ElectronsNamelist(;
electron_maxstep=100,
scf_must_converge=true,
conv_thr=1e-6,
adaptive_thr=false,
conv_thr_init=1e-3,
conv_thr_multi=0.1,
mixing_mode="plain",
mixing_beta=0.7,
mixing_ndim=8,
mixing_fixed_ns=0,
diagonalization="david",
ortho_para=0,
diago_thr_init=0.0,
diago_cg_maxiter=20,
diago_david_ndim=4,
diago_full_acc=false,
efield=0.0,
efield_cart=zeros(3),
efield_phase="none",
startingpot="atomic", # This depends on `calculation`
startingwfc="atomic+random", # This depends on `calculation`
tqr=false,
)
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1508-L1543.
@assert mixing_mode in ("plain", "TF", "local-TF")
@assert diagonalization in ("david", "cg", "cg-serial", "david-serial", "ppcg") # Different from docs
@assert efield_phase in ("read", "write", "none")
@assert startingpot in ("atomic", "file")
@assert startingwfc in ("atomic", "atomic+random", "random", "file")
return ElectronsNamelist(
electron_maxstep,
scf_must_converge,
conv_thr,
adaptive_thr,
conv_thr_init,
conv_thr_multi,
mixing_mode,
mixing_beta,
mixing_ndim,
mixing_fixed_ns,
diagonalization,
ortho_para,
diago_thr_init,
diago_cg_maxiter,
diago_david_ndim,
diago_full_acc,
efield,
efield_cart,
efield_phase,
startingpot,
startingwfc,
tqr,
)
end
ElectronsNamelist(nml::ElectronsNamelist; kwargs...) = setproperties(nml; kwargs...)
"""
IonsNamelist(ion_dynamics, ion_positions, pot_extrapolation, wfc_extrapolation, remove_rigid_rot, ion_temperature, tempw, tolp, delta_t, nraise, refold_pos, upscale, bfgs_ndim, trust_radius_max, trust_radius_min, trust_radius_ini, w_1, w_2)
IonsNamelist(; kwargs...)
IonsNamelist(::IonsNamelist; kwargs...)
Represent the `IONS` namelist of `pw.x`.
Input this namelist only if `calculation` is `"relax"`, `"md"`, `"vc-relax"`, or `"vc-md"`.
"""
@struct_hash_equal struct IonsNamelist <: Namelist
ion_dynamics::String
ion_positions::String
pot_extrapolation::String
wfc_extrapolation::String
remove_rigid_rot::Bool
ion_temperature::String
tempw::Float64
tolp::Float64
delta_t::Float64
nraise::UInt
refold_pos::Bool
upscale::Float64
bfgs_ndim::UInt
trust_radius_max::Float64
trust_radius_min::Float64 # The default value in QE's source code is 0.0001
trust_radius_ini::Float64
w_1::Float64
w_2::Float64
end # struct IonsNamelist
function IonsNamelist(;
ion_dynamics="none",
ion_positions="default",
pot_extrapolation="atomic",
wfc_extrapolation="none",
remove_rigid_rot=false,
ion_temperature="not_controlled",
tempw=300.0,
tolp=100.0,
delta_t=1.0,
nraise=1,
refold_pos=false,
upscale=100.0,
bfgs_ndim=1,
trust_radius_max=0.8,
trust_radius_min=1e-3, # The default value in QE's source code is 0.0001
trust_radius_ini=0.5,
w_1=0.01,
w_2=0.5,
)
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1552-L1585.
@assert ion_dynamics in
("none", "bfgs", "damp", "verlet", "langevin", "langevin-smc", "beeman")
@assert ion_positions in ("default", "from_input")
@assert pot_extrapolation in ("none", "atomic", "first_order", "second_order")
@assert wfc_extrapolation in ("none", "first_order", "second_order")
@assert ion_temperature in (
"rescaling",
"rescale-v",
"rescale-T",
"reduce-T",
"berendsen",
"andersen",
"initial",
"not_controlled",
)
@assert tempw > 0
return IonsNamelist(
ion_dynamics,
ion_positions,
pot_extrapolation,
wfc_extrapolation,
remove_rigid_rot,
ion_temperature,
tempw,
tolp,
delta_t,
nraise,
refold_pos,
upscale,
bfgs_ndim,
trust_radius_max,
trust_radius_min,
trust_radius_ini,
w_1,
w_2,
)
end
IonsNamelist(nml::IonsNamelist; kwargs...) = setproperties(nml; kwargs...)
"""
CellNamelist(cell_dynamics, press, wmass, cell_factor, press_conv_thr, cell_dofree)
CellNamelist(; kwargs...)
CellNamelist(::CellNamelist; kwargs...)
Represent the `CELL` namelist of `pw.x`.
Input this namelist only if `calculation` is `"vc-relax"` or `"vc-md"`.
"""
@struct_hash_equal struct CellNamelist <: Namelist
cell_dynamics::String
press::Float64
wmass::Float64
cell_factor::Float64
press_conv_thr::Float64
cell_dofree::String
end # struct CellNamelist
function CellNamelist(;
cell_dynamics="none",
press=0.0,
wmass=0.0,
cell_factor=0.0,
press_conv_thr=0.5,
cell_dofree="all",
)
# These checks are from https://github.com/QEF/q-e/blob/4132a64/Modules/read_namelists.f90#L1596-L1625.
@assert cell_dynamics in ("none", "sd", "damp-pr", "damp-w", "bfgs", "pr", "w")
@assert wmass >= 0
@assert cell_dofree in (
"all",
"ibrav",
"x",
"y",
"z",
"xy",
"xz",
"yz",
"xyz",
"shape",
"volume",
"2Dxy",
"2Dshape",
"epitaxial_ab", # New in 6.4
"epitaxial_ac", # New in 6.4
"epitaxial_bc", # New in 6.4
)
return CellNamelist(
cell_dynamics, press, wmass, cell_factor, press_conv_thr, cell_dofree
)
end
CellNamelist(nml::CellNamelist; kwargs...) = setproperties(nml; kwargs...)
# The following default values are picked from `<QE source>/PP/src/dos.f90`
"""
DosNamelist(prefix, outdir, ngauss, degauss, Emin, Emax, DeltaE, fildos)
DosNamelist(; kwargs...)
DosNamelist(::DosNamelist; kwargs...)
Represent the `DOS` namelist of `dos.x`.
"""
@struct_hash_equal struct DosNamelist <: Namelist
prefix::String
outdir::String
ngauss::Int
degauss::Float64
Emin::Float64
Emax::Float64
DeltaE::Float64
fildos::String
end # struct DosNamelist
function DosNamelist(;
prefix="pwscf",
outdir="./",
ngauss=0,
degauss=0.0,
Emin=-1000000.0,
Emax=1000000.0,
DeltaE=0.01,
fildos="$(prefix).dos",
)
@assert ngauss in (0, 1, -1, -99)
return DosNamelist(prefix, outdir, ngauss, degauss, Emin, Emax, DeltaE, fildos)
end
DosNamelist(nml::DosNamelist; kwargs...) = setproperties(nml; kwargs...)
# The following default values are picked from `<QE source>/PP/src/bands.f90`
"""
BandsNamelist(prefix, outdir, filband, spin_component, lsigma, lp, filp, lsym, no_overlap, plot_2d, firstk, lastk)
BandsNamelist(; kwargs...)
BandsNamelist(::BandsNamelist; kwargs...)
Represent the `BANDS` namelist of `bands.x`.
"""
@struct_hash_equal struct BandsNamelist <: Namelist
prefix::String
outdir::String
filband::String
spin_component::UInt8
lsigma::Vector{Maybe{Bool}} # The default value in QE's source code is just one `false`
lp::Bool
filp::String
lsym::Bool
no_overlap::Bool
plot_2d::Bool
firstk::UInt
lastk::UInt
end # struct BandsNamelist
function BandsNamelist(;
prefix="pwscf",
outdir="./",
filband="bands.out",
spin_component=1,
lsigma=falses(3), # The default value in QE's source code is just one `false`
lp=false,
filp="p_avg.dat",
lsym=true,
no_overlap=true,
plot_2d=false,
firstk=0,
lastk=10000000,
)
@assert spin_component in 1:2
return BandsNamelist(
prefix,
outdir,
filband,
spin_component,
lsigma,
lp,
filp,
lsym,
no_overlap,
plot_2d,
firstk,
lastk,
)
end
BandsNamelist(nml::BandsNamelist; kwargs...) = setproperties(nml; kwargs...)
@struct_hash_equal struct FcpNamelist <: Namelist
# fcp_mu
# fcp_dynamics
fcp_conv_thr::Float64
# fcp_ndiis
# fcp_mass
# fcp_velocity
# fcp_temperature
# fcp_tempw
# fcp_tolp
# fcp_delta_t
# fcp_nraise
# freeze_all_atoms
end
function FcpNamelist(; fcp_conv_thr=1e-2)
return FcpNamelist(fcp_conv_thr)
end
@struct_hash_equal struct RismNamelist <: Namelist
# nsolv
closure::String
# tempv
# ecutsolv
# solute_lj
# solute_epsilon
# solute_sigma
# starting1d
# starting3d
# smear1d
# smear3d
# rism1d_maxstep
# rism3d_maxstep
# rism1d_conv_thr
# rism3d_conv_thr
# mdiis1d_size
# mdiis3d_size
# mdiis1d_step
# mdiis3d_step
# rism1d_bond_width
# rism1d_dielectric
# rism1d_molesize
# rism1d_nproc
# rism3d_conv_level
# rism3d_planar_average
# laue_nfit
# laue_expand_right
# laue_expand_left
# laue_starting_right
# laue_starting_left
# laue_buffer_right
# laue_buffer_left
# laue_both_hands
# laue_wall
# laue_wall_z
# laue_wall_rho
# laue_wall_epsilon
# laue_wall_sigma
# laue_wall_lj6
end
function RismNamelist(; closure="kh")
return RismNamelist(closure)
end
function (x::VerbositySetter)(control::ControlNamelist)
if x.v == "high"
@reset control.verbosity = "high"
@reset control.wf_collect = true
@reset control.tstress = true
@reset control.tprnfor = true
@reset control.disk_io = "high"
else
@reset control.verbosity = "low"
@reset control.wf_collect = false
@reset control.tstress = false
@reset control.tprnfor = false
@reset control.disk_io = "low"
end
return control
end
struct ElectronicTemperatureSetter{T<:Number} <: Setter
value::T
end
function (x::ElectronicTemperatureSetter)(system::SystemNamelist)
@reset system.occupations = "smearing"
@reset system.smearing = "fermi-dirac"
@reset system.degauss = degauss(x.value)
return system
end
degauss(value::Real) = value
degauss(value::Temperature) = ustrip(u"Ry", value, Thermal())
degauss(value::Energy) = ustrip(u"Ry", value)
degauss(value::Frequency) = ustrip(u"Ry", value, Spectral())
degauss(value::Wavenumber) = ustrip(u"Ry", value, Spectral())
const ElecTempSetter = ElectronicTemperatureSetter
# _coupledargs(::Type{ControlNamelist}) = (:calculation => :disk_io,)
# _coupledargs(::Type{SystemNamelist}) = (:ecutwfc => :ecutrho, :ecutrho => :ecutfock)
# _coupledargs(::Type{DosNamelist}) = (:prefix => :fildos,)
groupname(::Type{ControlNamelist}) = "CONTROL"
groupname(::Type{SystemNamelist}) = "SYSTEM"
groupname(::Type{ElectronsNamelist}) = "ELECTRONS"
groupname(::Type{IonsNamelist}) = "IONS"
groupname(::Type{CellNamelist}) = "CELL"
groupname(::Type{FcpNamelist}) = "FCP"
groupname(::Type{RismNamelist}) = "RISM"
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 2298 | export VerbositySetter,
VolumeSetter,
PressureSetter,
CardSetter,
CellParametersCardSetter,
AtomicPositionsCardSetter
function (s::VerbositySetter)(template::PWInput)
@reset template.control = s(template.control)
return template
end
function (x::ElectronicTemperatureSetter)(template::PWInput)
@reset template.system = x(template.system)
return template
end
struct VolumeSetter{T<:Number} <: Setter
vol::T
end
function (x::VolumeSetter{<:Real})(template::PWInput)
factor = cbrt(x.vol / cellvolume(template))
if isnothing(template.cell_parameters) || getoption(template.cell_parameters) == :alat
@reset template.system.celldm[1] *= factor
else
@reset template.system.celldm = zeros(6)
@reset template.cell_parameters = convertoption(
CellParametersCard(template.cell_parameters.data * factor), :bohr
)
end
return template
end
(x::VolumeSetter{<:AbstractQuantity})(template::PWInput) =
VolumeSetter(ustrip(u"bohr^3", x.vol))(template)
struct PressureSetter{T<:Number} <: Setter
press::T
end
function (x::PressureSetter{<:Real})(template::PWInput)
@reset template.cell.press = x.press
return template
end
(x::PressureSetter{<:AbstractQuantity})(template::PWInput) =
PressureSetter(ustrip(u"kbar", x.press))(template)
struct CardSetter{T} <: Setter
card::T
end
const CellParametersCardSetter = CardSetter{CellParametersCard}
const AtomicPositionsCardSetter = CardSetter{AtomicPositionsCard}
function (x::CellParametersCardSetter)(template::PWInput)
if getoption(x.card) == :alat
if isnothing(template.cell_parameters) ||
getoption(template.cell_parameters) == :alat
@reset template.system.celldm = [template.system.celldm[1]]
else # getoption(template.cell_parameters) is `:bohr` or `:angstrom`
throw(InsufficientInfoError("the `CellParametersCard` does not have units!"))
end
else # "bohr" or "angstrom"
@reset template.system.celldm = zeros(6)
end
@reset template.system.ibrav = 0
@reset template.cell_parameters = x.card
return template
end
function (x::AtomicPositionsCardSetter)(template::PWInput)
@reset template.atomic_positions = x.card
return template
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 453 | export iscompatible
function iscompatible(system::SystemNamelist, cell_parameters::CellParametersCard)
ibrav, celldm = system.ibrav, system.celldm
if iszero(ibrav)
if getoption(cell_parameters) in (:bohr, :angstrom)
return all(iszero, celldm)
else # "alat"
return !iszero(first(celldm)) # first(celldm) != 0
end
else
return false
end
end
iscompatible(x, y) = iscompatible(y, x)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 3877 | module CP
using Test
using Accessors
using StructArrays: StructArray
using QuantumESPRESSOBase
using QuantumESPRESSOBase.CP
@testset "Constructing `AtomicVelocity`" begin
# Data from https://gitlab.com/QEF/q-e/blob/master/CPV/examples/autopilot-example/reference/water.autopilot.out
x = AtomicVelocity("H", [0.140374E-04, -0.333683E-04, 0.231834E-04])
@test_throws AssertionError @set x.atom = "hydrogen"
@test_throws InexactError @set x.velocity = [1im, 2im, 3im]
@test_throws AssertionError x.velocity = [1, 2, 3, 4]
@test_throws AssertionError x.velocity = [1, 2]
x.atom = 'H' # Setting `atom` with a `Char` still works
@test x.atom == "H"
@test_throws ErrorException x.velociti = [1, 2, 3] # Given a wrong field name
@test x == AtomicVelocity("H", [0.140374E-04, -0.333683E-04, 0.231834E-04])
y = AtomicVelocity('H') # Incomplete initialization
@test_throws UndefRefError y == AtomicVelocity("H")
as = AtomicSpecies("H", 1.00794000, "H.pbe-rrkjus_psl.1.0.0.UPF")
v = [0.140374E-04, -0.333683E-04, 0.231834E-04]
@test AtomicVelocity(as).atom == "H"
@test AtomicVelocity(as, v) == AtomicVelocity("H", v)
ap = AtomicPosition('H', [0.500000000, 0.288675130, 1.974192764])
@test AtomicVelocity(ap).atom == "H"
@test AtomicVelocity(ap, v) == AtomicVelocity("H", v)
end # testset
@testset "Test constructing `AtomicVelocitiesCard` from `StructArray`" begin
a = ["H", "O"]
v = [
[0.140374E-04, -0.333683E-04, 0.231834E-04],
[-0.111125E-05, -0.466724E-04, 0.972745E-05],
]
card = AtomicVelocitiesCard(StructArray{AtomicVelocity}((a, v)))
@test card.data == [
AtomicVelocity("H", [0.140374E-04, -0.333683E-04, 0.231834E-04]),
AtomicVelocity("O", [-0.111125E-05, -0.466724E-04, 0.972745E-05]),
]
end # testset
@testset "Test `push_atom!`" begin
@testset "`push_atom!` for `AtomicVelocity`" begin
v = [AtomicVelocity("H", [0.140374E-04, -0.333683E-04, 0.231834E-04])]
push_atom!(v, "S", "N")
@test [x.atom for x in v] == ["H", "S", "N"]
end # testset
@testset "" begin
a = ["H", "O"]
v = [
[0.140374E-04, -0.333683E-04, 0.231834E-04],
[-0.111125E-05, -0.466724E-04, 0.972745E-05],
]
card = AtomicVelocitiesCard(StructArray{AtomicVelocity}((a, v)))
push_atom!(card, "S", "N")
@test [x.atom for x in card.data] == ["H", "O", "S", "N"]
end # testset
end # testset
@testset "Test `append_atom!`" begin
@testset "`append_atom!` to `AtomicVelocity`" begin
v = [AtomicVelocity("H", [0.140374E-04, -0.333683E-04, 0.231834E-04])]
append_atom!(v, ["S", "N"])
@test [x.atom for x in v] == ["H", "S", "N"]
end # testset
@testset "`append_atom!` to `AtomicVelocitiesCard`" begin
a = ["H", "O"]
v = [
[0.140374E-04, -0.333683E-04, 0.231834E-04],
[-0.111125E-05, -0.466724E-04, 0.972745E-05],
]
card = AtomicVelocitiesCard(StructArray{AtomicVelocity}((a, v)))
append_atom!(card, ["S", "N"])
@test [x.atom for x in card.data] == ["H", "O", "S", "N"]
end # testset
end # testset
@testset "Constructing `RefCellParametersCard`" begin
option = "bohr"
data = [
12 0 0
0 5 0
0 0 5
]
init = RefCellParametersCard(option, data)
@test_throws AssertionError @set init.option = "alat"
@test_throws AssertionError @set init.option = "crystal" # Allowed options are angstrom, bohr
@test_throws AssertionError @set init.data = [ # Matrix size should be (3, 3)
1 2
3 4
]
@test_throws AssertionError @set init.data = [
1 2 3 4
5 6 7 8
4 3 2 1
8 7 6 5
]
@test RefCellParametersCard(data).option == :bohr
end # testset
end # module CP
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 2253 | module PHonon
using Test
using QuantumESPRESSOBase.PHonon:
PhNamelist,
Q2rNamelist,
MatdynNamelist,
QPointsCard,
PhInput,
Q2rInput,
MatdynInput,
DynmatInput
@testset "Construct a `PhInput`: silicon" begin
ph = PhNamelist(;
verbosity="high",
fildyn="dyn",
outdir="./tmp",
prefix="silicon",
ldisp=true,
tr2_ph=1e-14,
nq1=2,
nq2=2,
nq3=2,
amass=[28.086],
)
q_points = QPointsCard(
[
0.125 0.125 0.125 1.0
0.125 0.125 0.375 3.0
0.125 0.125 0.625 3.0
0.125 0.125 0.875 3.0
0.125 0.375 0.375 3.0
0.125 0.375 0.625 6.0
0.125 0.375 0.875 6.0
0.125 0.625 0.625 3.0
0.375 0.375 0.375 1.0
0.375 0.375 0.625 3.0
],
)
input = PhInput(ph, q_points)
# Test struct equality
@test input == PhInput(deepcopy(ph), deepcopy(q_points))
end
@testset "Construct a `Q2rInput`" begin
q2r = Q2rNamelist(; fildyn="dyn", zasr="crystal", flfrc="fc.out")
input = Q2rInput(q2r)
# Test struct equality
@test input == Q2rInput(deepcopy(q2r))
end
@testset "Construct a `MatdynInput`: silicon" begin
matdyn = MatdynNamelist(;
asr="crystal",
amass=[28.086],
flfrc="fc.out",
flfrq="freq.out",
flvec="modes.out",
dos=true,
q_in_band_form=false,
nk1=8,
nk2=8,
nk3=8,
)
q_points = QPointsCard(
[
0.125 0.125 0.125 1.0
0.125 0.125 0.375 3.0
0.125 0.125 0.625 3.0
0.125 0.125 0.875 3.0
0.125 0.375 0.375 3.0
0.125 0.375 0.625 6.0
0.125 0.375 0.875 6.0
0.125 0.625 0.625 3.0
0.375 0.375 0.375 1.0
0.375 0.375 0.625 3.0
],
)
input = MatdynInput(matdyn, q_points)
# Test struct equality
@test input == MatdynInput(deepcopy(matdyn), deepcopy(q_points))
end
@testset "Test if `==` is working" begin
@test PhInput() == PhInput()
@test Q2rInput() == Q2rInput()
@test MatdynInput() == MatdynInput()
@test DynmatInput() == DynmatInput()
end
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 18400 | module PWscf
using Test: @testset, @test, @test_throws
using Accessors: @set
using StructArrays: StructArray
using QuantumESPRESSOBase
using QuantumESPRESSOBase.PWscf
@testset "Test if `==` is working" begin
@test ControlNamelist() == ControlNamelist()
@test SystemNamelist() == SystemNamelist()
@test ElectronsNamelist() == ElectronsNamelist()
@test IonsNamelist() == IonsNamelist()
@test CellNamelist() == CellNamelist()
@test DosNamelist() == DosNamelist()
@test BandsNamelist() == BandsNamelist()
end
@testset "Construct `AtomicSpecies`" begin
# Data from https://github.com/QEF/q-e/blob/7be27df/PW/examples/gatefield/run_example#L128.
x = AtomicSpecies("S", 32.066, "S.pz-n-rrkjus_psl.0.1.UPF")
@test_throws AssertionError @set x.atom = "sulfur"
@test_throws InexactError @set x.mass = 1im
@test x == AtomicSpecies('S', 32.066, "S.pz-n-rrkjus_psl.0.1.UPF")
@test x == AtomicSpecies(
AtomicPosition('S', [0.500000000, 0.288675130, 1.974192764]),
32.066,
"S.pz-n-rrkjus_psl.0.1.UPF",
)
end
@testset "Construct `AtomicSpeciesCard` from a `StructArray`" begin
a = ["Al", "As"]
m = [24590.7655930491, 68285.4024548272]
pp = ["Al.pbe-n-kjpaw_psl.1.0.0.UPF", "As.pbe-n-kjpaw_psl.1.0.0.UPF"]
card = AtomicSpeciesCard(StructArray{AtomicSpecies}((a, m, pp)))
@test card == AtomicSpeciesCard([
AtomicSpecies("Al", 24590.7655930491, "Al.pbe-n-kjpaw_psl.1.0.0.UPF"),
AtomicSpecies("As", 68285.4024548272, "As.pbe-n-kjpaw_psl.1.0.0.UPF"),
])
push!(card.data, AtomicSpecies("Si", 25591.1924913552, "Si.pbe-n-kjpaw_psl.1.0.0.UPF"))
@test card == AtomicSpeciesCard([
AtomicSpecies("Al", 24590.7655930491, "Al.pbe-n-kjpaw_psl.1.0.0.UPF"),
AtomicSpecies("As", 68285.4024548272, "As.pbe-n-kjpaw_psl.1.0.0.UPF"),
AtomicSpecies("Si", 25591.1924913552, "Si.pbe-n-kjpaw_psl.1.0.0.UPF"),
])
end
@testset "Construct `AtomicPosition`" begin
# Data from https://github.com/QEF/q-e/blob/7be27df/PW/examples/gatefield/run_example#L129-L132.
x = AtomicPosition("S", [0.500000000, 0.288675130, 1.974192764])
@test_throws AssertionError @set x.atom = "sulfur"
@test_throws InexactError @set x.pos = [1im, 2im, 3im]
@test_throws ErrorException x.posi = [0.1, 0.2, 0.3] # Given a wrong field name
@test x.if_pos == [1, 1, 1]
@test x == AtomicPosition('S', [0.500000000, 0.288675130, 1.974192764])
@test x == AtomicPosition(
AtomicSpecies('S', 32.066, "S.pz-n-rrkjus_psl.0.1.UPF"),
[0.500000000, 0.288675130, 1.974192764],
)
end
@testset "Construct `AtomicPositionsCard` from a `StructArray`" begin
# Data from https://github.com/QEF/q-e/blob/7be27df/PW/examples/gatefield/run_example#L129-L132.
a = ["S", "Mo", "S"]
pos = [
[0.500000000, 0.288675130, 1.974192764],
[0.000000000, 0.577350270, 2.462038339],
[0.000000000, -0.577350270, 2.950837559],
]
card = AtomicPositionsCard(
StructArray{AtomicPosition}((a, pos, [[1, 1, 1], [1, 1, 1], [1, 1, 1]])), "alat"
)
@test card == AtomicPositionsCard(
[
AtomicPosition("S", [0.500000000, 0.288675130, 1.974192764]),
AtomicPosition("Mo", [0.000000000, 0.577350270, 2.462038339]),
AtomicPosition("S", [0.000000000, -0.577350270, 2.950837559]),
],
"alat",
)
end
@testset "Construct `CellParametersCard`" begin
#Data from https://gitlab.com/QEF/q-e/blob/master/NEB/examples/neb1.in
option = "bohr"
data = [
12 0 0
0 5 0
0 0 5
]
card = CellParametersCard(data, option)
@test_throws AssertionError @set card.option = "ala"
@test_throws AssertionError @set card.option = "crystal" # Allowed options are alat, angstrom, bohr
@test_throws DimensionMismatch @set card.data = [ # Matrix size should be (3, 3)
1 2
3 4
]
@test_throws DimensionMismatch @set card.data = [
1 2 3 4
5 6 7 8
4 3 2 1
8 7 6 5
]
@test CellParametersCard(data).option == :alat # default option is alat
end
@testset "Construct `AtomicForce`" begin
x = AtomicForce("H", [1, 2, 3])
@test_throws DimensionMismatch @set x.force = [1, 2]
@test_throws DimensionMismatch @set x.force = [1, 2, 3, 4]
end
@testset "Construct `AtomicForce` from a `StructArray`" begin
a = ["H", "O", "H"]
f = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
card = AtomicForcesCard(StructArray{AtomicForce}((a, f)))
@test card == AtomicForcesCard([
AtomicForce("H", [1, 2, 3]),
AtomicForce("O", [4, 5, 6]),
AtomicForce("H", [7, 8, 9]),
])
end
@testset "Construct a `PWInput`: silicon" begin
# This example is from https://github.com/QEF/q-e/blob/master/PW/examples/example01/run_example.
for diago in ("david", "cg", "ppcg")
control = ControlNamelist(;
tstress=true, tprnfor=true, outdir="./", prefix="silicon", pseudo_dir="pseudo/"
)
system = SystemNamelist(; ibrav=2, celldm=[10.2], nat=2, ntyp=1, ecutwfc=18.0)
electrons = ElectronsNamelist(; conv_thr=1.0e-8, diagonalization=diago)
atomic_species = AtomicSpeciesCard([AtomicSpecies("Si", 28.086, "Si.pz-vbc.UPF")])
atomic_positions = AtomicPositionsCard([
AtomicPosition("Si", [0.0, 0.0, 0.0]), AtomicPosition("Si", [0.25, 0.25, 0.25])
])
k_points = SpecialPointsCard([
SpecialPoint(0.125, 0.125, 0.125, 1),
SpecialPoint(0.125, 0.125, 0.375, 3),
SpecialPoint(0.125, 0.125, 0.625, 3),
SpecialPoint(0.125, 0.125, 0.875, 3),
SpecialPoint(0.125, 0.375, 0.375, 3),
SpecialPoint(0.125, 0.375, 0.625, 6),
SpecialPoint(0.125, 0.375, 0.875, 6),
SpecialPoint(0.125, 0.625, 0.625, 3),
SpecialPoint(0.375, 0.375, 0.375, 1),
SpecialPoint(0.375, 0.375, 0.625, 3),
])
input = PWInput(;
control=control,
system=system,
electrons=electrons,
atomic_species=atomic_species,
atomic_positions=atomic_positions,
k_points=k_points,
)
@test input.electrons.diagonalization == diago
@test input == PWInput(;
control=deepcopy(control),
system=deepcopy(system),
electrons=deepcopy(electrons),
atomic_species=deepcopy(atomic_species),
atomic_positions=deepcopy(atomic_positions),
k_points=deepcopy(k_points),
)
@test collect(eachpotential(input)) == ["Si.pz-vbc.UPF"]
if !Sys.iswindows()
@test getpseudodir(input) == joinpath(@__DIR__, "pseudo/")
@test getxmldir(input) == joinpath(@__DIR__, "silicon.save")
end
end
end
@testset "Construct a `PWInput`: silicon bands" begin
# This example is from https://github.com/QEF/q-e/blob/master/PW/examples/example01/run_example.
for diago in ("david", "cg", "ppcg")
control = ControlNamelist(;
calculation="bands", pseudo_dir="pseudo/", outdir="./", prefix="silicon"
)
system = SystemNamelist(;
ibrav=2, celldm=[10.2], nat=2, ntyp=1, ecutwfc=18.0, nbnd=8
)
electrons = ElectronsNamelist(; diagonalization=diago)
atomic_species = AtomicSpeciesCard([AtomicSpecies("Si", 28.086, "Si.pz-vbc.UPF")])
atomic_positions = AtomicPositionsCard([
AtomicPosition("Si", [0.0, 0.0, 0.0]), AtomicPosition("Si", [0.25, 0.25, 0.25])
])
k_points = SpecialPointsCard([
SpecialPoint(0.0, 0.0, 0.0, 1),
SpecialPoint(0.0, 0.0, 0.1, 1),
SpecialPoint(0.0, 0.0, 0.2, 1),
SpecialPoint(0.0, 0.0, 0.3, 1),
SpecialPoint(0.0, 0.0, 0.4, 1),
SpecialPoint(0.0, 0.0, 0.5, 1),
SpecialPoint(0.0, 0.0, 0.6, 1),
SpecialPoint(0.0, 0.0, 0.7, 1),
SpecialPoint(0.0, 0.0, 0.8, 1),
SpecialPoint(0.0, 0.0, 0.9, 1),
SpecialPoint(0.0, 0.0, 1.0, 1),
SpecialPoint(0.0, 0.0, 0.0, 1),
SpecialPoint(0.0, 0.1, 0.1, 1),
SpecialPoint(0.0, 0.2, 0.2, 1),
SpecialPoint(0.0, 0.3, 0.3, 1),
SpecialPoint(0.0, 0.4, 0.4, 1),
SpecialPoint(0.0, 0.5, 0.5, 1),
SpecialPoint(0.0, 0.6, 0.6, 1),
SpecialPoint(0.0, 0.7, 0.7, 1),
SpecialPoint(0.0, 0.8, 0.8, 1),
SpecialPoint(0.0, 0.9, 0.9, 1),
SpecialPoint(0.0, 1.0, 1.0, 1),
SpecialPoint(0.0, 0.0, 0.0, 1),
SpecialPoint(0.1, 0.1, 0.1, 1),
SpecialPoint(0.2, 0.2, 0.2, 1),
SpecialPoint(0.3, 0.3, 0.3, 1),
SpecialPoint(0.4, 0.4, 0.4, 1),
SpecialPoint(0.5, 0.5, 0.5, 1),
])
input = PWInput(;
control=control,
system=system,
electrons=electrons,
atomic_species=atomic_species,
atomic_positions=atomic_positions,
k_points=k_points,
)
@test input.electrons.diagonalization == diago
# Test whether equality holds for different constructions of `PWInput`
@test input == PWInput(;
control=deepcopy(control),
system=deepcopy(system),
electrons=deepcopy(electrons),
atomic_species=deepcopy(atomic_species),
atomic_positions=deepcopy(atomic_positions),
k_points=deepcopy(k_points),
)
@test collect(eachpotential(input)) == ["Si.pz-vbc.UPF"]
if !Sys.iswindows()
@test getpseudodir(input) == joinpath(@__DIR__, "pseudo/")
@test getxmldir(input) == joinpath(@__DIR__, "silicon.save")
end
end
end
@testset "Construct a `PWInput`: aluminium" begin
# This example is from https://github.com/QEF/q-e/blob/master/PW/examples/example01/run_example.
for diago in ("david", "cg", "ppcg")
control = ControlNamelist(;
calculation="scf",
restart_mode="from_scratch",
pseudo_dir="pseudo/",
outdir="./",
prefix="al",
tprnfor=true,
tstress=true,
)
system = SystemNamelist(;
ibrav=2,
celldm=[7.50],
nat=1,
ntyp=1,
ecutwfc=15.0,
occupations="smearing",
smearing="marzari-vanderbilt",
degauss=0.05,
)
electrons = ElectronsNamelist(; diagonalization=diago, mixing_beta=0.7)
atomic_species = AtomicSpeciesCard([AtomicSpecies("Al", 26.98, "Al.pz-vbc.UPF")])
atomic_positions = AtomicPositionsCard([AtomicPosition("Al", [0.0, 0.0, 0.0])])
k_points = SpecialPointsCard([
SpecialPoint(0.0625, 0.0625, 0.0625, 1),
SpecialPoint(0.0625, 0.0625, 0.1875, 3),
SpecialPoint(0.0625, 0.0625, 0.3125, 3),
SpecialPoint(0.0625, 0.0625, 0.4375, 3),
SpecialPoint(0.0625, 0.0625, 0.5625, 3),
SpecialPoint(0.0625, 0.0625, 0.6875, 3),
SpecialPoint(0.0625, 0.0625, 0.8125, 3),
SpecialPoint(0.0625, 0.0625, 0.9375, 3),
SpecialPoint(0.0625, 0.1875, 0.1875, 3),
SpecialPoint(0.0625, 0.1875, 0.3125, 6),
SpecialPoint(0.0625, 0.1875, 0.4375, 6),
SpecialPoint(0.0625, 0.1875, 0.5625, 6),
SpecialPoint(0.0625, 0.1875, 0.6875, 6),
SpecialPoint(0.0625, 0.1875, 0.8125, 6),
SpecialPoint(0.0625, 0.1875, 0.9375, 6),
SpecialPoint(0.0625, 0.3125, 0.3125, 3),
SpecialPoint(0.0625, 0.3125, 0.4375, 6),
SpecialPoint(0.0625, 0.3125, 0.5625, 6),
SpecialPoint(0.0625, 0.3125, 0.6875, 6),
SpecialPoint(0.0625, 0.3125, 0.8125, 6),
SpecialPoint(0.0625, 0.3125, 0.9375, 6),
SpecialPoint(0.0625, 0.4375, 0.4375, 3),
SpecialPoint(0.0625, 0.4375, 0.5625, 6),
SpecialPoint(0.0625, 0.4375, 0.6875, 6),
SpecialPoint(0.0625, 0.4375, 0.8125, 6),
SpecialPoint(0.0625, 0.4375, 0.9375, 6),
SpecialPoint(0.0625, 0.5625, 0.5625, 3),
SpecialPoint(0.0625, 0.5625, 0.6875, 6),
SpecialPoint(0.0625, 0.5625, 0.8125, 6),
SpecialPoint(0.0625, 0.6875, 0.6875, 3),
SpecialPoint(0.0625, 0.6875, 0.8125, 6),
SpecialPoint(0.0625, 0.8125, 0.8125, 3),
SpecialPoint(0.1875, 0.1875, 0.1875, 1),
SpecialPoint(0.1875, 0.1875, 0.3125, 3),
SpecialPoint(0.1875, 0.1875, 0.4375, 3),
SpecialPoint(0.1875, 0.1875, 0.5625, 3),
SpecialPoint(0.1875, 0.1875, 0.6875, 3),
SpecialPoint(0.1875, 0.1875, 0.8125, 3),
SpecialPoint(0.1875, 0.3125, 0.3125, 3),
SpecialPoint(0.1875, 0.3125, 0.4375, 6),
SpecialPoint(0.1875, 0.3125, 0.5625, 6),
SpecialPoint(0.1875, 0.3125, 0.6875, 6),
SpecialPoint(0.1875, 0.3125, 0.8125, 6),
SpecialPoint(0.1875, 0.4375, 0.4375, 3),
SpecialPoint(0.1875, 0.4375, 0.5625, 6),
SpecialPoint(0.1875, 0.4375, 0.6875, 6),
SpecialPoint(0.1875, 0.4375, 0.8125, 6),
SpecialPoint(0.1875, 0.5625, 0.5625, 3),
SpecialPoint(0.1875, 0.5625, 0.6875, 6),
SpecialPoint(0.1875, 0.6875, 0.6875, 3),
SpecialPoint(0.3125, 0.3125, 0.3125, 1),
SpecialPoint(0.3125, 0.3125, 0.4375, 3),
SpecialPoint(0.3125, 0.3125, 0.5625, 3),
SpecialPoint(0.3125, 0.3125, 0.6875, 3),
SpecialPoint(0.3125, 0.4375, 0.4375, 3),
SpecialPoint(0.3125, 0.4375, 0.5625, 6),
SpecialPoint(0.3125, 0.4375, 0.6875, 6),
SpecialPoint(0.3125, 0.5625, 0.5625, 3),
SpecialPoint(0.4375, 0.4375, 0.4375, 1),
SpecialPoint(0.4375, 0.4375, 0.5625, 3),
])
input = PWInput(;
control=control,
system=system,
electrons=electrons,
atomic_species=atomic_species,
atomic_positions=atomic_positions,
k_points=k_points,
)
@test input.electrons.diagonalization == diago
@test input == PWInput(;
control=deepcopy(control),
system=deepcopy(system),
electrons=deepcopy(electrons),
atomic_species=deepcopy(atomic_species),
atomic_positions=deepcopy(atomic_positions),
k_points=deepcopy(k_points),
)
@test input.k_points == SpecialPointsCard([
SpecialPoint([0.0625, 0.0625, 0.0625], 1.0),
SpecialPoint([0.0625, 0.0625, 0.1875], 3.0),
SpecialPoint([0.0625, 0.0625, 0.3125], 3.0),
SpecialPoint([0.0625, 0.0625, 0.4375], 3.0),
SpecialPoint([0.0625, 0.0625, 0.5625], 3.0),
SpecialPoint([0.0625, 0.0625, 0.6875], 3.0),
SpecialPoint([0.0625, 0.0625, 0.8125], 3.0),
SpecialPoint([0.0625, 0.0625, 0.9375], 3.0),
SpecialPoint([0.0625, 0.1875, 0.1875], 3.0),
SpecialPoint([0.0625, 0.1875, 0.3125], 6.0),
SpecialPoint([0.0625, 0.1875, 0.4375], 6.0),
SpecialPoint([0.0625, 0.1875, 0.5625], 6.0),
SpecialPoint([0.0625, 0.1875, 0.6875], 6.0),
SpecialPoint([0.0625, 0.1875, 0.8125], 6.0),
SpecialPoint([0.0625, 0.1875, 0.9375], 6.0),
SpecialPoint([0.0625, 0.3125, 0.3125], 3.0),
SpecialPoint([0.0625, 0.3125, 0.4375], 6.0),
SpecialPoint([0.0625, 0.3125, 0.5625], 6.0),
SpecialPoint([0.0625, 0.3125, 0.6875], 6.0),
SpecialPoint([0.0625, 0.3125, 0.8125], 6.0),
SpecialPoint([0.0625, 0.3125, 0.9375], 6.0),
SpecialPoint([0.0625, 0.4375, 0.4375], 3.0),
SpecialPoint([0.0625, 0.4375, 0.5625], 6.0),
SpecialPoint([0.0625, 0.4375, 0.6875], 6.0),
SpecialPoint([0.0625, 0.4375, 0.8125], 6.0),
SpecialPoint([0.0625, 0.4375, 0.9375], 6.0),
SpecialPoint([0.0625, 0.5625, 0.5625], 3.0),
SpecialPoint([0.0625, 0.5625, 0.6875], 6.0),
SpecialPoint([0.0625, 0.5625, 0.8125], 6.0),
SpecialPoint([0.0625, 0.6875, 0.6875], 3.0),
SpecialPoint([0.0625, 0.6875, 0.8125], 6.0),
SpecialPoint([0.0625, 0.8125, 0.8125], 3.0),
SpecialPoint([0.1875, 0.1875, 0.1875], 1.0),
SpecialPoint([0.1875, 0.1875, 0.3125], 3.0),
SpecialPoint([0.1875, 0.1875, 0.4375], 3.0),
SpecialPoint([0.1875, 0.1875, 0.5625], 3.0),
SpecialPoint([0.1875, 0.1875, 0.6875], 3.0),
SpecialPoint([0.1875, 0.1875, 0.8125], 3.0),
SpecialPoint([0.1875, 0.3125, 0.3125], 3.0),
SpecialPoint([0.1875, 0.3125, 0.4375], 6.0),
SpecialPoint([0.1875, 0.3125, 0.5625], 6.0),
SpecialPoint([0.1875, 0.3125, 0.6875], 6.0),
SpecialPoint([0.1875, 0.3125, 0.8125], 6.0),
SpecialPoint([0.1875, 0.4375, 0.4375], 3.0),
SpecialPoint([0.1875, 0.4375, 0.5625], 6.0),
SpecialPoint([0.1875, 0.4375, 0.6875], 6.0),
SpecialPoint([0.1875, 0.4375, 0.8125], 6.0),
SpecialPoint([0.1875, 0.5625, 0.5625], 3.0),
SpecialPoint([0.1875, 0.5625, 0.6875], 6.0),
SpecialPoint([0.1875, 0.6875, 0.6875], 3.0),
SpecialPoint([0.3125, 0.3125, 0.3125], 1.0),
SpecialPoint([0.3125, 0.3125, 0.4375], 3.0),
SpecialPoint([0.3125, 0.3125, 0.5625], 3.0),
SpecialPoint([0.3125, 0.3125, 0.6875], 3.0),
SpecialPoint([0.3125, 0.4375, 0.4375], 3.0),
SpecialPoint([0.3125, 0.4375, 0.5625], 6.0),
SpecialPoint([0.3125, 0.4375, 0.6875], 6.0),
SpecialPoint([0.3125, 0.5625, 0.5625], 3.0),
SpecialPoint([0.4375, 0.4375, 0.4375], 1.0),
SpecialPoint([0.4375, 0.4375, 0.5625], 3.0),
])
@test collect(eachpotential(input)) == ["Al.pz-vbc.UPF"]
if !Sys.iswindows()
@test getpseudodir(input) == joinpath(@__DIR__, "pseudo/")
@test getxmldir(input) == joinpath(@__DIR__, "al.save")
end
end
end
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 176 | using QuantumESPRESSOBase
using Test
@testset "QuantumESPRESSOBase.jl" begin
include("PWscf.jl")
include("PHonon.jl")
include("set.jl")
# include("CP.jl")
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | code | 1824 | module Setters
using Test: @testset, @test
using Unitful
using UnitfulAtomic
using QuantumESPRESSOBase.PWscf:
ControlNamelist, SystemNamelist, VerbositySetter, ElectronicTemperatureSetter
@testset "Apply `VerbositySetter` on `ControlNamelist`" begin
control = ControlNamelist()
@test ( # Default values
control.verbosity,
control.wf_collect,
control.tstress,
control.tprnfor,
control.disk_io,
) == ("low", true, false, false, "low")
@testset "Set verbosity to 'high'" begin
result = VerbositySetter("high")(control)
@test (
result.verbosity,
result.wf_collect,
result.tstress,
result.tprnfor,
result.disk_io,
) == ("high", true, true, true, "high")
end
@testset "Set verbosity to 'low'" begin
result = VerbositySetter("low")(control)
@test (
result.verbosity,
result.wf_collect,
result.tstress,
result.tprnfor,
result.disk_io,
) == ("low", false, false, false, "low")
end
end
@testset "Apply `ElectronicTemperatureSetter` on `SystemNamelist`" begin
system = SystemNamelist()
@test (system.occupations, system.degauss, system.smearing) ==
("fixed", 0.0, "gaussian")
for value in (
0.0019000869380733452,
300u"K",
3e8u"μK",
2.5851999786e-8u"MeV",
0.00095004346903668u"hartree",
6.250985736u"THz",
20851.044012u"m^-1",
208.51044012u"cm^-1",
4.141947e-24u"kJ",
)
result = ElectronicTemperatureSetter(value)(system)
@test result.occupations == "smearing"
@test result.smearing == "fermi-dirac"
@test result.degauss ≈ 0.0019000869380733452
end
end
end
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 5961 | <div align="center">
<img src="https://raw.githubusercontent.com/MineralsCloud/QuantumESPRESSOBase.jl/master/docs/src/assets/logo.png" height="200"><br>
</div>
# QuantumESPRESSOBase
| **Documentation** | **Build Status** | **Others** |
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------: |
| [![Stable][docs-stable-img]][docs-stable-url] [![Dev][docs-dev-img]][docs-dev-url] | [![Build Status][gha-img]][gha-url] [![Build Status][appveyor-img]][appveyor-url] [![Build Status][cirrus-img]][cirrus-url] [![pipeline status][gitlab-img]][gitlab-url] [![Coverage][codecov-img]][codecov-url] | [![GitHub license][license-img]][license-url] [![Code Style: Blue][style-img]][style-url] [![QuantumESPRESSOBase Downloads][downloads-img]][downloads-url] |
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://singularitti.github.io/Spglib.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg
[docs-dev-url]: https://singularitti.github.io/Spglib.jl/dev
[gha-img]: https://github.com/singularitti/Spglib.jl/workflows/CI/badge.svg
[gha-url]: https://github.com/singularitti/Spglib.jl/actions
[appveyor-img]: https://ci.appveyor.com/api/projects/status/github/singularitti/Spglib.jl?svg=true
[appveyor-url]: https://ci.appveyor.com/project/singularitti/Spglib-jl
[cirrus-img]: https://api.cirrus-ci.com/github/singularitti/Spglib.jl.svg
[cirrus-url]: https://cirrus-ci.com/github/singularitti/Spglib.jl
[gitlab-img]: https://gitlab.com/singularitti/Spglib.jl/badges/main/pipeline.svg
[gitlab-url]: https://gitlab.com/singularitti/Spglib.jl/-/pipelines
[codecov-img]: https://codecov.io/gh/singularitti/Spglib.jl/branch/main/graph/badge.svg
[codecov-url]: https://codecov.io/gh/singularitti/Spglib.jl
[license-img]: https://img.shields.io/github/license/singularitti/Spglib.jl
[license-url]: https://github.com/singularitti/Spglib.jl/blob/main/LICENSE
[style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg
[style-url]: https://github.com/invenia/BlueStyle
[downloads-img]: https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/QuantumESPRESSOBase
[downloads-url]: https://pkgs.genieframework.com?packages=QuantumESPRESSOBase
[QuantumESPRESSOBase.jl](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl) declares
basic data types and methods for manipulating crystal structures, generating input files for
[Quantum ESPRESSO](https://www.quantum-espresso.org/), error checking before running, etc.
It is written purely in the language [Julia](https://julialang.org/).
Please [cite this package](https://doi.org/10.1016/j.cpc.2022.108515) as:
Q. Zhang, C. Gu, J. Zhuang et al., `express`: extensible, high-level workflows for swifter *ab initio* materials modeling, *Computer Physics Communications*, 108515, doi: https://doi.org/10.1016/j.cpc.2022.108515.
The BibTeX format is:
```bibtex
@article{ZHANG2022108515,
title = {express: extensible, high-level workflows for swifter ab initio materials modeling},
journal = {Computer Physics Communications},
pages = {108515},
year = {2022},
issn = {0010-4655},
doi = {https://doi.org/10.1016/j.cpc.2022.108515},
url = {https://www.sciencedirect.com/science/article/pii/S001046552200234X},
author = {Qi Zhang and Chaoxuan Gu and Jingyi Zhuang and Renata M. Wentzcovitch},
keywords = {automation, workflow, high-level, high-throughput, data lineage}
}
```
We also have an [arXiv prepint](https://arxiv.org/abs/2109.11724).
The code is [hosted on GitHub](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl),
with some continuous integration services to test its validity.
This repository is created and maintained by [@singularitti](https://github.com/singularitti).
You are very welcome to contribute.
## Installation
The package can be installed with the Julia package manager.
From the Julia REPL, type `]` to enter the Pkg REPL mode and run:
```
pkg> add QuantumESPRESSOBase
```
Or, equivalently, via the [`Pkg` API](https://pkgdocs.julialang.org/v1/getting-started/):
```julia
julia> import Pkg; Pkg.add("QuantumESPRESSOBase")
```
## Documentation
- [**STABLE**][docs-stable-url] — **documentation of the most recently tagged version.**
- [**DEV**][docs-dev-url] — _documentation of the in-development version._
## Project status
The package is tested against, and being developed for, Julia `1.6` and above on Linux,
macOS, and Windows.
## Questions and contributions
You are welcome to post usage questions on [our discussion page][discussions-url].
Contributions are very welcome, as are feature requests and suggestions. Please open an
[issue][issues-url] if you encounter any problems. The [Contributing](@ref) page has
guidelines that should be followed when opening pull requests and contributing code.
[discussions-url]: https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/discussions
[issues-url]: https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/issues
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=MineralsCloud/QuantumESPRESSOBase.jl&type=Date)](https://star-history.com/#MineralsCloud/QuantumESPRESSOBase.jl&Date)
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 631 | * **Please check if the PR fulfills these requirements**
- [ ] The commit message follows our guidelines
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)
* **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...)
* **What is the current behavior?** (You can also link to an open issue here)
* **What is the new behavior (if this is a feature change)?**
* **Does this PR introduce a breaking change?** (What changes might users need to make in their application due to this PR?)
* **Other information**:
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 748 | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: singularitti
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
5. Run code
```julia
using Pkg
```
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, paste screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. macOS 12.5.1]
- Julia version: [e.g. 1.6.7, 1.7.3]
- Package version: [e.g. 2.0.0]
**Additional context**
Add any other context about the problem here.
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 624 | ---
name: Feature request
about: Suggest an idea for this project
title: 'Request feature: '
labels: ''
assignees: 'singularitti'
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 3473 | ```@meta
CurrentModule = QuantumESPRESSOBase
```
# QuantumESPRESSOBase
Documentation for [QuantumESPRESSOBase](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl).
[QuantumESPRESSOBase.jl](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl) declares
basic data types and methods for manipulating crystal structures, generating input files for
[Quantum ESPRESSO](https://www.quantum-espresso.org/), error checking before running, etc.
It is written purely in the language [Julia](https://julialang.org/).
Please [cite this package](https://doi.org/10.1016/j.cpc.2022.108515) as:
Q. Zhang, C. Gu, J. Zhuang et al., `express`: extensible, high-level workflows for swifter *ab initio* materials modeling, *Computer Physics Communications*, 108515, doi: https://doi.org/10.1016/j.cpc.2022.108515.
The BibTeX format is:
```bibtex
@article{ZHANG2022108515,
title = {express: extensible, high-level workflows for swifter ab initio materials modeling},
journal = {Computer Physics Communications},
pages = {108515},
year = {2022},
issn = {0010-4655},
doi = {https://doi.org/10.1016/j.cpc.2022.108515},
url = {https://www.sciencedirect.com/science/article/pii/S001046552200234X},
author = {Qi Zhang and Chaoxuan Gu and Jingyi Zhuang and Renata M. Wentzcovitch},
keywords = {automation, workflow, high-level, high-throughput, data lineage}
}
```
We also have an [arXiv prepint](https://arxiv.org/abs/2109.11724).
See the [Index](@ref main-index) for the complete list of documented functions
and types.
The code is [hosted on GitHub](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl),
with some continuous integration services to test its validity.
This repository is created and maintained by [@singularitti](https://github.com/singularitti).
You are very welcome to contribute.
## Installation
The package can be installed with the Julia package manager.
From the Julia REPL, type `]` to enter the Pkg REPL mode and run:
```julia
pkg> add QuantumESPRESSOBase
```
Or, equivalently, via the `Pkg` API:
```@repl
import Pkg; Pkg.add("QuantumESPRESSOBase")
```
## Documentation
- [**STABLE**](https://MineralsCloud.github.io/QuantumESPRESSOBase.jl/stable) — **documentation of the most recently tagged version.**
- [**DEV**](https://MineralsCloud.github.io/QuantumESPRESSOBase.jl/dev) — _documentation of the in-development version._
## Project status
The package is tested against, and being developed for, Julia `1.6` and above on Linux,
macOS, and Windows.
## Questions and contributions
Usage questions can be posted on
[our discussion page](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/discussions).
Contributions are very welcome, as are feature requests and suggestions. Please open an
[issue](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/issues)
if you encounter any problems. The [Contributing](@ref) page has
a few guidelines that should be followed when opening pull requests and contributing code.
## Manual outline
```@contents
Pages = [
"installation.md",
"developers/contributing.md",
"developers/style-guide.md",
"developers/design-principles.md",
"troubleshooting.md",
]
Depth = 3
```
## Library outline
```@contents
Pages = [
"api/QuantumESPRESSOBase.md",
"api/PWscf.md",
"api/PHonon.md",
]
```
### [Index](@id main-index)
```@index
Pages = [
"api/QuantumESPRESSOBase.md",
"api/PWscf.md",
"api/PHonon.md",
]
```
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 5353 | # [Installation Guide](@id installation)
```@contents
Pages = ["installation.md"]
Depth = 2
```
Here are the installation instructions for package
[QuantumESPRESSOBase](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl).
If you have trouble installing it, please refer to our [Troubleshooting](@ref) page
for more information.
## Install Julia
First, you should install [Julia](https://julialang.org/). We recommend downloading it from
[its official website](https://julialang.org/downloads/). Please follow the detailed
instructions on its website if you have to
[build Julia from source](https://docs.julialang.org/en/v1/devdocs/build/build/).
Some computing centers provide preinstalled Julia. Please contact your administrator for
more information in that case.
Here's some additional information on
[how to set up Julia on HPC systems](https://github.com/hlrs-tasc/julia-on-hpc-systems).
If you have [Homebrew](https://brew.sh) installed,
[open `Terminal.app`](https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac)
and type
```bash
brew install julia
```
to install it as a [formula](https://docs.brew.sh/Formula-Cookbook).
If you are also using macOS and want to install it as a prebuilt binary app, type
```bash
brew install --cask julia
```
instead.
If you want to install multiple Julia versions in the same operating system,
a recommended way is to use a version manager such as
[`juliaup`](https://github.com/JuliaLang/juliaup).
First, [install `juliaup`](https://github.com/JuliaLang/juliaup#installation).
Then, run
```bash
juliaup add release
juliaup default release
```
to configure the `julia` command to start the latest stable version of
Julia (this is also the default value).
There is a [short video introduction to `juliaup`](https://youtu.be/14zfdbzq5BM)
made by its authors.
### Which version should I pick?
You can install the "Current stable release" or the "Long-term support (LTS)
release".
- The "Current stable release" is the latest release of Julia. It has access to
newer features, and is likely faster.
- The "Long-term support release" is an older version of Julia that has
continued to receive bug and security fixes. However, it may not have the
latest features or performance improvements.
For most users, you should install the "Current stable release", and whenever
Julia releases a new version of the current stable release, you should update
your version of Julia. Note that any code you write on one version of the
current stable release will continue to work on all subsequent releases.
For users in restricted software environments (e.g., your enterprise IT controls
what software you can install), you may be better off installing the long-term
support release because you will not have to update Julia as frequently.
Versions higher than `v1.3`,
especially `v1.6`, are strongly recommended. This package may not work on `v1.0` and below.
Since the Julia team has set `v1.6` as the LTS release,
we will gradually drop support for versions below `v1.6`.
Julia and Julia packages support multiple operating systems and CPU architectures; check
[this table](https://julialang.org/downloads/#supported_platforms) to see if it can be
installed on your machine. For Mac computers with M-series processors, this package and its
dependencies may not work. Please install the Intel-compatible version of Julia (for macOS
x86-64) if any platform-related error occurs.
## Install QuantumESPRESSOBase
Now I am using [macOS](https://en.wikipedia.org/wiki/MacOS) as a standard
platform to explain the following steps:
1. Open `Terminal.app`, and type `julia` to start an interactive session (known as the
[REPL](https://docs.julialang.org/en/v1/stdlib/REPL/)).
2. Run the following commands and wait for them to finish:
```julia-repl
julia> using Pkg
julia> Pkg.update()
julia> Pkg.add("QuantumESPRESSOBase")
```
3. Run
```julia-repl
julia> using QuantumESPRESSOBase
```
and have fun!
4. While using, please keep this Julia session alive. Restarting might cost some time.
If you want to install the latest in-development (probably buggy)
version of QuantumESPRESSOBase, type
```@repl
using Pkg
Pkg.update()
pkg"add https://github.com/MineralsCloud/QuantumESPRESSOBase.jl"
```
in the second step above.
## Update QuantumESPRESSOBase
Please [watch](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)
our [GitHub repository](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl)
for new releases.
Once we release a new version, you can update QuantumESPRESSOBase by typing
```@repl
using Pkg
Pkg.update("QuantumESPRESSOBase")
Pkg.gc()
```
in the Julia REPL.
## Uninstall and reinstall QuantumESPRESSOBase
Sometimes errors may occur if the package is not properly installed.
In this case, you may want to uninstall and reinstall the package. Here is how to do that:
1. To uninstall, in a Julia session, run
```julia-repl
julia> using Pkg
julia> Pkg.rm("QuantumESPRESSOBase")
julia> Pkg.gc()
```
2. Press `ctrl+d` to quit the current session. Start a new Julia session and
reinstall QuantumESPRESSOBase.
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 2169 | # Troubleshooting
```@contents
Pages = ["troubleshooting.md"]
Depth = 2
```
This page collects some possible errors you may encounter and trick how to fix them.
If you have some questions about how to use this code, you are welcome to
[discuss with us](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/discussions).
If you have additional tips, please either
[report an issue](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/issues/new) or
[submit a PR](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/compare) with suggestions.
## Installation problems
### Cannot find the `julia` executable
Make sure you have Julia installed in your environment. Please download the latest
[stable version](https://julialang.org/downloads/#current_stable_release) for your platform.
If you are using a *nix system, the recommended way is to use
[Juliaup](https://github.com/JuliaLang/juliaup). If you do not want to install Juliaup
or you are using other platforms that Julia supports, download the corresponding binaries.
Then, create a symbolic link to the Julia executable. If the path is not in your `$PATH`
environment variable, export it to your `$PATH`.
Some clusters, like
[Habanero](https://confluence.columbia.edu/confluence/display/rcs/Habanero+HPC+Cluster+User+Documentation),
[Comet](https://www.sdsc.edu/support/user_guides/comet.html),
or [Expanse](https://www.sdsc.edu/services/hpc/expanse/index.html),
already have Julia installed as a module, you may
just `module load julia` to use it. If not, either install by yourself or contact your
administrator.
## Loading QuantumESPRESSOBase
### Julia compiles/loads slow
First, we recommend you download the latest version of Julia. Usually, the newest version
has the best performance.
If you just want Julia to do a simple task and only once, you could start the Julia REPL with
```bash
julia --compile=min
```
to minimize compilation or
```bash
julia --optimize=0
```
to minimize optimizations, or just use both. Or you could make a system image
and run with
```bash
julia --sysimage custom-image.so
```
See [Fredrik Ekre's talk](https://youtu.be/IuwxE3m0_QQ?t=313) for details.
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 258 | ```@meta
CurrentModule = QuantumESPRESSOBase.PHonon
```
# `QuantumESPRESSOBase.PHonon` module
```@contents
Pages = ["PHonon.md"]
Depth = 3
```
## Types
```@docs
PhNamelist
Q2rNamelist
MatdynNamelist
DynmatNamelist
```
## Methods
```@docs
relayinfo
```
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 535 | ```@meta
CurrentModule = QuantumESPRESSOBase.PWscf
```
# `QuantumESPRESSOBase.PWscf` module
```@contents
Pages = ["PWscf.md"]
Depth = 3
```
## Types
```@docs
Lattice
ControlNamelist
SystemNamelist
ElectronsNamelist
IonsNamelist
CellNamelist
DosNamelist
BandsNamelist
AtomicSpecies
AtomicSpeciesCard
AtomicPosition
AtomicPositionsCard
CellParametersCard
KMeshCard
GammaPointCard
SpecialPointsCard
PWInput
```
## Methods
```@docs
isrequired
isoptional
cellvolume
convertoption
getpseudodir
eachpotential
getxmldir
listwfcfiles
```
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 186 | # `QuantumESPRESSOBase` module
```@contents
Pages = ["QuantumESPRESSOBase.md"]
Depth = 3
```
## Types
```@docs
QuantumESPRESSOInput
```
## Methods
```@docs
getoption
optionpool
```
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 8930 | # Contributing
```@contents
Pages = ["contributing.md"]
Depth = 2
```
Welcome! This document explains some ways you can contribute to QuantumESPRESSOBase.
## Code of conduct
This project and everyone participating in it is governed by the
[Contributor Covenant Code of Conduct](https://github.com/MineralsCloud/.github/blob/main/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code.
## Join the community forum
First up, join the [community forum](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/discussions).
The forum is a good place to ask questions about how to use QuantumESPRESSOBase. You can also
use the forum to discuss possible feature requests and bugs before raising a
GitHub issue (more on this below).
Aside from asking questions, the easiest way you can contribute to QuantumESPRESSOBase is to
help answer questions on the forum!
## Improve the documentation
Chances are, if you asked (or answered) a question on the community forum, then
it is a sign that the [documentation](https://MineralsCloud.github.io/QuantumESPRESSOBase.jl/dev/) could be
improved. Moreover, since it is your question, you are probably the best-placed
person to improve it!
The docs are written in Markdown and are built using
[Documenter.jl](https://github.com/JuliaDocs/Documenter.jl).
You can find the source of all the docs
[here](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/tree/main/docs).
If your change is small (like fixing typos or one or two sentence corrections),
the easiest way to do this is via GitHub's online editor. (GitHub has
[help](https://help.github.com/articles/editing-files-in-another-user-s-repository/)
on how to do this.)
If your change is larger or touches multiple files, you will need to make the
change locally and then use Git to submit a
[pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests).
(See [Contribute code to QuantumESPRESSOBase](@ref) below for more on this.)
## File a bug report
Another way to contribute to QuantumESPRESSOBase is to file
[bug reports](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/issues/new?template=bug_report.md).
Make sure you read the info in the box where you write the body of the issue
before posting. You can also find a copy of that info
[here](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/blob/main/.github/ISSUE_TEMPLATE/bug_report.md).
!!! tip
If you're unsure whether you have a real bug, post on the
[community forum](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/discussions)
first. Someone will either help you fix the problem or let you know the
most appropriate place to open a bug report.
## Contribute code to QuantumESPRESSOBase
Finally, you can also contribute code to QuantumESPRESSOBase!
!!! warning
If you do not have experience with Git, GitHub, and Julia development, the
first steps can be a little daunting. However, there are lots of tutorials
available online, including:
- [GitHub](https://guides.github.com/activities/hello-world/)
- [Git and GitHub](https://try.github.io/)
- [Git](https://git-scm.com/book/en/v2)
- [Julia package development](https://docs.julialang.org/en/v1/stdlib/Pkg/#Developing-packages-1)
Once you are familiar with Git and GitHub, the workflow for contributing code to
QuantumESPRESSOBase is similar to the following:
### Step 1: decide what to work on
The first step is to find an [open issue](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/issues)
(or open a new one) for the problem you want to solve. Then, _before_ spending
too much time on it, discuss what you are planning to do in the issue to see if
other contributors are fine with your proposed changes. Getting feedback early can
improve code quality and avoid time spent writing code that does not get merged into
QuantumESPRESSOBase.
!!! tip
At this point, remember to be patient and polite; you may get a _lot_ of
comments on your issue! However, do not be afraid! Comments mean that people are
willing to help you improve the code that you are contributing to QuantumESPRESSOBase.
### Step 2: fork QuantumESPRESSOBase
Go to [https://github.com/MineralsCloud/QuantumESPRESSOBase.jl](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl)
and click the "Fork" button in the top-right corner. This will create a copy of
QuantumESPRESSOBase under your GitHub account.
### Step 3: install QuantumESPRESSOBase locally
Similar to [Installation](@ref), open the Julia REPL and run:
```@repl
using Pkg
Pkg.update()
Pkg.develop("QuantumESPRESSOBase")
```
Then the package will be cloned to your local machine. On *nix systems, the default path is
`~/.julia/dev/QuantumESPRESSOBase` unless you modify the
[`JULIA_DEPOT_PATH`](http://docs.julialang.org/en/v1/manual/environment-variables/#JULIA_DEPOT_PATH-1)
environment variable. If you're on
Windows, this will be `C:\\Users\\<my_name>\\.julia\\dev\\QuantumESPRESSOBase`.
In the following text, we will call it `PKGROOT`.
Go to `PKGROOT`, start a new Julia session, and run
```@repl
using Pkg
Pkg.instantiate()
```
to instantiate the project.
### Step 4: checkout a new branch
!!! note
In the following, replace any instance of `GITHUB_ACCOUNT` with your GitHub
username.
The next step is to check out a development branch. In a terminal (or command
prompt on Windows), run:
```bash
cd ~/.julia/dev/QuantumESPRESSOBase
git remote add GITHUB_ACCOUNT https://github.com/GITHUB_ACCOUNT/QuantumESPRESSOBase.jl.git
git checkout main
git pull
git checkout -b my_new_branch
```
### Step 5: make changes
Now make any changes to the source code inside the `~/.julia/dev/QuantumESPRESSOBase`
directory.
Make sure you:
- Follow our [Style Guide](@ref style) and [Run JuliaFormatter](@ref).
- Add tests and documentation for any changes or new features.
!!! tip
When you change the source code, you'll need to restart Julia for the
changes to take effect. This is a pain, so install
[Revise.jl](https://github.com/timholy/Revise.jl).
### Step 6a: test your code changes
To test that your changes work, run the QuantumESPRESSOBase test-suite by opening Julia and
running:
```julia-repl
julia> cd(joinpath(DEPOT_PATH[1], "dev", "QuantumESPRESSOBase"))
julia> using Pkg
julia> Pkg.activate(".")
Activating new project at `~/.julia/dev/QuantumESPRESSOBase`
julia> Pkg.test()
```
!!! warning
Running the tests might take a long time.
!!! tip
If you are using Revise.jl, you can also run the tests by calling `include`:
```julia-repl
include("test/runtests.jl")
```
This can be faster if you want to re-run the tests multiple times.
### Step 6b: test your documentation changes
Open Julia, then run:
```julia-repl
julia> cd(joinpath(DEPOT_PATH[1], "dev", "QuantumESPRESSOBase", "docs"))
julia> using Pkg
julia> Pkg.activate(".")
Activating new project at `~/.julia/dev/QuantumESPRESSOBase/docs`
julia> include("src/make.jl")
```
After a while, a folder `PKGROOT/docs/build` will appear. Open
`PKGROOT/docs/build/index.html` with your favorite browser, and have fun!
!!! warning
Building the documentation might take a long time.
!!! tip
If there's a problem with the tests that you don't know how to fix, don't
worry. Continue to step 5, and one of the QuantumESPRESSOBase contributors will comment
on your pull request, telling you how to fix things.
### Step 7: make a pull request
Once you've made changes, you're ready to push the changes to GitHub. Run:
```bash
cd ~/.julia/dev/QuantumESPRESSOBase
git add .
git commit -m "A descriptive message of the changes"
git push -u GITHUB_ACCOUNT my_new_branch
```
Then go to [https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/pulls](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/pulls)
and follow the instructions that pop up to open a pull request.
### Step 8: respond to comments
At this point, remember to be patient and polite; you may get a _lot_ of
comments on your pull request! However, do not be afraid! A lot of comments
means that people are willing to help you improve the code that you are
contributing to QuantumESPRESSOBase.
To respond to the comments, go back to step 5, make any changes, test the
changes in step 6, and then make a new commit in step 7. Your PR will
automatically update.
### Step 9: cleaning up
Once the PR is merged, clean-up your Git repository, ready for the
next contribution!
```bash
cd ~/.julia/dev/QuantumESPRESSOBase
git checkout main
git pull
```
!!! note
If you have suggestions to improve this guide, please make a pull request!
It's particularly helpful if you do this after your first pull request
because you'll know all the parts that could be explained better.
Thanks for contributing to QuantumESPRESSOBase!
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 15260 | # Design Principles
```@contents
Pages = ["design-principles.md"]
Depth = 2
```
We adopt some [`SciML`](https://sciml.ai/) design [guidelines](https://github.com/SciML/SciMLStyle)
here. Please read it before contributing!
## Consistency vs adherence
According to PEP8:
> A style guide is about consistency. Consistency with this style guide is important.
> Consistency within a project is more important. Consistency within one module or function is the most important.
>
> However, know when to be inconsistent—sometimes style guide recommendations just aren't
> applicable. When in doubt, use your best judgment. Look at other examples and decide what
> looks best. And don’t hesitate to ask!
## Community contribution guidelines
For a comprehensive set of community contribution guidelines, refer to [ColPrac](https://github.com/SciML/ColPrac).
A relevant point to highlight PRs should do one thing. In the context of style, this means that PRs which update
the style of a package's code should not be mixed with fundamental code contributions. This separation makes it
easier to ensure that large style improvement are isolated from substantive (and potentially breaking) code changes.
## Open source contributions are allowed to start small and grow over time
If the standard for code contributions is that every PR needs to support every possible input type that anyone can
think of, the barrier would be too high for newcomers. Instead, the principle is to be as correct as possible to
begin with, and grow the generic support over time. All recommended functionality should be tested, any known
generality issues should be documented in an issue (and with a `@test_broken` test when possible).
## Generic code is preferred unless code is known to be specific
For example, the code:
```@repl
function f(A, B)
for i in 1:length(A)
A[i] = A[i] + B[i]
end
end
```
would not be preferred for two reasons. One is that it assumes `A` uses one-based indexing, which would fail in cases
like [OffsetArrays](https://github.com/JuliaArrays/OffsetArrays.jl) and [FFTViews](https://github.com/JuliaArrays/FFTViews.jl).
Another issue is that it requires indexing, while not all array types support indexing (for example,
[CuArrays](https://github.com/JuliaGPU/CuArrays.jl)). A more generic compatible implementation of this function would be
to use broadcast, for example:
```@repl
function f(A, B)
@. A = A + B
end
```
which would allow support for a wider variety of array types.
## Internal types should match the types used by users when possible
If `f(A)` takes the input of some collections and computes an output from those collections, then it should be
expected that if the user gives `A` as an `Array`, the computation should be done via `Array`s. If `A` was a
`CuArray`, then it should be expected that the computation should be internally done using a `CuArray` (or appropriately
error if not supported). For these reasons, constructing arrays via generic methods, like `similar(A)`, is preferred when
writing `f` instead of using non-generic constructors like `Array(undef,size(A))` unless the function is documented as
being non-generic.
## Trait definition and adherence to generic interface is preferred when possible
Julia provides many interfaces, for example:
- [Iteration](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration)
- [Indexing](https://docs.julialang.org/en/v1/manual/interfaces/#Indexing)
- [Broadcast](https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting)
Those interfaces should be followed when possible. For example, when defining broadcast overloads,
one should implement a `BroadcastStyle` as suggested by the documentation instead of simply attempting
to bypass the broadcast system via `copyto!` overloads.
When interface functions are missing, these should be added to Base Julia or an interface package,
like [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl). Such traits should be
declared and used when appropriate. For example, if a line of code requires mutation, the trait
`ArrayInterface.ismutable(A)` should be checked before attempting to mutate, and informative error
messages should be written to capture the immutable case (or, an alternative code which does not
mutate should be given).
One example of this principle is demonstrated in the generation of Jacobian matrices. In many scientific
applications, one may wish to generate a Jacobian cache from the user's input `u0`. A naive way to generate
this Jacobian is `J = similar(u0,length(u0),length(u0))`. However, this will generate a Jacobian `J` such
that `J isa Matrix`.
## Macros should be limited and only be used for syntactic sugar
Macros define new syntax, and for this reason they tend to be less composable than other coding styles
and require prior familiarity to be easily understood. One principle to keep in mind is, "can the person
reading the code easily picture what code is being generated?". For example, a user of Soss.jl may not know
what code is being generated by:
```julia
@model (x, α) begin
σ ~ Exponential()
β ~ Normal()
y ~ For(x) do xj
Normal(α + β * xj, σ)
end
return y
end
```
and thus using such a macro as the interface is not preferred when possible. However, a macro like
[`@muladd`](https://github.com/SciML/MuladdMacro.jl) is trivial to picture on a code (it recursively
transforms `a*b + c` to `muladd(a,b,c)` for more
[accuracy and efficiency](https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation)), so using
such a macro for example:
```julia
julia> @macroexpand(@muladd k3 = f(t + c3 * dt, @. uprev + dt * (a031 * k1 + a032 * k2)))
:(k3 = f((muladd)(c3, dt, t), (muladd).(dt, (muladd).(a032, k2, (*).(a031, k1)), uprev)))
```
is recommended. Some macros in this category are:
- `@inbounds`
- [`@muladd`](https://github.com/SciML/MuladdMacro.jl)
- `@view`
- [`@named`](https://github.com/SciML/ModelingToolkit.jl)
- `@.`
- [`@..`](https://github.com/YingboMa/FastBroadcast.jl)
Some performance macros, like `@simd`, `@threads`, or
[`@turbo` from LoopVectorization.jl](https://github.com/JuliaSIMD/LoopVectorization.jl),
make an exception in that their generated code may be foreign to many users. However, they still are
classified as appropriate uses as they are syntactic sugar since they do (or should) not change the behavior
of the program in measurable ways other than performance.
## Errors should be caught as high as possible, and error messages should be contextualized for newcomers
Whenever possible, defensive programming should be used to check for potential errors before they are encountered
deeper within a package. For example, if one knows that `f(u0,p)` will error unless `u0` is the size of `p`, this
should be caught at the start of the function to throw a domain specific error, for example "parameters and initial
condition should be the same size".
## Subpackaging and interface packages is preferred over conditional modules via Requires.jl
Requires.jl should be avoided at all costs. If an interface package exists, such as
[ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl) for defining automatic differentiation
rules without requiring a dependency on the whole ChainRules.jl system, or
[RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl) which allows for defining Plots.jl
plot recipes without a dependency on Plots.jl, a direct dependency on these interface packages is
preferred.
Otherwise, instead of resorting to a conditional dependency using Requires.jl, it is
preferred one creates subpackages, i.e. smaller independent packages kept within the same Github repository
with independent versioning and package management. An example of this is seen in
[Optimization.jl](https://github.com/SciML/Optimization.jl) which has subpackages like
[OptimizationBBO.jl](https://github.com/SciML/Optimization.jl/tree/master/lib/OptimizationBBO) for
BlackBoxOptim.jl support.
Some important interface packages to know about are:
- [ChainRulesCore.jl](https://github.com/JuliaDiff/ChainRulesCore.jl)
- [RecipesBase.jl](https://github.com/JuliaPlots/RecipesBase.jl)
- [ArrayInterface.jl](https://github.com/JuliaArrays/ArrayInterface.jl)
- [CommonSolve.jl](https://github.com/SciML/CommonSolve.jl)
- [SciMLBase.jl](https://github.com/SciML/SciMLBase.jl)
## Functions should either attempt to be non-allocating and reuse caches, or treat inputs as immutable
Mutating codes and non-mutating codes fall into different worlds. When a code is fully immutable,
the compiler can better reason about dependencies, optimize the code, and check for correctness.
However, many times a code making the fullest use of mutation can outperform even what the best compilers
of today can generate. That said, the worst of all worlds is when code mixes mutation with non-mutating
code. Not only is this a mishmash of coding styles, it has the potential non-locality and compiler
proof issues of mutating code while not fully benefiting from the mutation.
## Out-of-place and immutability is preferred when sufficient performant
Mutation is used to get more performance by decreasing the amount of heap allocations. However,
if it's not helpful for heap allocations in a given spot, do not use mutation. Mutation is scary
and should be avoided unless it gives an immediate benefit. For example, if
matrices are sufficiently large, then `A*B` is as fast as `mul!(C,A,B)`, and thus writing
`A*B` is preferred (unless the rest of the function is being careful about being fully non-allocating,
in which case this should be `mul!` for consistency).
Similarly, when defining types, using `struct` is preferred to `mutable struct` unless mutating
the struct is a common occurrence. Even if mutating the struct is a common occurrence, see whether
using [Setfield.jl](https://github.com/jw3126/Setfield.jl) is sufficient. The compiler will optimize
the construction of immutable structs, and thus this can be more efficient if it's not too much of a
code hassle.
## Tests should attempt to cover a wide gamut of input types
Code coverage numbers are meaningless if one does not consider the input types. For example, one can
hit all the code with `Array`, but that does not test whether `CuArray` is compatible! Thus, it's
always good to think of coverage not in terms of lines of code but in terms of type coverage. A good
list of number types to think about are:
- `Float64`
- `Float32`
- `Complex`
- [`Dual`](https://github.com/JuliaDiff/ForwardDiff.jl)
- `BigFloat`
Array types to think about testing are:
- `Array`
- [`OffsetArray`](https://github.com/JuliaArrays/OffsetArrays.jl)
- [`CuArray`](https://github.com/JuliaGPU/CUDA.jl)
## When in doubt, a submodule should become a subpackage or separate package
Keep packages to one core idea. If there's something separate enough to be a submodule, could it
instead be a separate well-tested and documented package to be used by other packages? Most likely
yes.
## Globals should be avoided whenever possible
Global variables should be avoided whenever possible. When required, global variables should be
constants and have an all uppercase name separated with underscores (e.g. `MY_CONSTANT`). They should be
defined at the top of the file, immediately after imports and exports but before an `__init__` function.
If you truly want mutable global style behavior you may want to look into mutable containers.
## Type-stable and type-grounded code is preferred wherever possible
Type-stable and type-grounded code helps the compiler create not only more optimized code, but also
faster to compile code. Always keep containers well-typed, functions specializing on the appropriate
arguments, and types concrete.
## Closures should be avoided whenever possible
Closures can cause accidental type instabilities that are difficult to track down and debug; in the
long run it saves time to always program defensively and avoid writing closures in the first place,
even when a particular closure would not have been problematic. A similar argument applies to reading
code with closures; if someone is looking for type instabilities, this is faster to do when code does
not contain closures.
See examples [here](https://discourse.julialang.org/t/are-closures-should-be-avoided-whenever-possible-still-valid-in-julia-v1-9/95893/5).
Furthermore, if you want to update variables in an outer scope, do so explicitly with `Ref`s or self
defined structs.
## Numerical functionality should use the appropriate generic numerical interfaces
While you can use `A\b` to do a linear solve inside a package, that does not mean that you should.
This interface is only sufficient for performing factorizations, and so that limits the scaling
choices, the types of `A` that can be supported, etc. Instead, linear solves within packages should
use LinearSolve.jl. Similarly, nonlinear solves should use NonlinearSolve.jl. Optimization should use
Optimization.jl. Etc. This allows the full generic choice to be given to the user without depending
on every solver package (effectively recreating the generic interfaces within each package).
## Functions should capture one underlying principle
Functions mean one thing. Every dispatch of `+` should be "the meaning of addition on these types".
While in theory you could add dispatches to `+` that mean something different, that will fail in
generic code for which `+` means addition. Thus, for generic code to work, code needs to adhere to
one meaning for each function. Every dispatch should be an instantiation of that meaning.
## Internal choices should be exposed as options whenever possible
Whenever possible, numerical values and choices within scripts should be exposed as options
to the user. This promotes code reusability beyond the few cases the author may have expected.
## Prefer code reuse over rewrites whenever possible
If a package has a function you need, use the package. Add a dependency if you need to. If the
function is missing a feature, prefer to add that feature to said package and then add it as a
dependency. If the dependency is potentially troublesome, for example because it has a high
load time, prefer to spend time helping said package fix these issues and add the dependency.
Only when it does not seem possible to make the package "good enough" should using the package
be abandoned. If it is abandoned, consider building a new package for this functionality as you
need it, and then make it a dependency.
## Prefer to not shadow functions
Two functions can have the same name in Julia by having different namespaces. For example,
`X.f` and `Y.f` can be two different functions, with different dispatches, but the same name.
This should be avoided whenever possible. Instead of creating `MyPackage.sort`, consider
adding dispatches to `Base.sort` for your types if these new dispatches match the underlying
principle of the function. If it doesn't, prefer to use a different name. While using `MyPackage.sort`
is not conflicting, it is going to be confusing for most people unfamiliar with your code,
so `MyPackage.special_sort` would be more helpful to newcomers reading the code.
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.12.1 | c5abe6e98f0bf3258e3832435b0cdb33b0765e51 | docs | 2263 | # [Style Guide](@id style)
This section describes the coding style rules that apply to our code and that
we recommend you to use it also.
In some cases, our style guide diverges from Julia's official
[Style Guide](https://docs.julialang.org/en/v1/manual/style-guide/) (Please read it!).
All such cases will be explicitly noted and justified.
Our style guide adopts many recommendations from the
[BlueStyle](https://github.com/invenia/BlueStyle).
Please read the [BlueStyle](https://github.com/invenia/BlueStyle)
before contributing to this package.
If not following, your pull requests may not be accepted.
!!! info
The style guide is always a work in progress, and not all QuantumESPRESSOBase code
follows the rules. When modifying QuantumESPRESSOBase, please fix the style violations
of the surrounding code (i.e., leave the code tidier than when you
started). If large changes are needed, consider separating them into
another pull request.
## Formatting
### Run JuliaFormatter
QuantumESPRESSOBase uses [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) as
an auto-formatting tool.
We use the options contained in [`.JuliaFormatter.toml`](https://github.com/MineralsCloud/QuantumESPRESSOBase.jl/blob/main/.JuliaFormatter.toml).
To format your code, `cd` to the QuantumESPRESSOBase directory, then run:
```@repl
using Pkg
Pkg.add("JuliaFormatter")
using JuliaFormatter: format
format("docs")
format("src")
format("test")
```
!!! info
A continuous integration check verifies that all PRs made to QuantumESPRESSOBase have
passed the formatter.
The following sections outline extra style guide points that are not fixed
automatically by JuliaFormatter.
### Use the Julia extension for Visual Studio Code
Please use [Visual Studio Code](https://code.visualstudio.com/) with the
[Julia extension](https://marketplace.visualstudio.com/items?itemName=julialang.language-julia)
to edit, format, and test your code.
We do not recommend using other editors to edit your code for the time being.
This extension already has [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl)
integrated. So to format your code, follow the steps listed
[here](https://www.julia-vscode.org/docs/stable/userguide/formatter/).
| QuantumESPRESSOBase | https://github.com/MineralsCloud/QuantumESPRESSOBase.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | code | 645 | using Documenter
using Pkg
if isfile("src/OpenStreetMapXPlot.jl")
if !("." in LOAD_PATH)
push!(LOAD_PATH,".")
end
elseif isfile("../src/OpenStreetMapXPlot.jl")
if !(".." in LOAD_PATH)
push!(LOAD_PATH,"..")
end
end
using OpenStreetMapXPlot
println("Generating docs for module\n$(pathof(OpenStreetMapXPlot))")
makedocs(
sitename = "OpenStreetMapXPlot",
format = format = Documenter.HTML(),
modules = [OpenStreetMapXPlot],
pages = ["index.md", "reference.md"],
checkdocs = :exports,
doctest = true
)
deploydocs(
repo ="github.com/pszufe/OpenStreetMapXPlot.jl.git",
target="build"
)
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | code | 208 | module OpenStreetMapXPlot
using OpenStreetMapX
import Plots
export plotmap, addroute!, plot_nodes!, plot_nodes_as_symbols! #Plotting
include("plot.jl") #plotting
include("layers.jl") #colors
end #module
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | code | 3371 | ### Julia OpenStreetMapXPlot Package ###
### MIT License ###
### Standard map display "layers." ###
const LAYER_STANDARD = Dict(
1 => OpenStreetMapXPlot.Style("0xd97486", 4), # @motorway-fill
2 => OpenStreetMapXPlot.Style("0xebb36a", 3), # @primary-fill
3 => OpenStreetMapXPlot.Style("0xe8b995", 3), # @secondary-fill
4 => OpenStreetMapXPlot.Style("0xecf27c", 3), # @tertiary-fill
5 => OpenStreetMapXPlot.Style("0xb9b9b6", 2), # gray
6 => OpenStreetMapXPlot.Style("0xc7c7c4", 2), # gray
7 => OpenStreetMapXPlot.Style("0xd9d9d5", 2), # Light gray
8 => OpenStreetMapXPlot.Style("0xd9d9d5", 1)) # Light gray
const LAYER_CYCLE = Dict(
1 => OpenStreetMapXPlot.Style("0x006600", 3), # Green
2 => OpenStreetMapXPlot.Style("0x5C85FF", 3), # Blue
3 => OpenStreetMapXPlot.Style("0x5C85FF", 2), # Blue
4 => OpenStreetMapXPlot.Style("0x999999", 2)) # Dark gray
const LAYER_PED = Dict(
1 => OpenStreetMapXPlot.Style("0x999999", 3), # Dark gray
2 => OpenStreetMapXPlot.Style("0x999999", 3), # Dark gray
3 => OpenStreetMapXPlot.Style("0x999999", 2), # Dark gray
4 => OpenStreetMapXPlot.Style("0xE0E0E0", 2)) # Light gray
const LAYER_FEATURES = Dict(
1 => OpenStreetMapXPlot.Style("0x9966FF", 1.5, "."), # Lavender
2 => OpenStreetMapXPlot.Style("0xFF0000", 1.5, "."), # Red
3 => OpenStreetMapXPlot.Style("0x000000", 1.5, "."), # Black
4 => OpenStreetMapXPlot.Style("0xFF66FF", 1.5, "."), # Pink
5 => OpenStreetMapXPlot.Style("0x996633", 1.5, "."), # Brown
6 => OpenStreetMapXPlot.Style("0xFF9900", 2.0, "."), # Orange
7 => OpenStreetMapXPlot.Style("0xCC00CC", 1.5, "."), # Brown
8 => OpenStreetMapXPlot.Style("0xFFFF00", 1.5, "."), # Yellow
9 => OpenStreetMapXPlot.Style("0xF4CCCC", 1.5, "."), # Vanilla Ice
10 => OpenStreetMapXPlot.Style("0x351C75", 1.5, "."), # Persian Indigo
11 => OpenStreetMapXPlot.Style("0x00FF00", 1.5, "."), # Lime
12 => OpenStreetMapXPlot.Style("0x00FFFF", 1.5, "."), # Aqua
13 => OpenStreetMapXPlot.Style("0x005353", 2.0, "."), # Sherpa Blue
14 => OpenStreetMapXPlot.Style("0xBDAD7D", 1.5, "."), # Ecru
15 => OpenStreetMapXPlot.Style("0xFF00FF", 1.5, "."), # Fuchsia
16 => OpenStreetMapXPlot.Style("0xB9D1D6", 1.5, "."), # Light Blue
17 => OpenStreetMapXPlot.Style("0x7A00CC", 1.5, "."), # Violet
18 => OpenStreetMapXPlot.Style("0x004225", 1.5, "."), # British Racing Green
19 => OpenStreetMapXPlot.Style("0x7E8386", 2.0, "."), # Silver
20 => OpenStreetMapXPlot.Style("0xB87333", 1.5, "."), # Copper
21 => OpenStreetMapXPlot.Style("0x800020", 1.5, "."), # Burgundy
22 => OpenStreetMapXPlot.Style("0x5B718D", 1.5, "."), # Ultramarine
23 => OpenStreetMapXPlot.Style("0x636F22", 1.5, "."), # Fiji Green
24 => OpenStreetMapXPlot.Style("0xCAF4DF", 1.5, "."), # Mint
25 => OpenStreetMapXPlot.Style("0x231F66", 2.0, "."), # Midnight Blue
26 => OpenStreetMapXPlot.Style("0xE6DFE7", 1.5, ".")) # Selago
const LAYER_BUILDINGS = Dict(
1 => OpenStreetMapXPlot.Style("0xE1E1EB", 1, "-"), # Lighter gray
2 => OpenStreetMapXPlot.Style("0xB8DBFF", 1, "-"), # Light blue
3 => OpenStreetMapXPlot.Style("0xB5B5CE", 1, "-"), # Light gray
4 => OpenStreetMapXPlot.Style("0xFFFF99", 1, "-"), # Pale yellow
5 => OpenStreetMapXPlot.Style("0x006600", 1, "-")) # Green
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | code | 19792 | ###
# Functions for with Plots.jl Packages
###
"""
struct Style{T}
color::T
width::Float64
spec::String
end
For most cases you will use constructor declared as:
```julia
Style(col, width, spec="-")
```
"""
struct Style{T}
color::T
width::Float64
spec::String
end
Style(col::T, width::Int, spec) where T= Style{T}(col, Float64(width), spec)
Style(col::T, width) where T = Style{T}(col, Float64(width), "-")
const Styles{T} = Union{OpenStreetMapXPlot.Style{T},Dict{Int,OpenStreetMapXPlot.Style{T}}} where T
const gr_linestyles = Dict("-" => :solid, ":"=>:dot, ";"=>:dashdot, "-."=>:dashdot,"--"=>:dash)
"""
Compute approximate "aspect ratio" at mean latitude
"""
function aspect_ratio(bounds::OpenStreetMapX.Bounds{OpenStreetMapX.LLA})
c_adj = cosd((bounds.min_y + bounds.max_y) / 2)
range_y = bounds.max_y - bounds.min_y
range_x = bounds.max_x - bounds.min_x
return range_x * c_adj / range_y
end
"""
Compute exact "aspect ratio"
"""
aspect_ratio(bounds::OpenStreetMapX.Bounds{OpenStreetMapX.ENU}) =
(bounds.max_x - bounds.min_x) / (bounds.max_y - bounds.min_y)
"""
Draw Ways without defined layers
"""
function draw_ways!(p,nodes::Dict{Int,T}, ways::Vector{OpenStreetMapX.Way},
style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
for way in ways
X = [OpenStreetMapX.getX(nodes[node]) for node in way.nodes]
Y = [OpenStreetMapX.getY(nodes[node]) for node in way.nodes]
if isa(nodes,Dict{Int,OpenStreetMapX.ENU}) && km
X /= 1000
Y /= 1000
end
if length(X) > 1
Plots.plot!(p, X, Y, color=style.color,width=style.width,
linestyle=gr_linestyles[style.spec])
end
end
end
"""
Draw Ways with defined Layers
"""
function draw_ways!(p,nodes::Dict{Int,T}, ways::Vector{OpenStreetMapX.Way},
class::Dict{Int,Int}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
for i = 1:length(ways)
lineStyle = style[class[ways[i].id]]
X = [OpenStreetMapX.getX(nodes[node]) for node in ways[i].nodes]
Y = [OpenStreetMapX.getY(nodes[node]) for node in ways[i].nodes]
if isa(nodes,Dict{Int,OpenStreetMapX.ENU}) && km
X /= 1000
Y /= 1000
end
if length(X) > 1
Plots.plot!(p, X, Y, color=lineStyle.color,width=lineStyle.width,
linestyle=gr_linestyles[lineStyle.spec])
end
end
end
"""
Draw Buildings
"""
function draw_buildings!(p,nodes::Dict{Int,T},
buildings::Vector{OpenStreetMapX.Way}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if isa(style, OpenStreetMapXPlot.Style)
OpenStreetMapXPlot.draw_ways!(p,nodes,buildings,style,km)
else
classes = OpenStreetMapX.classify_buildings(buildings)
OpenStreetMapXPlot.draw_ways!(p,nodes,buildings, classes, style,km)
end
end
"""
Draw Roadways
"""
function draw_roadways!(p,nodes::Dict{Int,T},
roadways::Vector{OpenStreetMapX.Way}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if isa(style, OpenStreetMapXPlot.Style)
OpenStreetMapXPlot.draw_ways!(p,nodes,roadways,style,km)
else
classes = OpenStreetMapX.classify_roadways(roadways)
OpenStreetMapXPlot.draw_ways!(p,nodes,roadways, classes, style,km)
end
end
"""
Draw Walkways
"""
function draw_walkways!(p,nodes::Dict{Int,T},
walkways::Vector{OpenStreetMapX.Way}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if isa(style, OpenStreetMapXPlot.Style)
OpenStreetMapXPlot.draw_ways!(p,nodes,walkways,style,km)
else
classes = OpenStreetMapX.classify_walkways(walkways)
OpenStreetMapXPlot.draw_ways!(p,nodes,walkways, classes, style,km)
end
end
"""
Draw Cycleways
"""
function draw_cycleways!(p,nodes::Dict{Int,T},
cycleways::Vector{OpenStreetMapX.Way}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if isa(style, OpenStreetMapXPlot.Style)
OpenStreetMapXPlot.draw_ways!(p,nodes,cycleways,style,km)
else
classes = OpenStreetMapX.classify_cycleways(cycleways)
OpenStreetMapXPlot.draw_ways!(p,nodes,cycleways, classes, style,km)
end
end
"""
Draw Features
"""
function draw_features!(p,nodes::Dict{Int,T},
features::Dict{Int,Tuple{String,String}}, style::OpenStreetMapXPlot.Styles,
km::Bool) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if isa(style, OpenStreetMapXPlot.Style)
X = [OpenStreetMapX.getX(nodes[node]) for node in keys(features)]
Y = [OpenStreetMapX.getY(nodes[node]) for node in keys(features)]
if isa(nodes,Dict{Int,OpenStreetMapX.ENU}) && km
X /= 1000
Y /= 1000
end
if length(X) > 1
Plots.plot!(p, X, Y, color=style.color,width=style.width,
linestyle=gr_linestyles[style.spec])
end
else
classes = OpenStreetMapX.classify_features(features)
for (key,val) in style
indices = [id for id in keys(classes) if classes[id] == key]
X = [OpenStreetMapX.getX(nodes[node]) for node in indices]
Y = [OpenStreetMapX.getY(nodes[node]) for node in indices]
if isa(nodes,Dict{Int,OpenStreetMapX.ENU}) && km
X /= 1000
Y /= 1000
end
if length(X) > 1
Plots.plot!(p, X, Y, color=val.color,width=val.width,
linestyle=gr_linestyles[val.spec])
end
end
end
end
"""
plotmap(nodes::Dict{Int,T},
bounds::Union{Nothing,OpenStreetMapX.Bounds{T}} = nothing;
buildings::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
buildingStyle::Styles=OpenStreetMapXPlot.Style("0x000000", 1, "-"),
roadways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
roadwayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
walkways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
walkwayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
cycleways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
cyclewayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
features::Union{Nothing,Dict{Int64,Tuple{String,String}}} = nothing,
featureStyle::Styles=OpenStreetMapXPlot.Style("0xCC0000", 2.5, "."),
width::Integer=600,
height::Integer=600,
fontsize::Integer=0,
km::Bool=false,
use_plain_pyplot::Bool=false
) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
Plots selected map features for a given dictionary of node locations (`nodes`)
and within the given `bounds`.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
The default plotting backend is whatever is defined in `Plots.jl`, however if the `use_plain_pyplot`
is set to `true` Plots.pythonplot() will be called to switch to PythonPlot backend
(note this option is depraciated and normally backend should be changed outside of this function).
Returns an object that can be used for further plot updates.
"""
function plotmap(nodes::Dict{Int,T},
bounds::Union{Nothing,OpenStreetMapX.Bounds{T}} = nothing;
buildings::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
buildingStyle::Styles=OpenStreetMapXPlot.Style("0x000000", 1, "-"),
roadways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
roadwayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
walkways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
walkwayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
cycleways::Union{Nothing,Vector{OpenStreetMapX.Way}} = nothing,
cyclewayStyle::Styles=OpenStreetMapXPlot.Style("0x007CFF", 1.5, "-"),
features::Union{Nothing,Dict{Int64,Tuple{String,String}}} = nothing,
featureStyle::Styles=OpenStreetMapXPlot.Style("0xCC0000", 2.5, "."),
width::Integer=600,
height::Integer=600,
fontsize::Integer=0,
km::Bool=false, use_plain_pyplot::Bool=false
) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
if use_plain_pyplot && !any(contains.(string(Plots.backend()), ["Python", "PyPlot"]))
@warn "Will now call Plots.pythonplot() to switch to PythonPlot backend"
Plots.pythonplot()
end
# Chose labels according to point type and scale
xlab, ylab = if isa(nodes, Dict{Int,OpenStreetMapX.LLA})
"Longitude (deg)", "Latitude (deg)"
elseif km
"East (km)", "North (km)"
else
"East (m)", "North (m)"
end
local p
if isa(bounds,Nothing)
p = Plots.plot(xlabel=xlab,ylabel=ylab,legend=false,size=(width,height))
else # Limit plot to specified bounds
if km && isa(nodes, Dict{Int,OpenStreetMapX.ENU})
xrange = (bounds.min_x/1000, bounds.max_x/1000)
yrange = (bounds.min_y/1000, bounds.max_y/1000)
else
xrange = (bounds.min_x, bounds.max_x)
yrange = (bounds.min_y, bounds.max_y)
end
p = Plots.plot(xlabel=xlab,ylabel=ylab,xlims=xrange,ylims=yrange,legend=false,size=(width,height))
end
# Draw all buildings
if !isa(buildings,Nothing)
OpenStreetMapXPlot.draw_buildings!(p,nodes, buildings, buildingStyle, km)
end
# Draw all roadways
if !isa(roadways,Nothing)
OpenStreetMapXPlot.draw_roadways!(p,nodes, roadways, roadwayStyle, km)
end
# Draw all walkways
if !isa(walkways,Nothing)
OpenStreetMapXPlot.draw_walkways!(p,nodes, walkways, walkwayStyle, km)
end
# Draw all cycleways
if !isa(cycleways,Nothing)
OpenStreetMapXPlot.draw_cycleways!(p,nodes, cycleways, cyclewayStyle, km)
end
#Draw all features
if !isa(features,Nothing)
OpenStreetMapXPlot.draw_features!(p,nodes, features, featureStyle, km)
end
if fontsize > 0
attr = Dict(:fontsize => fontsize)
end
return p
end
"""
plotmap(m::OpenStreetMapX.MapData;
roadwayStyle = OpenStreetMapXPlot.LAYER_STANDARD,
width::Integer=600, height::Integer=600, use_plain_pyplot::Bool=false)
Plots `roadways` for a given map `m`.
The width will be set to `width` and the height will be set to `height`. If only one of `width`
or `height` is set, the other will be set to perserve the aspect ratio of the bounding box.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
The default plotting backend is whatever is defined in `Plots.jl`, however if the `use_plain_pyplot`
is set to `true` Plots.pythonplot() will be called to switch to PythonPlot backend
(note this option is depraciated and normally backend should be changed outside of this function).
Returns an object that can be used for further plot updates.
"""
function plotmap(m::OpenStreetMapX.MapData;roadwayStyle = OpenStreetMapXPlot.LAYER_STANDARD,
width::Union{Integer,Nothing}=nothing, height::Union{Integer,Nothing}=nothing, km::Bool=false, use_plain_pyplot::Bool=false)
# Set plot aspect ratio to that of bounds (in meters), unless both height and width are specified
if isnothing(width) || isnothing(height)
# Compute aspect ratio
aspect_ratio = OpenStreetMapXPlot.aspect_ratio(m.bounds)
if isnothing(width) && isnothing(height)
width = 600
height = Int(round(width/aspect_ratio))
elseif isnothing(height)
height = Int(round(width/aspect_ratio))
elseif isnothing(width)
width = Int(round(height*aspect_ratio))
end
end
plotmap(m.nodes, OpenStreetMapX.ENU(m.bounds), roadways=m.roadways,roadwayStyle = roadwayStyle,
width=width, height=height, km=km, use_plain_pyplot=use_plain_pyplot)
end
"""
plotmap(m::OpenStreetMapX.Mapaddroute!(p, m::OpenStreetMapX.MapData,
route::Vector{Int}; route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false)
Adds a `route` to the plot `p` representing the map `m`.
The first element from the list of nodes `route` will be annoted by `start_name`
while the last will be annotated by `end_name`.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
Returns an object that can be used for further plot updates.
"""
function addroute!(p, m::OpenStreetMapX.MapData,
route::Vector{Int}; route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false, start_name="A", end_name="B", fontsize=15)
addroute!(p, m.nodes, route, route_color=route_color, km=km, start_name=start_name, end_name=end_name, fontsize=fontsize)
end
"""
addroute!(p, nodes::Dict{Int,T},
route::Vector{Int};
route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false,
start_name="A", end_name="B",
fontsize=15
) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
Adds a `route` to the plot `p` using the node information stored in `nodes`.
The first element from the list of nodes `route` will be annoted by `start_name`
while the last will be annotated by `end_name`.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
Returns an object that can be used for further plot updates.
"""
function addroute!(p, nodes::Dict{Int,T},
route::Vector{Int}; route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false, start_name="A", end_name="B", fontsize=15) where T<:Union{OpenStreetMapX.LLA,OpenStreetMapX.ENU}
route_style = OpenStreetMapXPlot.Style(route_color, 3, "--")
X = [OpenStreetMapX.getX(nodes[node]) for node in route]
Y = [OpenStreetMapX.getY(nodes[node]) for node in route]
if isa(nodes,Dict{Int,OpenStreetMapX.ENU}) && km
X /= 1000
Y /= 1000
end
#length(X) > 1 && Winston.plot(p, X, Y, route_style.spec, color=route_style.color, linewidth=route_style.width)
if length(X) > 1
Plots.plot!(p, X, Y, color=route_style.color,width=route_style.width,linestyle=gr_linestyles[route_style.spec])
Plots.annotate!(p,X[1],Y[1],Plots.text(start_name,fontsize))
Plots.annotate!(p,X[end],Y[end],Plots.text(end_name,fontsize))
end
p
end
"""
addroute!(p, m::OpenStreetMapX.MapData,
route::Vector{OpenStreetMapX.LLA};
route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false,
start_name="A", end_name="B",
fontsize=15
)
Adds a `route` in LLA coordinates to the plot `p` representing the map `m`.
The first element from the list of route coordinates `route` will be annoted by `start_name`
while the last will be annotated by `end_name`.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
Returns an object that can be used for further plot updates.
"""
function addroute!(p, m::OpenStreetMapX.MapData,
route::Vector{OpenStreetMapX.LLA}; route_color::Union{String, Plots.RGB} ="0x000053",
km::Bool=false, start_name="A", end_name="B", fontsize=15)
route_style = OpenStreetMapXPlot.Style(route_color, 3, "--")
routeENU = [ENU(lla, m.bounds) for lla in route]
X = map(enu->enu.east, routeENU)
Y = map(enu->enu.north, routeENU)
if km
X /= 1000
Y /= 1000
end
if length(X) > 1
Plots.plot!(p, X, Y, color=route_style.color,width=route_style.width,linestyle=gr_linestyles[route_style.spec])
Plots.annotate!(p,X[1],Y[1],Plots.text(start_name,fontsize))
Plots.annotate!(p,X[end],Y[end],Plots.text(end_name,fontsize))
end
p
end
"""
plot_nodes!(p, m::OpenStreetMapX.MapData,
nodeids::Vector{Int};
start_numbering_from::Union{Int,Nothing}=1,
km::Bool=false,
color="darkgreen",
fontsize=10)
Plots nodes having node identifiers `nodeids` on the plot `p` using map information `m`.
By default the node indices within the are plotted (e.g. 1, 2, 3...), however,
setting the parameter `start_numbering_from` to nothing will show actual OSM node identifiers.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
Returns an object that can be used for further plot updates.
"""
function plot_nodes!(p,m::OpenStreetMapX.MapData,nodeids::Vector{Int};
start_numbering_from ::Union{Int,Nothing}=1, km::Bool=false, color="darkgreen", fontsize=10)
(length(nodeids) == 0) && return
divkm = (isa(m.nodes[nodeids[1]],OpenStreetMapX.ENU) && km) ? 1000.0 : 1.0
for i in 1:length(nodeids)
X = OpenStreetMapX.getX(m.nodes[nodeids[i]]) / divkm
Y = OpenStreetMapX.getY(m.nodes[nodeids[i]]) / divkm
num = string(start_numbering_from == nothing ? nodeids[i] : (i-1+start_numbering_from))
Plots.annotate!(p,X,Y,Plots.text(num,fontsize,color))
end
p
end
"""
plot_nodes_as_symbols!(p, m::OpenStreetMapX.MapData,
nodeids::Vector{Int};
symbols::Union{T, Vector{T}}="*",
colors::Union{U,Vector{U}}=["darkgreen"],
km::Bool=false, fontsize=10)
where {T <: Union{String,Symbol}, U <: Union{String,Plots.RGB}}
Plots nodes having node identifiers `nodeids` on the plot `p` using map information `m`.
By default the nodes are plotted with the "*" symbol, however,
setting the parameter `symbols` to a string will plot all node locations as that string.
Setting `symbols` to an array of strings will plot each successive location as the symbol
in that position of the array, repeating over the string array if the `symbols` array
is shorter than the `nodeids` array.
The `km` parameter can be used to have a kilometer scale of the map instead of meters.
Returns an object that can be used for further plot updates.
"""
function plot_nodes_as_symbols!(p,m::OpenStreetMapX.MapData,nodeids::Vector{Int};
symbols::Union{T, Vector{T}}="*",
colors::Union{U,Vector{U}}=["darkgreen"],
km::Bool=false, fontsize=10) where {T <: Union{String,Symbol}, U <: Union{String,Plots.RGB}}
(length(nodeids) == 0) && return
divkm = (isa(m.nodes[nodeids[1]],OpenStreetMapX.ENU) && km) ? 1000.0 : 1.0
symbols = typeof(symbols)<:AbstractVector ? symbols : [symbols]
colors = typeof(colors)<:AbstractVector ? colors : [colors]
for i in 1:length(nodeids)
X = OpenStreetMapX.getX(m.nodes[nodeids[i]]) / divkm
Y = OpenStreetMapX.getY(m.nodes[nodeids[i]]) / divkm
j = (i-1)%length(symbols) + 1
k = (i-1)%length(colors) + 1
Plots.annotate!(p,X,Y,Plots.text(symbols[j],fontsize,colors[k]))
end
p
end
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | code | 1251 | println("Running tests at $(pwd())")
using Test, OpenStreetMapX
const m = OpenStreetMapX.sample_map();
using Random
Random.seed!(0);
const pointA = point_to_nodes(generate_point_in_bounds(m), m)
const pointB = point_to_nodes(generate_point_in_bounds(m), m)
sr1, shortest_distance1, shortest_time1 = OpenStreetMapX.shortest_route(m, pointA, pointB)
@assert length(sr1) > 0
ENV["PLOTS_TEST"] = "true" #copied from Plots.jl tests
ENV["GKSwstype"] = "100" #copied from Plots.jl tests
ENV["MPLBACKEND"]="agg" # no GUI - copied from PyPlot.jl tests
using OpenStreetMapXPlot
println("OpenStreetMapXPlot is located at $(pathof(OpenStreetMapXPlot))")
import Plots
Plots.gr()
Plots.default(show=false, reuse=true)
const trk = [LLA(m.bounds.min_y,m.bounds.min_x,0.0), LLA(m.bounds.max_y,m.bounds.max_x,0.0)]
@testset "Plots backend " begin
p = OpenStreetMapXPlot.plotmap(m)
@test typeof(p) == Plots.Plot{Plots.GRBackend}
@test addroute!(p,m,sr1;route_color="red") == p
@test plot_nodes!(p,m,[sr1[1],sr1[end]],start_numbering_from=nothing,fontsize=13,color="pink") == p
@test plot_nodes_as_symbols!(p, m, sr1, symbols=["*","+","#"],colors=["red","green","blue"],fontsize=13) == p
@test addroute!(p,m,trk;route_color="red") == p
end
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | docs | 2129 | # OpenStreetMapXPlot.jl
[Documentation ![](https://img.shields.io/badge/docs-latest-blue.svg)](https://pszufe.github.io/OpenStreetMapXPlot.jl/latest)
This is a plotting companion for the [OpenStreetMapX.jl](https://github.com/pszufe/OpenStreetMapX.jl) package.
The package provides plotting mechanisms for map vizualization via Plots.jl.
The recommended backend is `gr()`
## Installation
The current version has been tested with Julia 1.9 and up
```julia
using Pkg
pkg"add OpenStreetMapX"
pkg"add OpenStreetMapXPlot"
```
## Usage
We will show a full scenario including routing. Let us start by preparing the data and calculating a sample route.
```julia
using OpenStreetMapX
m = get_map_data(sample_map_path(), use_cache = false);
import Random
Random.seed!(0);
pointA = point_to_nodes(generate_point_in_bounds(m), m)
pointB = point_to_nodes(generate_point_in_bounds(m), m)
sr = shortest_route(m, pointA, pointB)[1]
```
Once the map data is in the memory we can start plotting. Let us start with `Plots.jl` with a `GR` back-end (this is the recommended approach due to GR's plotting speed, however due to Julia compiling process *time-to-the-first-plot* is around one minute, while subsequent plots can be created within few seconds).
```julia
using OpenStreetMapXPlot
using Plots, Colors
Plots.gr()
p = OpenStreetMapXPlot.plotmap(m,width=600,height=400);
addroute!(p,m,sr;route_color=colorant"red");
plot_nodes!(p,m,[sr[1],sr[end]],start_numbering_from=nothing,fontsize=13,color=colorant"blue");
p
```
![](plot_image_gr.png)
#### Acknowledgments
<sup>This code is a major re-write of plotting functionality of [https://github.com/tedsteiner/OpenStreetMap.jl](https://github.com/tedsteiner/OpenStreetMap.jl) project.
The creation of this source code was partially financed by research project supported by the Ontario Centres of Excellence ("OCE") under Voucher for Innovation and Productivity (VIP) program, OCE Project Number: 30293, project name: "Agent-based simulation modelling of out-of-home advertising viewing opportunity conducted in cooperation with Environics Analytics of Toronto, Canada. </sup>
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | docs | 183 | # OpenStreetMapXPlot.jl
Documentation for OpenStreetMapXPlot.jl
For details please go to the [Reference](https://pszufe.github.io/OpenStreetMapXPlot.jl/latest/reference/) section.
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"MIT"
] | 0.2.0 | cbfd2a5cb0b121ce097f199f6d119c2ce983da5b | docs | 280 | Reference
=========
```@meta
CurrentModule = OpenStreetMapXPlot
DocTestSetup = quote
using OpenStreetMapX
using OpenStreetMapXPlot
end
```
Map plotting functions
----------------------
```@docs
Style
plotmap
addroute!
plot_nodes!
```
```@meta
DocTestSetup = nothing
```
| OpenStreetMapXPlot | https://github.com/pszufe/OpenStreetMapXPlot.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 408 | module PDDLViz
using Base: @kwdef
using PDDL, SymbolicPlanners
using Makie, GraphMakie
using Graphs, NetworkLayout
using FileIO, Base64
using OrderedCollections
using DocStringExtensions
using Printf
include("utils.jl")
include("graphics/graphics.jl")
include("interface.jl")
include("render.jl")
include("animate.jl")
include("storyboard.jl")
include("control.jl")
include("renderers/renderers.jl")
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 21176 | export anim_initialize!, anim_transition!
export anim_plan!, anim_plan
export anim_trajectory!, anim_trajectory
export anim_solve!, anim_solve, anim_refine!
import Makie: FigureLike
"""
Animation
Displayable animation which wraps a `VideoStream` object. Can be displayed
with `show(io, MIME"text/html"(), anim)`, or saved with `save(path, anim)`.
"""
mutable struct Animation
videostream::VideoStream
path::String
end
Animation(videostream::VideoStream) =
Animation(videostream, videostream.path)
Animation(figlike::FigureLike; kwargs...) =
Animation(VideoStream(figlike; kwargs...))
Animation(canvas::Canvas; kwargs...) =
Animation(canvas.figure; kwargs...)
Makie.recordframe!(anim::Animation) =
recordframe!(anim.videostream)
function FileIO.save(path::AbstractString, anim::Animation; kwargs...)
if anim.path == anim.videostream.path
save(path, anim.videostream; kwargs...)
anim.path = abspath(path)
elseif anim.path != abspath(path)
format = lstrip(splitext(path)[2], '.')
options = anim.videostream.options
if format != options.format || !isempty(kwargs)
framerate = get(kwargs, :framerate, options.framerate)
Makie.convert_video(anim.path, path; framerate=framerate, kwargs...)
else
cp(anim.path, path; force=true)
end
else
warn("Animation already saved to $path.")
end
return path
end
Base.show(io::IO, ::MIME"juliavscode/html", anim::Animation) =
show(io, MIME"text/html"(), anim)
function Base.show(io::IO, ::MIME"text/html", anim::Animation)
# Save to file if not already saved
format = anim.videostream.options.format
if anim.path == anim.videostream.path
dir = mktempdir()
path = joinpath(dir, "$(gensym(:video)).$(format)")
save(path, anim)
end
# Display animation as HTML tag, depending on format
if format == "gif"
# Display GIFs as image tags
blob = base64encode(read(anim.path))
print(io, "<img src=\"data:image/gif;base64,$blob\">")
elseif format == "mp4"
# Display MP4 videos as video tags
blob = base64encode(read(anim.path))
print(io, "<video controls autoplay muted>",
"<source src=\"data:video/mp4;base64,$blob\"",
"type=\"video/mp4\"></video>")
else
# Convert other video types to MP4
mktempdir() do dir
path = joinpath(dir, "video.mp4")
save(path, anim)
blob = base64encode(read(path))
print(io, "<video controls autoplay muted>",
"<source src=\"data:video/mp4;base64,$blob\"",
"type=\"video/mp4\"></video>")
end
end
end
"""
Transition
Abstract animation transition type.
"""
abstract type Transition end
"""
StepTransition
Transition that immediately steps to the next state.
"""
struct StepTransition <: Transition end
"""
LinearTransition
Transition that linearly interpolates between node positions.
"""
struct LinearTransition <: Transition end
"""
ManhattanTransition(;
order = [:up, :horizontal, :down],
stop_early = [true, false, false]
)
Transition that interpolates between node positions by moving horizontally
and vertically.
# Arguments
- `order::Vector{Symbol} = [:up, :horizontal, :down]`: Order in which to
interpolate between node positions. Valid values are `:up`, `:down`,
`:left`, `:right`, `:horizontal`, and `:vertical`.
- `stop_early::Vector{Bool} = [true, false, false]`: Whether to stop
interpolating early for each direction. If `true`, then the transition
will stop once that direction is done. If no nodes have moved in that
direction, then the transition will continue to the next direction.
"""
@kwdef struct ManhattanTransition <: Transition
order::Vector{Symbol} = [:up, :horizontal, :down]
stop_early::Vector{Bool} = [true, false, false]
end
"""
anim_initialize!(canvas, renderer, domain, state;
callback=nothing, overlay=nothing, kwargs...)
Initializes an animation that will be rendered on the `canvas`. Called by
[`anim_plan`](@ref) and [`anim_trajectory`](@ref) as an initialization step.
By default, this just renders the initial `state` on the `canvas`. This function
can be overloaded for different [`Renderer`](@ref) types to implement custom
initializations, e.g., to add captions or other overlays.
"""
function anim_initialize!(
canvas::Canvas, renderer::Renderer, domain::Domain, state::State;
callback=nothing, overlay=nothing, kwargs...
)
if canvas.state === nothing
render_state!(canvas, renderer, domain, state; kwargs...)
else
anim_transition!(canvas, renderer, domain, state; kwargs...)
end
# Run callbacks
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
return canvas
end
"""
anim_transition!(canvas, renderer, domain, state, [action, t];
callback=nothing, overlay=nothing, kwargs...)
Animates a transition from the current state stored in the `canvas` to the
newly provided `state` (via `action` at timestep `t` if provided). Called by
[`anim_plan`](@ref) and [`anim_trajectory`](@ref) to animate a series of
state transitions.
By default, this updates the `canvas` with the new `state`, then runs the
`overlay` and `callback` functions (if provided) on `canvas` (e.g. to ovelay
annotations, or to record a frame).
This function can be overloaded for different [`Renderer`](@ref) types to
implement custom transitions, e.g., transitions that involve multiple frames.
"""
function anim_transition!(
canvas::Canvas, renderer::Renderer, domain::Domain,
state::State, action::Term, t::Int;
callback=nothing, overlay=nothing, kwargs...
)
# Ignore timestep by default
return anim_transition!(canvas, renderer, domain, state, action;
callback, overlay, kwargs...)
end
function anim_transition!(
canvas::Canvas, renderer::Renderer, domain::Domain,
state::State, action::Term;
callback=nothing, overlay=nothing, kwargs...
)
# Ignore action by default
return anim_transition!(canvas, renderer, domain, state;
callback, overlay, kwargs...)
end
function anim_transition!(
canvas::Canvas, renderer::Renderer, domain::Domain, state::State;
callback=nothing, overlay=nothing, kwargs...
)
# Default to updating canvas with new state
canvas.state[] = state
# Run callback
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
return canvas
end
"""
anim_plan([path], renderer, domain, state, actions;
format="mp4", framerate=5, show=false,
record_init=true, options...)
anim_plan!([anim|path], canvas, renderer, domain, state, actions;
format="mp4", framerate=5, show=is_displayed(canvas),
record_init=true, options...)
Uses `renderer` to animate a series of `actions` in a PDDL `domain` starting
from `state` (updating the `canvas` if one is provided). An [`Animation`](@ref)
object is returned, which can be saved or displayed.
An existing `anim` can provided as the first argument, so that frames are
appended to that animation (format and frame rates are ignored in this case).
Alternatively, if a `path` is specified, the animation is saved to that file,
and the `path` is returned.
Note that once an animation is displayed or saved, no frames can be added to it.
"""
function anim_plan(
renderer::Renderer, domain::Domain, state::State, actions;
show::Bool=false, kwargs...
)
canvas = new_canvas(renderer)
return anim_plan!(canvas, renderer, domain, state, actions;
show, kwargs...)
end
function anim_plan(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
save(path, anim_plan(args...; format, kwargs...))
end
function anim_plan!(
canvas::Canvas, renderer::Renderer, domain::Domain, state::State, actions;
kwargs...
)
trajectory = PDDL.simulate(domain, state, actions)
return anim_trajectory!(canvas, renderer, domain,
trajectory, actions; kwargs...)
end
function anim_plan!(
anim::Animation, canvas::Canvas,
renderer::Renderer, domain::Domain, state::State, actions;
kwargs...
)
trajectory = PDDL.simulate(domain, state, actions)
return anim_trajectory!(anim, canvas, renderer, domain,
trajectory, actions; kwargs...)
end
function anim_plan!(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
save(path, anim_plan!(args...; format, kwargs...))
end
@doc (@doc anim_plan) anim_plan!
"""
anim_trajectory([path], renderer, domain, trajectory, [actions];
format="mp4", framerate=5, show=false,
record_init=true, options...)
anim_trajectory!([anim|path], canvas, renderer,
domain, trajectory, [actions];
format="mp4", framerate=5, show=is_displayed(canvas),
record_init=true, options...)
Uses `renderer` to animate a `trajectory` in a PDDL `domain` (updating the
`canvas` if one is provided). An [`Animation`](@ref) object is returned,
which can be saved or displayed.
An existing `anim` can provided as the first argument, so that frames are
appended to that animation (format and frame rates are ignored in this case).
Alternatively, if a `path` is specified, the animation is saved to that file,
and the `path` is returned.
Note that once an animation is displayed or saved, no frames can be added to it.
"""
function anim_trajectory(
renderer::Renderer, domain::Domain,
trajectory, actions=fill(PDDL.no_op, length(trajectory)-1);
show::Bool=false, kwargs...
)
canvas = new_canvas(renderer)
return anim_trajectory!(canvas, renderer, domain, trajectory;
show, kwargs...)
end
function anim_trajectory(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
save(path, anim_trajectory(args...; format=format, kwargs...))
end
function anim_trajectory!(
canvas::Canvas, renderer::Renderer, domain::Domain,
trajectory, actions=fill(PDDL.no_op, length(trajectory)-1);
format="mp4", framerate=5, show::Bool=is_displayed(canvas),
showrate=framerate, record_init=true, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation
record_args = filter(Dict(options)) do (k, v)
k in (:compression, :profile, :pixel_format, :loop)
end
anim = Animation(canvas.figure; visible=is_displayed(canvas),
format, framerate, record_args...)
# Record animation
anim_trajectory!(anim, canvas, renderer, domain, trajectory, actions;
show, showrate, record_init, options...)
return anim
end
function anim_trajectory!(
anim::Animation, canvas::Canvas, renderer::Renderer, domain::Domain,
trajectory, actions=fill(PDDL.no_op, length(trajectory)-1);
show::Bool=is_displayed(canvas), showrate=5, record_init=true, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation and record initial frame
anim_initialize!(canvas, renderer, domain, trajectory[1]; options...)
record_init && recordframe!(anim)
# Construct recording callback
function record_callback(canvas::Canvas)
recordframe!(anim)
!show && return
notify(canvas.state)
sleep(1/showrate)
end
# Iterate over subsequent states and actions
for (t, act) in enumerate(actions)
state = trajectory[t+1]
anim_transition!(canvas, renderer, domain, state, act, t+1;
callback=record_callback, options...)
end
return anim
end
function anim_trajectory!(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
save(path, anim_trajectory!(args...; format=format, kwargs...))
end
@doc (@doc anim_trajectory) anim_trajectory!
"""
AnimSolveCallback{R <: Renderer}
A callback for [`anim_solve`](@ref) that animates the solving process of a
SymbolicPlanners.jl [`Planner`]. The behavior of this callback can be customized
on a per-renderer and per-`planner`` basis by defining a new method for
`(cb::AnimSolveCallback{R <: Renderer)(planner::Planner, args...)`.
"""
struct AnimSolveCallback{R <: Renderer} <: Function
renderer::R
domain::Domain
canvas::Canvas
sleep_dur::Float64
record_callback::Union{Nothing, Function}
options::Dict{Symbol, Any}
end
function AnimSolveCallback(
renderer::R, domain::Domain, canvas::Canvas,
sleep_dur::Real = 0.0, record_callback = nothing;
options...
) where {R <: Renderer}
return AnimSolveCallback{R}(renderer, domain, canvas, sleep_dur,
record_callback, Dict(options))
end
"""
anim_solve([path], renderer, planner, domain, state, spec;
format="mp4", framerate=30, show=false,
record_init=true, options...)
anim_solve!([anim|path], canvas, renderer,
planner, domain, state, spec;
format="mp4", framerate=30, show=is_displayed(canvas),
record_init=true, options...)
Uses `renderer` to animate the solving process of a SymbolicPlanners.jl
`planner` in a PDDL `domain` (updating the `canvas` if one is provided).
Returns a tuple `(anim, sol)` where `anim` is an [`Animation`](@ref) object
containing the animation, and `sol` is the solution returned by `planner`. If
`anim` is provided as the first argument, then additional frames are added to
the animation. Alternatively, if a `path` is provided, the animation is saved
to that file, and `(path, sol)` is returned.
Note that once an animation is displayed or saved, no frames can be added to it.
"""
function anim_solve(
renderer::Renderer, planner::Planner, domain::Domain, state::State, spec;
show::Bool=false, kwargs...
)
canvas = new_canvas(renderer)
return anim_solve!(canvas, renderer, planner, domain, state, spec;
show=show, kwargs...)
end
function anim_solve(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
anim, sol = anim_solve(args...; format=format, kwargs...)
save(path, anim)
return (path, sol)
end
function anim_solve!(
canvas::Canvas, renderer::Renderer,
planner::Planner, domain::Domain, state::State, spec;
format="mp4", framerate=30, show::Bool=is_displayed(canvas),
showrate=framerate, record_init=true, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation
record_args = filter(Dict(options)) do (k, v)
k in (:compression, :profile, :pixel_format, :loop)
end
anim = Animation(canvas.figure; visible=is_displayed(canvas), format=format,
framerate=framerate, record_args...)
# Record animation
return anim_solve!(anim, canvas, renderer, planner, domain, state, spec;
show, showrate, record_init, options...)
end
function anim_solve!(
anim::Animation, canvas::Canvas, renderer::Renderer,
planner::Planner, domain::Domain, state::State, spec;
show::Bool=is_displayed(canvas), showrate=30, record_init=true, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation and record initial frame
anim_initialize!(canvas, renderer, domain, state; options...)
record_init && recordframe!(anim)
# Construct recording callback
function record_callback(canvas::Canvas)
recordframe!(anim)
!show && return
notify(canvas.state)
sleep(1/showrate)
end
# Construct animation callback
anim_callback = AnimSolveCallback(renderer, domain, canvas, 0.0,
record_callback; options...)
# Run planner and return solution with animation
planner = add_anim_callback(planner, anim_callback)
sol = SymbolicPlanners.solve(planner, domain, state, spec)
return (anim, sol)
end
function anim_solve!(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
anim, sol = anim_solve!(args...; format=format, kwargs...)
save(path, anim)
return (path, sol)
end
@doc (@doc anim_solve) anim_solve!
"""
anim_refine!([path], renderer,
sol, planner, domain, state, spec;
format="mp4", framerate=30, show=false,
record_init=true, copy_sol=false, options...)
anim_refine!([anim|path], canvas, renderer,
sol, planner, domain, state, spec;
format="mp4", framerate=30, show=is_displayed(canvas),
record_init=true, copy_sol=false, options...)
Uses `renderer` to animate the refinement of an existing solution by a
SymbolicPlanners.jl `planner` in a PDDL `domain` (updating the `canvas`
if one is provided).
Returns a tuple `(anim, sol)` where `anim` is an [`Animation`](@ref) object
containing the animation, and `sol` is the solution returned by `planner`. If
`anim` is provided as the first argument, then additional frames are added to
the animation. Alternatively, if a `path` is provided, the animation is saved
to that file, and `(path, sol)` is returned. If `copy_sol` is `true`, then
a copy of the initial solution is made before refinement.
Note that once an animation is displayed or saved, no frames can be added to it.
"""
function anim_refine!(
renderer::Renderer,
sol::Solution, planner::Planner, domain::Domain, state::State, spec;
show::Bool=false, kwargs...
)
canvas = new_canvas(renderer)
return anim_refine!(canvas, renderer, sol, planner, domain, state, spec;
show=show, kwargs...)
end
function anim_refine!(path::AbstractString, args...; kwargs...)
format = lstrip(splitext(path)[2], '.')
anim, sol = anim_refine!(args...; format=format, kwargs...)
save(path, anim)
return (path, sol)
end
function anim_refine!(
canvas::Canvas, renderer::Renderer,
sol::Solution, planner::Planner, domain::Domain, state::State, spec;
format="mp4", framerate=30, show::Bool=is_displayed(canvas),
showrate=framerate, record_init=true, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation
record_args = filter(Dict(options)) do (k, v)
k in (:compression, :profile, :pixel_format, :loop)
end
anim = Animation(canvas.figure; visible=is_displayed(canvas), format=format,
framerate=framerate, record_args...)
# Record animation
return anim_refine!(anim, canvas, renderer,
sol, planner, domain, state, spec;
show, showrate, record_init, options...)
end
function anim_refine!(
anim::Animation, canvas::Canvas, renderer::Renderer,
sol::Solution, planner::Planner, domain::Domain, state::State, spec;
show::Bool=is_displayed(canvas), showrate=30, record_init=true,
copy_sol::Bool=false, options...
)
# Display canvas if `show` is true
show && !is_displayed(canvas) && display(canvas)
# Initialize animation and record initial frame
anim_initialize!(canvas, renderer, domain, state; options...)
record_init && recordframe!(anim)
# Construct recording callback
function record_callback(canvas::Canvas)
recordframe!(anim)
!show && return
notify(canvas.state)
sleep(1/showrate)
end
# Construct animation callback
anim_callback = AnimSolveCallback(renderer, domain, canvas, 0.0,
record_callback; options...)
# Refine existing solution and return solution with animation
planner = add_anim_callback(planner, anim_callback)
copy_sol && (sol = copy(sol))
sol = SymbolicPlanners.refine!(sol, planner, domain, state, spec)
return (anim, sol)
end
function add_anim_callback(planner::Planner, cb::AnimSolveCallback)
planner = copy(planner)
planner.callback = cb
return planner
end
function add_anim_callback(planner::RTHS, cb::AnimSolveCallback)
# Set top-level callback
planner = copy(planner)
planner.callback = cb
# Set callback for internal forward-search planner
planner.planner = copy(planner.planner)
planner.planner.callback = cb
return planner
end
function add_anim_callback(planner::AlternatingRTHS, cb::AnimSolveCallback)
# Set top-level callback
planner = copy(planner)
planner.callback = cb
# Set callback for internal forward-search planner
for subplanner in planner.planners
subplanner.planner = copy(subplanner.planner)
subplanner.planner.callback = cb
end
return planner
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 10210 | export Controller, KeyboardController
export add_controller!, remove_controller!, render_controls!
export ControlRecorder
import Makie: ObserverFunction
"""
Controller
Abstract supertype for all controllers. When attached to a canvas, a controller
interprets user input as PDDL actions and updates the canvas accordingly.
Can be attached to a canvas using [`add_controller!`](@ref), and removed using
[`remove_controller`](@ref).
"""
abstract type Controller end
"""
add_controller!(canvas, controller, domain, [init_state];
show_controls::Bool=false)
Adds a `controller` to a `canvas` for a given PDDL `domain`. An initial state
`init_state` can be specified to enable restart functionality.
"""
function add_controller!(canvas::Canvas, controller::Controller,
domain::Domain, init_state=nothing;
show_controls::Bool=false)
error("Not implemented.")
end
"""
remove_controller!(canvas, controller)
Removes a `controller` from a `canvas`.
"""
remove_controller!(canvas::Canvas, controller::Controller) =
error("Not implemented.")
"""
render_controls!(canvas, controller, domain)
Renders controls for a `controller` to a `canvas`.
"""
render_controls!(canvas::Canvas, controller::Controller, domain::Domain) =
nothing
"""
KeyboardController(options...)
KeyboardController(
key1 => act1, key2 => act2, ...,
extra_key1, extra_key2, ...;
exclusive=true, callback=nothing
)
A controller that maps keyboard input to PDDL actions. Set `callback` to a
[`ControlRecorder`](@ref) to record actions.
# Options
$(FIELDS)
"""
@kwdef struct KeyboardController{T,U} <: Controller
"A dictionary mapping keyboard keys to PDDL actions."
keymap::OrderedDict{Keyboard.Button, Term} = OrderedDict{Keyboard.Button, Term}()
"Keys mapped to remaining available actions (default: number keys)."
extrakeys::Vector{Keyboard.Button} = Keyboard.Button.(collect(49:57))
"Function `(state, acts) -> acts` that filters/processes remaining actions."
extraprocess::T = nothing
"Restart button if an initial state is specified."
restart_key::Keyboard.Button = Keyboard.backspace
"Whether an action is executed only if no other keys are pressed."
exclusive::Bool = true
"Post-action callback `f(canvas, domain, state, act, next_state)`."
callback::U = nothing
obsfunc::Ref{ObserverFunction} = Ref{ObserverFunction}()
end
function KeyboardController(
args::Union{Pair{Keyboard.Button, <:Term}, Keyboard.Button}...;
kwargs...
)
keymap = OrderedDict{Keyboard.Button, Term}()
extrakeys = Keyboard.Button[]
for arg in args
if arg isa Pair{Keyboard.Button, <:Term}
keymap[arg[1]] = arg[2]
else
push!(extrakeys, arg)
end
end
if isempty(extrakeys)
return KeyboardController(;keymap=keymap, kwargs...)
else
return KeyboardController(;keymap=keymap, extrakeys=extrakeys, kwargs...)
end
end
function add_controller!(
canvas::Canvas, controller::KeyboardController,
domain::Domain, init_state=nothing;
show_controls::Bool=false
)
controller.obsfunc[] = on(events(canvas.figure).keyboardbutton) do event
figure, callback = canvas.figure, controller.callback
# Skip if no keys are pressed
event.action == Keyboard.press || return
# Skip if window not in focus
events(figure).hasfocus[] || return
# Check if restart button is pressed
if init_state !== nothing && ispressed(figure, Keyboard.backspace)
canvas.state[] = init_state
if callback !== nothing
callback(canvas, domain, nothing, nothing, init_state)
end
return
end
# Get currently available actions
state = canvas.state[]
actions = collect(available(domain, state))
# Check if pressed key is in main keymap
for (key, act) in controller.keymap
key = controller.exclusive ? Exclusively(key) : key
# Execute corresponding action if it is available
if ispressed(figure, key) && act in actions
next_state = transition(domain, state, act; check=false)
canvas.state[] = next_state
if callback !== nothing
callback(canvas, domain, state, act, next_state)
end
return
end
end
# Filter and sort remaining available actions
actions = filter!(a -> !(a in values(controller.keymap)), actions)
if !isnothing(controller.extraprocess)
actions = controller.extraprocess(state, actions)
else
sort!(actions, by=string)
end
# Take first action that matches an extra key
for (i, key) in enumerate(controller.extrakeys)
key = controller.exclusive ? Exclusively(key) : key
if ispressed(figure, key) && i <= length(actions)
act = actions[i]
next_state = transition(domain, state, act; check=false)
canvas.state[] = next_state
if callback !== nothing
callback(canvas, domain, state, act, next_state)
end
return
end
end
end
if show_controls
render_controls!(canvas, controller, domain)
end
return nothing
end
function remove_controller!(canvas::Canvas, controller::KeyboardController)
off(controller.obsfunc[])
end
function render_controls!(
canvas::Canvas, controller::KeyboardController, domain::Domain
)
# Construct control legend
figure = canvas.figure
buttons = collect(keys(controller.keymap))
labels = [write_pddl(controller.keymap[b]) for b in buttons]
n_fixed = length(buttons)
append!(buttons, controller.extrakeys)
append!(labels, fill(' '^40, length(controller.extrakeys)))
markers = _keyboard_button_marker.(buttons)
entries = [LegendEntry(m, Attributes(label=l, labelcolor=:black))
for (l, m) in zip(labels, markers)]
entrygroups = Observable(Makie.EntryGroup[("Controls", entries)])
controls = nothing
try
controls = Legend(figure[1, end+1], entrygroups;
framevisible=false, labelsize=14,
halign=:left, titlehalign=:left)
catch
controls = Legend(figure[1, end+1]; entrygroups=entrygroups,
framevisible=false, labelsize=14,
halign=:left, titlehalign=:left)
end
resize_to_layout!(figure)
# Extract observables from entries
label_obs = Observable[]
lcolor_obs = Observable[]
mcolor_obs = Observable[]
scolor_obs = Observable[]
for entry in controls.entrygroups[][1][2]
push!(label_obs, entry.attributes.label)
push!(lcolor_obs, entry.attributes.labelcolor)
push!(mcolor_obs, entry.elements[2].attributes.markercolor)
push!(scolor_obs, entry.elements[1].attributes.markerstrokecolor)
end
# Set up observer function
on(canvas.state, update=true) do state
# Recolor actions that are not available
actions = collect(available(domain, state))
for (i, key) in enumerate(buttons[1:n_fixed])
act = controller.keymap[key]
if act in actions
lcolor_obs[i][] = :black
mcolor_obs[i][] = :black
scolor_obs[i][] = :black
else
lcolor_obs[i][] = :gray
mcolor_obs[i][] = :gray
scolor_obs[i][] = :gray
end
end
# Filter and sort remaining available actions
actions = filter!(a -> !(a in values(controller.keymap)), actions)
if !isnothing(controller.extraprocess)
actions = controller.extraprocess(state, actions)
else
sort!(actions, by=string)
end
for (i, key) in enumerate(controller.extrakeys)
if i <= length(actions)
act = actions[i]
label_obs[n_fixed+i][] = write_pddl(act)
mcolor_obs[n_fixed+i][] = :black
scolor_obs[n_fixed+i][] = :black
else
label_obs[n_fixed+i][] = ' '^40
mcolor_obs[n_fixed+i][] = :gray
scolor_obs[n_fixed+i][] = :gray
end
end
end
return controls
end
function _keyboard_button_marker(button::Keyboard.Button)
button_id = Int(button)
if button_id > 32 && button_id < 127
char = Char(button_id)
elseif button == Keyboard.space
char = '␣'
elseif button == Keyboard.backspace
char = '⌫'
elseif button == Keyboard.enter
char = '⏎'
elseif button == Keyboard.tab
char = '⇥'
elseif button == Keyboard.up
char = '↑'
elseif button == Keyboard.down
char = '↓'
elseif button == Keyboard.left
char = '←'
elseif button == Keyboard.right
char = '→'
else
char = '⍰'
end
key = MarkerElement(marker=char, markersize=15, markercolor=:black)
box = MarkerElement(marker=:rect, markersize=30, color=(:white, 0.0),
strokewidth=1, strokecolor=:black)
return [box, key]
end
"""
ControlRecorder(record_actions = true, record_states = false)
Callback function for a [`Controller`](@ref) that records actions and states.
After constructing a `recorder`, the recorded values can be accessed via
`recorder.actions` and `recorder.states`.
"""
struct ControlRecorder <: Function
record_actions::Bool
record_states::Bool
actions::Vector{Term}
states::Vector{State}
end
function ControlRecorder(record_actions::Bool=true, record_states::Bool=false)
return ControlRecorder(record_actions, record_states, Term[], State[])
end
function (cb::ControlRecorder)(canvas, domain, state, act, next_state)
act = isnothing(act) ? PDDL.no_op : act
cb.record_actions && push!(cb.actions, act)
cb.record_states && push!(cb.states, next_state)
return nothing
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 5249 | export Canvas, Renderer
export new_canvas, save
import Makie: Block, AbstractPlot
import Makie.GridLayoutBase: GridLayoutBase, gridcontent
"""
Canvas
A `Canvas` is a mutable container for renderable outputs produced by a
[`Renderer`](@ref), consisting of a reference to the figure and grid layout
on which the output is rendered, the PDDL [`State`](@ref) that the output is
based on, and a dictionary of additional `Observable`s.
"""
mutable struct Canvas
figure::Figure
blocks::Vector{Block}
layout::GridLayout
state::Union{Nothing,Observable}
observables::Dict{Symbol,Observable}
plots::Dict{Symbol,AbstractPlot}
end
function Canvas(figure::Figure, blocks::Vector{Block}, layout::GridLayout)
return Canvas(figure, blocks, layout, nothing,
Dict{Symbol,Observable}(), Dict{Symbol,AbstractPlot}())
end
Canvas(figure::Figure) =
Canvas(figure, Block[], figure.layout)
Canvas(figure::Figure, axis::Block) =
Canvas(figure, Block[axis], gridcontent(axis).parent)
Canvas(figure::Figure, layout::GridLayout) =
Canvas(figure, Vector{Block}(contents(layout)), layout)
Canvas(figure::Figure, gp::GridPosition) =
Canvas(figure, Vector{Block}(contents(gp)), gp.layout)
Canvas(axis::Block) =
Canvas(axis.parent, axis)
Canvas(layout::GridLayout) =
Canvas(GridLayoutBase.top_parent(layout), layout)
Canvas(gridpos::GridPosition) =
Canvas(Makie.get_top_parent(gridpos), gridpos)
Base.showable(m::MIME"text/plain", canvas::Canvas) = true
Base.showable(m::MIME, canvas::Canvas) = showable(m, canvas.figure)
Base.show(io::IO, m::MIME"text/plain", canvas::Canvas) = show(io, canvas)
Base.show(io::IO, m::MIME, canvas::Canvas) = show(io, m, canvas.figure)
Base.display(canvas::Canvas; kwargs...) = display(canvas.figure; kwargs...)
function is_displayed(canvas::Canvas)
scene = canvas.figure.scene
screen = Makie.getscreen(scene)
return screen in scene.current_screens
end
FileIO.save(path::AbstractString, canvas::Canvas; kwargs...) =
save(path, canvas.figure; kwargs...)
"""
Renderer
A `Renderer` defines how a PDDL [`State`](@ref) for a specific [`Domain`](@ref)
should be rendered. A concrete sub-type of `Renderer` should be implemented
for a PDDL domain (or family of PDDL domains, e.g. 2D gridworlds) for users who
wish to visualize that domain.
(r::Renderer)(domain::Domain, args...; options...)
(r::Renderer)(canvas::Canvas, domain::Domain, args...; options...)
Once a `Renderer` has been constructed, it can be used to render PDDL states and
other entities by calling it with the appropriate arguments.
"""
abstract type Renderer end
function (r::Renderer)(
domain::Domain, state::MaybeObservable{<:State};
options...
)
return render_state(r, domain, state; options...)
end
function (r::Renderer)(
domain::Domain, state::MaybeObservable{<:State},
actions::MaybeObservable{<:AbstractVector{<:Term}};
options...
)
return render_plan(r, domain, state, actions; options)
end
function (r::Renderer)(
domain::Domain, trajectory::MaybeObservable{AbstractVector{<:State}};
options...
)
return render_trajectory(r, domain, trajectory; options...)
end
function (r::Renderer)(
domain::Domain, state::MaybeObservable{<:State},
sol::MaybeObservable{<:Solution};
options...
)
return render_sol(r, domain, state, sol; options...)
end
function (r::Renderer)(
canvas::Canvas,
domain::Domain, state::MaybeObservable{<:State};
options...
)
return render_state!(canvas, r, domain, state; options...)
end
function (r::Renderer)(
canvas::Canvas,
domain::Domain, state::MaybeObservable{<:State},
actions::MaybeObservable{<:AbstractVector{<:Term}};
options...
)
return render_plan!(canvas, r, domain, state, actions; options...)
end
function (r::Renderer)(
canvas::Canvas,
domain::Domain, trajectory::MaybeObservable{<:AbstractVector{<:State}};
options...
)
return render_trajectory!(canvas, r, domain, trajectory; options...)
end
function (r::Renderer)(
canvas::Canvas,
domain::Domain, state::MaybeObservable{<:State},
sol::MaybeObservable{<:Solution};
options...
)
return render_sol!(canvas, r, domain, state, sol; options...)
end
"""
new_canvas(renderer::Renderer)
new_canvas(renderer::Renderer, figure::Figure)
new_canvas(renderer::Renderer, axis::Axis)
new_canvas(renderer::Renderer, gridpos::GridPosition)
Creates a new [`Canvas`](@ref) to be used by `renderer`. An existing `figure`,
`axis`, or `gridpos` can be specified to use as the base for the new canvas.
"""
function new_canvas(renderer::Renderer)
figure = Figure()
resize!(figure.scene, (800, 800))
axis = Axis(figure[1, 1])
return Canvas(figure, axis)
end
new_canvas(renderer::Renderer, figure::Figure) =
Canvas(figure)
new_canvas(renderer::Renderer, axis::Axis) =
Canvas(axis)
new_canvas(renderer::Renderer, gridpos::GridPosition) =
Canvas(gridpos)
default_state_options(R::Type{<:Renderer}) = Dict{Symbol,Any}()
default_plan_options(R::Type{<:Renderer}) = Dict{Symbol,Any}()
default_trajectory_options(R::Type{<:Renderer}) = Dict{Symbol,Any}()
default_anim_options(R::Type{<:Renderer}) = Dict{Symbol,Any}()
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 4926 | export render_state, render_plan, render_trajectory, render_sol
export render_state!, render_plan!, render_trajectory!, render_sol!
"""
render_state(renderer, domain, state)
Uses `renderer` to render a `state` of a PDDL `domain`. Constructs and
returns a new [`Canvas`](@ref).
"""
function render_state(
renderer::Renderer, domain::Domain, state; options...
)
render_state!(new_canvas(renderer), renderer, domain, state; options...)
end
"""
render_state!(canvas, renderer, domain, state; options...)
Uses `renderer` to render a `state` of a PDDL `domain` to an existing `canvas`,
rendering over any existing content.
"""
function render_state!(
canvas::Canvas, renderer::Renderer, domain::Domain, state;
options...
)
render_state!(canvas, renderer, domain, maybe_observe(state); options...)
end
function render_state!(
canvas::Canvas, renderer::Renderer, domain::Domain, state::Observable;
options...
)
error("Not implemented.")
end
"""
render_plan(renderer, domain, state, actions; options...)
Uses `renderer` to render a series of `actions` in a PDDL `domain` starting
from `state`. Constructs and returns a new [`Canvas`](@ref).
"""
function render_plan(
renderer::Renderer, domain::Domain, state, actions;
options...
)
render_plan!(new_canvas(renderer), renderer, domain, state, actions;
options...)
end
"""
render_plan!(canvas, renderer, domain, state, actions)
Uses `renderer` to render a series of `actions` in a PDDL `domain` starting
from `state`. Renders to a `canvas` on top of any existing content.
"""
function render_plan!(
canvas::Canvas, renderer::Renderer, domain::Domain,
state, actions;
options...
)
render_plan!(canvas, renderer, domain, maybe_observe(state),
maybe_observe(actions); options...)
end
function render_plan!(
canvas::Canvas, renderer::Renderer, domain::Domain,
state::Observable, actions::Observable;
options...
)
trajectory = @lift PDDL.simulate(domain, $state, $actions)
return render_trajectory!(canvas, renderer, domain, trajectory; options...)
end
"""
render_trajectory(renderer::Renderer,
domain::Domain, trajectory::AbstractVector{<:State})
Uses `renderer` to render a `trajectory` of PDDL `domain` states. Constructs
and returns a new [`Canvas`](@ref).
"""
function render_trajectory(
renderer::Renderer, domain::Domain, trajectory;
options...
)
render_trajectory!(new_canvas(renderer), renderer, domain, trajectory;
options...)
end
"""
render_trajectory!(canvas::Canvas, renderer::Renderer,
domain::Domain, trajectory::AbstractVector{<:State})
Uses `renderer` to render a `trajectory` of PDDL `domain` states. Renders to a
`canvas` on top of any existing content.
"""
function render_trajectory!(
canvas::Canvas, renderer::Renderer, domain::Domain, trajectory;
options...
)
render_trajectory!(canvas, renderer, domain, maybe_observe(trajectory);
options...)
end
function render_trajectory!(
canvas::Canvas, renderer::Renderer, domain::Domain, trajectory::Observable;
options...
)
error("Not implemented.")
end
"""
render_sol(renderer::Renderer,
domain::Domain, state::State, sol::Solution)
Uses `renderer` to render a planning solution `sol` starting from a `state` in
a PDDL `domain`. Constructs and returns a new [`Canvas`](@ref).
"""
function render_sol(
renderer::Renderer, domain::Domain, state, sol;
options...
)
render_sol!(new_canvas(renderer), renderer, domain, state, sol; options...)
end
"""
render_sol!(canvas::Canvas, renderer::Renderer,
domain::Domain, state::State, sol::Solution)
Uses `renderer` to render a planning solution `sol` starting from a `state` in
a PDDL `domain`. Renders to a `canvas` on top of any existing content.
"""
function render_sol!(
canvas::Canvas, renderer::Renderer, domain::Domain, state, sol;
options...
)
render_sol!(canvas, renderer, domain, maybe_observe(state),
maybe_observe(sol); options...)
end
function render_sol!(
canvas::Canvas, renderer::Renderer,
domain::Domain, state::Observable, sol::Observable{<:Solution};
options...
)
error("Not implemented.")
end
function render_sol!(
canvas::Canvas, renderer::Renderer,
domain::Domain, state::Observable, sol::Observable{<: OrderedSolution};
options...
)
trajectory = @lift PDDL.simulate(domain, $state, collect($sol))
return render_trajectory!(canvas, renderer, domain, trajectory; options...)
end
function render_sol!(
canvas::Canvas, renderer::Renderer,
domain::Domain, state::Observable, sol::Observable{<:MultiSolution};
options...
)
sol = @lift $sol.selector($sol.solutions, $state)
return render_sol!(canvas, renderer, domain, state, sol; options...)
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 3828 | export render_storyboard
using Makie: extract_frames
"""
render_storyboard(anim::Animation, [idxs]; options...)
Renders an [`Animation`](@ref) as a series of (bitmap) images in a storyboard.
Returns a `Figure` where each frame is a subplot.
The frames to render can be specified by `idxs`, a vector of indices. If
`idxs` is not specified, all frames are rendered.
# Options
- `n_rows = 1`: Number of storyboard rows.
- `n_cols = nothing`: Number of storyboard columns (default: number of frames).
- `figscale = 1`: Scales figure size relative to number of pixels required
to fit all frames at their full resolution.
- `titles`: List or dictionary of frame titles.
- `subtitles`: List or dictionary of frame subtitles.
- `xlabels`: List or dictionary of x-axis labels per frame.
- `ylabels`: List or dictionary of y-axis labels per frame.
Options that control title and label styling (e.g. `titlesize`) can also be
specified as keyword arguments. See `Axis` for details.
"""
function render_storyboard(
anim::Animation, idxs=nothing;
n_rows::Union{Int, Nothing}=1, n_cols::Union{Int, Nothing}=nothing,
figscale::Real=1, options...
)
# Save animation to file if not already saved
if anim.path == anim.videostream.path
dir = mktempdir()
format = anim.videostream.options.format
path = joinpath(dir, "$(gensym(:video)).$(format)")
save(path, anim)
end
# Extract frames from video
frames = Any[]
mktempdir() do dir
extract_frames(anim.path, dir)
for (i, path) in enumerate(readdir(dir))
frame = load(joinpath(dir, path))
idxs !== nothing && !(i in idxs) && continue
push!(frames, rotr90(frame))
end
end
# Determine number of rows and columns
n_frames = length(frames)
if n_rows === nothing && n_cols === nothing
n_rows = 1
n_cols = n_frames
elseif n_rows === nothing
n_rows = ceil(Int, n_frames / n_cols)
elseif n_cols === nothing
n_cols = ceil(Int, n_frames / n_rows)
end
# Extract titles, labels, and other options
titles = get(options, :titles) do
fill(get(options, :title, ""), n_frames)
end
subtitles = get(options, :subtitles) do
fill(get(options, :subtitle, ""), n_frames)
end
xlabels = get(options, :xlabels) do
fill(get(options, :xlabel, ""), n_frames)
end
ylabels = get(options, :ylabels) do
fill(get(options, :ylabel, ""), n_frames)
end
title_options = filter(Dict(options)) do (k, v)
k in (
:titlealign, :titlecolor, :titlefont,
:titlesize, :titlegap, :titlelineheight,
:subtitlealign, :subtitlecolor, :subtitlefont,
:subtitlesize, :subtitlegap, :subtitlelineheight,
:xlabelcolor, :xlabelfont, :xlabelsize,
:xlabelpadding, :xlabelrotation,
:ylabelcolor, :ylabelfont, :ylabelsize,
:ylabelpadding, :ylabelrotation
)
end
# Create figure with subplots for each frame
width = round(Int, size(frames[1])[1] * n_cols * figscale)
height = round(Int, size(frames[1])[2] * n_rows * figscale)
figure = Figure()
resize!(figure.scene, (width, height))
for (i, frame) in enumerate(frames)
i_row = ceil(Int, i / n_cols)
i_col = i - (i_row - 1) * n_cols
ax = Axis(figure[i_row, i_col]; aspect=DataAspect(),
title=get(titles, i, ""), subtitle=get(subtitles, i, ""),
xlabel=get(xlabels, i, ""), ylabel=get(ylabels, i, ""),
title_options...)
image!(ax, frame)
hidedecorations!(ax)
hidespines!(ax)
ax.xlabelvisible = true
ax.ylabelvisible = true
end
resize_to_layout!(figure)
return figure
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 165 | const MaybeObservable{T} = Union{Observable{T}, T}
maybe_observe(x::Observable) = x
maybe_observe(x) = Observable(x)
Point2fVecObservable() = Observable(Point2f[])
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 2293 | using Makie: to_color, ColorScheme
using ColorTypes: RGBA, RGB, Colorant
"Lighten a RGB(A) color by a given amount."
function lighten(color::RGBA, amount::Real)
return RGBA(
color.r + (1 - color.r) * amount,
color.g + (1 - color.g) * amount,
color.b + (1 - color.b) * amount,
color.alpha
)
end
function lighten(color::RGB, amount::Real)
return RGB(
color.r + (1 - color.r) * amount,
color.g + (1 - color.g) * amount,
color.b + (1 - color.b) * amount
)
end
lighten(color, amount::Real) = lighten(to_color(color), amount)
lighten(color::Observable, amount::Real) = lift(x -> lighten(x, amount), color)
"Darken a RGB(A) color by a given amount."
function darken(color::RGBA, amount::Real)
return RGBA(
color.r * (1 - amount),
color.g * (1 - amount),
color.b * (1 - amount),
color.alpha
)
end
function darken(color::RGB, amount::Real)
return RGB(
color.r * (1 - amount),
color.g * (1 - amount),
color.b * (1 - amount)
)
end
darken(color, amount::Real) = darken(to_color(color), amount)
darken(color::Observable, amount::Real) = lift(x -> darken(x, amount), color)
"Set the alpha value of a RGB(A) color."
set_alpha(color::RGBA, alpha::Real) =
RGBA(color.r, color.g, color.b, alpha)
set_alpha(color::RGB, alpha::Real) =
RGBA(color.r, color.g, color.b, alpha)
set_alpha(color, alpha::Real) =
set_alpha(to_color(color), alpha)
set_alpha(color::Observable, alpha::Real) =
lift(x -> set_alpha(x, alpha), color)
"Convert a color or observable to a `Observable{RGBA}`."
to_color_obs(obs::Observable) =
obs[] isa RGBA ? obs : lift(x -> to_color(x), obs)
to_color_obs(color) =
Observable(to_color(color))
"A dictionary of `ColorScheme`s provided by PDDLViz."
const colorschemes = Dict{Symbol, ColorScheme}()
colorschemes[:vibrant] = ColorScheme([
colorant"#D41159",
colorant"#FFC20A",
colorant"#1A85FF",
colorant"#007D68",
colorant"#785EF0",
colorant"#D55E00",
colorant"#56B4E9",
colorant"#CC79A7"
])
colorschemes[:vibrantlight] =
ColorScheme([lighten(c, 0.5) for c in colorschemes[:vibrant]])
colorschemes[:vibrantdark] =
ColorScheme([darken(c, 0.5) for c in colorschemes[:vibrant]])
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 5320 |
"Return the coordinates of a graphic."
GeometryBasics.coordinates(g::BasicGraphic) =
Point2{Float64}.(coordinates(g.shape))
GeometryBasics.coordinates(g::MarkerGraphic) =
coordinates(RectShape(g.x, g.y, g.w, g.h))
GeometryBasics.coordinates(g::TextGraphic) =
coordinates(RectShape(g.x, g.y, g.fontsize[1]*length(g.str), g.fontsize[2]))
GeometryBasics.coordinates(g::MultiGraphic) =
reduce(vcat, (coordinates(c) for c in g.components))
"Return the centroid of a graphic."
centroid(g::BasicGraphic) = centroid(g.shape)
centroid(g::MarkerGraphic) = Point2(g.x, g.y)
centroid(g::TextGraphic) = Point2(g.x, g.y)
centroid(g::MultiGraphic) = centroid(boundingbox(g))
centroid(c::Circle) = c.center
centroid(r::Rect2{T}) where {T} =
Point2{T}(r.origin + r.widths./2)
centroid(p::Polygon{2, T}) where {T} =
Point2{T}(sum(coordinates(p)) ./ length(coordinates(p)))
"Return the bounding box of a graphic."
boundingbox(g::Graphic) = Rect(coordinates(g))
"Translate a graphic by `x` and `y` units."
function translate(g::BasicGraphic, x::Real, y::Real)
return BasicGraphic(translate(g.shape, x, y), copy(g.attributes))
end
function translate(g::MarkerGraphic, x::Real, y::Real)
return MarkerGraphic(g.marker, g.x + x, g.y + y, g.w, g.h, copy(g.attributes))
end
function translate(g::TextGraphic, x::Real, y::Real)
return TextGraphic(g.str, g.x + x, g.y + y, g.fontsize, copy(g.attributes))
end
function translate(g::MultiGraphic, x::Real, y::Real)
return MultiGraphic(map(a -> translate(a, x, y), g.components), copy(g.attributes))
end
function translate(rect::Rect2{T}, x::Real, y::Real) where {T}
return Rect2{T}(rect.origin + Vec2{T}(x, y), rect.widths)
end
function translate(circle::Circle{T}, x::Real, y::Real) where {T}
return Circle(circle.center + Vec2{T}(x, y), circle.r)
end
function translate(polygon::Polygon{2,T}, x::Real, y::Real) where {T}
return Polygon([v + Vec2{T}(x, y) for v in coordinates(polygon)])
end
"Scale by a horizontal factor `x` and vertical factor `y` around a point `c`."
function scale(g::BasicGraphic, x::Real, y::Real=x, c=centroid(g))
return BasicGraphic(scale(g.shape, x, y, c), copy(g.attributes))
end
function scale(g::MarkerGraphic, x::Real, y::Real=x, c=centroid(g))
return MarkerGraphic(g.marker, g.x, g.y, g.w * x, g.h * y, copy(g.attributes))
end
function scale(g::TextGraphic, x::Real, y::Real=x, c=centroid(g))
return TextGraphic(g.str, g.x, g.y, g.fontsize .* (x, y), copy(g.attributes))
end
function scale(g::MultiGraphic, x::Real, y::Real=x, c=centroid(g))
return MultiGraphic(map(a -> scale(a, x, y, c), g.components), copy(g.attributes))
end
function scale(rect::Rect2{T}, x::Real, y::Real=x, c=centroid(r)) where {T}
origin = Vec2{T}(c[1] - x * (c[1] - rect.origin[1]),
c[2] - y * (c[2] - rect.origin[2]))
widths = Vec2{T}(x * rect.widths[1], y * rect.widths[2])
return Rect2{T}(origin, widths)
end
function scale(circle::Circle{T}, x::Real, y::Real=x, c=centroid(circle)) where {T}
if x != y
polygon = Polygon(Point2{T}.(coordinates(circle)))
return scale(polygon, x, y, c)
end
center = Point2{T}(c[1] - x * (c[1] - circle.center[1]),
c[2] - y * (c[2] - circle.center[2]))
return Circle{T}(center, x * circle.r)
end
function scale(polygon::Polygon{2,T}, x::Real, y::Real=x, c=centroid(polygon)) where {T}
vertices = [Point2{T}(c[1] - x * (c[1] - v[1]),
c[2] - y * (c[2] - v[2])) for v in coordinates(polygon)]
return Polygon(vertices)
end
"Rotate a graphic by θ radians around a point `c`."
function rotate(g::BasicGraphic, θ::Real, c=centroid(g))
return BasicGraphic(rotate(g.shape, θ, c), copy(g.attributes))
end
function rotate(g::MarkerGraphic, θ::Real, c=nothing)
attributes = copy(g.attributes)
attributes[:rotations] = get(attributes, :rotations, 0) + θ
return MarkerGraphic(g.marker, g.x, g.y, g.w, g.h, attributes)
end
function rotate(g::TextGraphic, θ::Real, c=nothing)
attributes = copy(g.attributes)
attributes[:rotation] = get(attributes, :rotation, 0) + θ
return TextGraphic(g.str, g.x, g.y, g.fontsize, attributes)
end
function rotate(g::MultiGraphic, θ::Real, c=centroid(g))
return MultiGraphic(map(a -> rotate(a, θ, c), g.components), copy(g.attributes))
end
function rotate(rect::Rect2{T}, θ::Real, c=centroid(rect)) where {T}
vertices = Point2{T}.(coordinates(rect))[[1, 2, 4, 3]]
polygon = Polygon(vertices)
return rotate(polygon, θ, c)
end
function rotate(circle::Circle{T}, θ::Real, c=centroid(circle)) where {T}
if θ == 0 || c == circle.center
return circle
end
center = Point2{T}(c[1] + (circle.center[1] - c[1]) * cos(θ)
- (circle.center[2] - c[2]) * sin(θ),
c[2] + (circle.center[1] - c[1]) * sin(θ)
+ (circle.center[2] - c[2]) * cos(θ))
return Circle{T}(center, circle.r)
end
function rotate(polygon::Polygon{2,T}, θ::Real, c=centroid(polygon)) where {T}
vertices = [Point2{T}(c[1] + (v[1]-c[1]) * cos(θ) - (v[2]-c[2]) * sin(θ),
c[2] + (v[1]-c[1]) * sin(θ) + (v[2]-c[2]) * cos(θ))
for v in coordinates(polygon)]
return Polygon(vertices)
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 2354 | using GeometryBasics: GeometryBasics, Circle, Rect, Polygon, coordinates
export BasicGraphic, MarkerGraphic, TextGraphic, MultiGraphic
abstract type Graphic end
"""
BasicGraphic(shape; attributes...)
Basic graphic type, containing a primitive shape and a dictionary of attributes.
"""
struct BasicGraphic{T} <: Graphic
shape::T
attributes::Dict{Symbol, Any}
end
BasicGraphic(shape; attributes...) =
BasicGraphic(shape, Dict{Symbol,Any}(attributes...))
"""
MarkerGraphic(marker, x, y, [w=1.0, h=w]; attributes...)
A marker graphic with a given position and size, rendered using `scatter`
with the corresponding marker type.
"""
struct MarkerGraphic{T} <: Graphic
marker::T
x::Float64
y::Float64
w::Float64
h::Float64
attributes::Dict{Symbol, Any}
end
function MarkerGraphic(
marker::T, x::Real=0.0, y::Real=0.0, w::Real=1.0, h::Real=w;
attributes...
) where {T}
return MarkerGraphic{T}(marker, x, y, w, h, Dict{Symbol,Any}(attributes...))
end
"""
TextGraphic(str, x, y, [fontsize]; attributes...)
A text graphic with a given position and [fontsize], rendered using the `text`
plotting command.
"""
struct TextGraphic <: Graphic
str::String
x::Float64
y::Float64
fontsize::Vec2f
attributes::Dict{Symbol, Any}
end
function TextGraphic(
str::AbstractString, x::Real=0.0, y::Real=0.0, fontsize=1/length(str);
attributes...
)
if fontsize isa Real
fontsize = Vec2f(fontsize, fontsize)
elseif fontsize isa Tuple
fontsize = Vec2f(fontsize...)
end
return TextGraphic(str, x, y, fontsize, Dict{Symbol,Any}(attributes...))
end
"""
MultiGraphic(graphics; attributes...)
Composite graphic type, containing a tuple of graphics in depth-order and a
dictionary of attributes.
"""
struct MultiGraphic{Gs <: Tuple} <: Graphic
components::Gs
attributes::Dict{Symbol, Any}
end
MultiGraphic(graphics::Tuple; attributes...) =
MultiGraphic(graphics, Dict{Symbol,Any}(attributes...))
MultiGraphic(graphics::AbstractVector; attributes...) =
MultiGraphic(Tuple(graphics), Dict{Symbol,Any}(attributes...))
MultiGraphic(graphics::Graphic...; attributes...) =
MultiGraphic(graphics, Dict{Symbol,Any}(attributes...))
include("recipes.jl")
include("colors.jl")
include("geometry.jl")
include("shapes.jl")
include("prefabs.jl")
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 7786 | export GemGraphic, LockedDoorGraphic, KeyGraphic
export BoxGraphic, QuestionBoxGraphic
export RobotGraphic, HumanGraphic
export CityGraphic
"""
GemGraphic(x=0.0, y=0.0, size=1.0, sides=6, aspect=0.75;
color=:royalblue, strokewidth=1.0, kwargs...)
Gem graphic, consisting of a N-gon and a smaller N-gon inside it.
"""
function GemGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0, sides::Int=6, aspect::Real=0.75;
color=:royalblue, strokewidth=1.0, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
outer = NgonShape(x, y, size, sides; color=color, strokewidth=strokewidth)
outer = scale(outer, aspect*0.3, 0.3)
color = lighten(color, 0.5)
inner = NgonShape(x, y, size, sides; color=color)
inner = scale(inner, aspect*0.18, 0.18)
return MultiGraphic(outer, inner; kwargs...)
end
"""
LockedDoorGraphic(x=0.0, y=0.0, size=1.0;
color=:gray, strokewidth=1.0, kwargs...)
Locked door graphic, consisting of square with a keyhole in it.
"""
function LockedDoorGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:gray, strokewidth=1.0, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
bg = SquareShape(x, y, size; color=color, strokewidth=strokewidth)
color = lighten(color, 0.1)
fg = SquareShape(x, y, 0.85*size; color=color, strokewidth=strokewidth)
hole1 = NgonShape(x, y+0.1*size, 0.10*size, 16; color=:black)
hole2 = TriangleShape(x, y-0.1*size, size; color=:black)
hole2 = scale(hole2, 0.125, -0.25)
return MultiGraphic(bg, fg, hole1, hole2; kwargs...)
end
"""
KeyGraphic(x=0.0, y=0.0, size=1.0;
color=:goldenrod1, shadow_color=:black, kwargs...)
Key graphic, consisting of a key with a handle and two teeth.
"""
function KeyGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:goldenrod1, shadow_color=:black, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
shadow_color = shadow_color isa Observable ?
to_color_obs(shadow_color) : to_color(shadow_color)
handle = NgonShape(-0.35, 0.0, 0.4, 8)
blade = RectShape(0.375, 0.0, 0.75, 0.2)
tooth1 = RectShape(0.4, -0.2, 0.1, 0.2)
tooth2 = RectShape(0.6, -0.2, 0.1, 0.2)
key = MultiGraphic(handle, blade, tooth1, tooth2; color=color)
shadow = translate(key, 0.025, -0.025)
shadow.attributes[:color] = shadow_color
graphic = MultiGraphic(shadow, key; kwargs...)
return scale(translate(graphic, x, y), 0.5*size)
end
"""
BoxGraphic(x=0.0, y=0.0, size=1.0;
color=:burlywood3, is_open=false, kwargs...)
Cardboard box graphic, consisting of a box with a lid.
"""
function BoxGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:burlywood3, is_open::Bool=false, kwargs...
)
size = size * 0.9
lid_color = lighten(color, 0.3)
if is_open
lid = RectShape(x-0.37*size, y+0.02*size, 0.825*size, 0.2*size;
color=lid_color)
lid = rotate(lid, 11*π/24)
else
lid = RectShape(x, y+0.3*size, 0.825*size, 0.2*size; color=lid_color)
lid = rotate(lid, 0.0)
end
box = RectShape(x, y-0.05*size, 0.75*size, 0.65*size; color=color)
return MultiGraphic(box, lid; kwargs...)
end
"""
QuestionBoxGraphic(x=0.0, y=0.0, size=1.0;
color=:burlywood3, text_color=:white,
is_open=false, kwargs...)
Question box graphic, consisting of a box with a lid and question mark.
"""
function QuestionBoxGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:burlywood3, text_color=:white, is_open::Bool=false, kwargs...
)
size = size * 0.9
lid_color = lighten(color, 0.3)
if is_open
lid = RectShape(x-0.37*size, y+0.02*size, 0.825*size, 0.2*size;
color=lid_color)
lid = rotate(lid, 11*π/24)
else
lid = RectShape(x, y+0.3*size, 0.825*size, 0.2*size; color=lid_color)
lid = rotate(lid, 0.0)
end
box = RectShape(x, y-0.05*size, 0.75*size, 0.65*size; color=color)
question = TextGraphic("?", x, y-0.075*size; color=text_color,
fontsize=0.5*size, font=:bold)
return MultiGraphic(box, lid, question; kwargs...)
end
"""
RobotGraphic(x=0.0, y=0.0, size=1.0;
color=:slategray, kwargs...)
Robot prefab character graphic, consisting of a semi-circular head with an
antenna, two arms, a body and a wheel.
"""
function RobotGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:slategray, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
light_color = lighten(color, 0.4)
dark_color = darken(color, 0.3)
tip = NgonShape(x, y+0.325*size, 0.025*size, 16)
antenna = RectShape(x, y+0.31*size, 0.05*size, 0.03*size)
head = NgonShape(x, y+0.05*size, 0.25*size, 32)
face = NgonShape(x, y+0.05*size, 0.2*size, 32; color=light_color)
eye1 = SquareShape(x-0.1*size, y+0.1*size, 0.05*size)
eye2 = SquareShape(x+0.1*size, y+0.1*size, 0.05*size)
wheel = NgonShape(x, y-0.325*size, 0.10*size, 32; color=dark_color)
body = RectShape(x, y-0.15*size, 0.5*size, 0.4*size;)
shoulder1 = RectShape(x+0.28125*size, y, 0.0625*size, 0.05*size)
shoulder2 = RectShape(x-0.28125*size, y, 0.0625*size, 0.05*size)
arm1 = RectShape(x+0.2875*size, y-0.125*size, 0.05*size, 0.2*size)
arm2 = RectShape(x-0.2875*size, y-0.125*size, 0.05*size, 0.2*size)
return MultiGraphic(tip, antenna, head, face, eye1, eye2,
wheel, body, shoulder1, shoulder2,
arm1, arm2; color=color, kwargs...)
end
"""
HumanGraphic(x=0.0, y=0.0, size=1.0;
color=:black, kwargs...)
Human character graphic, consisting of a circular head, and a trapezoidal torso,
two-segment arms, and legs.
"""
function HumanGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:black, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
head = NgonShape(x, y+0.205*size, 0.15*size, 32)
eye1 = NgonShape(x-0.1*size, y+0.22*size, 0.025*size, 16; color=:white)
eye2 = NgonShape(x+0.1*size, y+0.22*size, 0.025*size, 16; color=:white)
body = TrapezoidShape(x, y-0.075*size, 0.15*size, 0.3*size, 0.25*size)
u_arm = TriangleShape(x, y-0.03*size, 0.1*size)
u_arm1 = rotate(scale(translate(u_arm, -0.14*size, 0.0), 0.5, 1), π-1.1*π/6)
u_arm2 = rotate(scale(translate(u_arm, 0.14*size, 0.0), 0.5, 1), π+1.1*π/6)
l_arm = TrapezoidShape(x, y, size/12, 0.02*size, 0.12*size)
l_arm1 = rotate(translate(l_arm, -0.202*size, -0.132*size), -1.1*π/6)
l_arm2 = rotate(translate(l_arm, +0.202*size, -0.132*size), 1.1*π/6)
leg = TrapezoidShape(x, y, size/12, 0.02*size, 0.12*size)
leg1 = translate(leg, -0.102*size, -0.268*size)
leg2 = translate(leg, 0.102*size, -0.268*size)
human = MultiGraphic(
body, head, eye1, eye2, u_arm1, u_arm2,
l_arm1, l_arm2, leg1, leg2; color=color, kwargs...
)
return scale(human, 1.2, 1.2)
end
"""
CityGraphic(x=0.0, y=0.0, size=1.0;
color=:grey, kwargs...)
City graphic, made of three rectangles with slightly different shading.
"""
function CityGraphic(
x::Real=0.0, y::Real=0.0, size::Real=1.0;
color=:grey, kwargs...
)
color = color isa Observable ? to_color_obs(color) : to_color(color)
block1 = RectShape(x+0.00, y, 0.30, 0.75, color=color)
block2 = RectShape(x-0.15, y-0.075, 0.30, 0.60, color=darken(color, 0.2))
block3 = RectShape(x+0.15, y-0.1875, 0.30, 0.375, color=darken(color, 0.4))
city = MultiGraphic(block1, block2, block3; kwargs...)
return scale(city, size)
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 3183 | ## Makie plotting recipes for graphics ##
@recipe(GraphicPlot, graphic) do scene
Makie.Attributes(
cycle=[:color],
colormap=colorschemes[:vibrant]
)
end
function Makie.plot!(plt::GraphicPlot{<:Tuple{BasicGraphic}})
graphic = plt[:graphic]
shape = @lift $graphic.shape
attributes = Dict(plt.attributes)
local_attributes = Dict{Symbol, Any}(
k => graphic[].attributes[k] isa Observable ?
graphic[].attributes[k] : @lift($graphic.attributes[k])
for k in keys(graphic[].attributes)
)
attributes = merge!(attributes, local_attributes)
if !haskey(attributes, :shading)
attributes[:shading] = isdefined(Makie.MakieCore, :NoShading) ?
Makie.MakieCore.NoShading : false
end
# Plot fill
mesh!(plt, shape; attributes...)
# Plot stroke if width is greater than 0
visible = get!(attributes, :visible, Observable(true))
strokewidth = get!(attributes, :strokewidth, Observable(0))
attributes[:visible] = @lift $visible && $strokewidth > 0
attributes[:color] = get(attributes, :strokecolor, :black)
attributes[:linewidth] = strokewidth
if haskey(attributes, :shading)
delete!(attributes, :shading)
end
lines!(plt, shape; attributes...)
end
function Makie.plot!(plt::GraphicPlot{<:Tuple{MarkerGraphic}})
graphic = plt[:graphic]
attributes = Dict(plt.attributes)
local_attributes = Dict{Symbol, Any}(
k => graphic[].attributes[k] isa Observable ?
graphic[].attributes[k] : @lift($graphic.attributes[k])
for k in keys(graphic[].attributes)
)
attributes = merge!(attributes, local_attributes)
# Plot marker
marker = @lift $graphic.marker
position = @lift Point2f($graphic.x, $graphic.y)
size = @lift Vec2f($graphic.w, $graphic.h)
scatter!(plt, position; marker=marker, markersize=size,
markerspace=:data, attributes...)
end
function Makie.plot!(plt::GraphicPlot{<:Tuple{TextGraphic}})
graphic = plt[:graphic]
attributes = Dict(plt.attributes)
local_attributes = Dict{Symbol, Any}(
k => graphic[].attributes[k] isa Observable ?
graphic[].attributes[k] : @lift($graphic.attributes[k])
for k in keys(graphic[].attributes)
)
attributes = merge!(attributes, local_attributes)
# Plot text
str = @lift $graphic.str
text!(plt, @lift($graphic.x), @lift($graphic.y); text=str,
fontsize=@lift($graphic.fontsize), markerspace=:data,
align=(:center, :center), attributes...)
end
function Makie.plot!(plt::GraphicPlot{<:Tuple{MultiGraphic}})
graphic = plt[:graphic]
attributes = Dict(plt.attributes)
local_attributes = Dict{Symbol, Any}(
k => graphic[].attributes[k] isa Observable ?
graphic[].attributes[k] : @lift($graphic.attributes[k])
for k in keys(graphic[].attributes)
)
attributes = merge!(attributes, local_attributes)
n_components = length(graphic[].components)
components = [@lift($graphic.components[i]) for i in 1:n_components]
for subgraphic in components
graphicplot!(plt, subgraphic; attributes...)
end
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 2347 | ## Basic shapes and primitives ##
"Construct a circle centered at `x` and `y` with radius `r`."
CircleShape(x::Real, y::Real, r::Real; attributes...) =
BasicGraphic(Circle(Point2{Float64}(x, y), r); attributes...)
"Construct a square centered at `x` and `y` with side length `l`."
SquareShape(x::Real, y::Real, l::Real; attributes...) =
BasicGraphic(Rect(x-l/2, y-l/2, l, l); attributes...)
"Construct a rectangle centered at `x` and `y` with width `w` and height `h`."
RectShape(x::Real, y::Real, w::Real, h::Real; attributes...) =
BasicGraphic(Rect(x-w/2, y-h/2, w, h); attributes...)
"Construct a `n`-sided regular polygon centered at `x` and `y` with radius `1`."
function NgonShape(x::Real, y::Real, r::Real, n::Int; attributes...)
points = collect(coordinates(Circle(Point2{Float64}(x, y), r), n+1))
resize!(points, n)
BasicGraphic(Polygon(points); attributes...)
end
"Construct a triangle centered at `x` and `y` with radius `r`."
TriangleShape(x::Real, y::Real, r::Real; attributes...) =
NgonShape(x, y, r, 3; attributes...)
"Construct a pentagon centered at `x` and `y` with radius `r`."
PentagonShape(x::Real, y::Real, r::Real; attributes...) =
NgonShape(x, y, r, 5; attributes...)
"Construct a hexagon centered at `x` and `y` with radius `r`."
HexagonShape(x::Real, y::Real, r::Real; attributes...) =
NgonShape(x, y, r, 6; attributes...)
"Construct a heptagon centered at `x` and `y` with radius `r`."
HeptagonShape(x::Real, y::Real, r::Real; attributes...) =
NgonShape(x, y, r, 7; attributes...)
"Construct an octagon centered at `x` and `y` with radius `r`."
OctagonShape(x::Real, y::Real, r::Real; attributes...) =
NgonShape(x, y, r, 8; attributes...)
"Construct a polygon from a list of vertices."
PolygonShape(vertices; attributes) =
BasicGraphic(Polygon(Point2{Float64}.(vertices)); attributes...)
"""
Construct a trapezoid at `x` and `y` with top and bottom width `a`, bottom width
`b`, and height `h`. The top can be shifted by an `offset` (zero by default).
"""
function TrapezoidShape(
x::Real, y::Real, a::Real, b::Real, h::Real, offset::Real=0.0;
attributes...
)
vertices = [
Point2(x-a/2+offset, y+h/2), Point2(x+a/2+offset, y+h/2),
Point2(x+b/2, y-h/2), Point2(x-b/2, y-h/2)
]
BasicGraphic(Polygon(vertices); attributes...)
end | PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 70 | include("gridworld/gridworld.jl")
include("graphworld/graphworld.jl")
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 6018 | function anim_initialize!(
canvas::Canvas, renderer::GraphworldRenderer, domain::Domain, state::State;
callback=nothing, overlay=nothing, kwargs...
)
if canvas.state === nothing
render_state!(canvas, renderer, domain, state; kwargs...)
end
# Run callbacks
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
return canvas
end
function anim_transition!(
canvas::Canvas, renderer::GraphworldRenderer, domain::Domain,
state::State, action::Term = PDDL.no_op, t::Int = 1;
options...
)
options = merge(renderer.anim_options, options)
transition = get(options, :transition, StepTransition())
return anim_transition!(
transition, canvas, renderer, domain, state, action, t;
options...
)
end
function anim_transition!(
trans::StepTransition,
canvas::Canvas, renderer::GraphworldRenderer, domain::Domain,
state::State, action::Term = PDDL.no_op, t::Int = 1;
callback=nothing, overlay=nothing, options...
)
# Update canvas with new state
canvas.state[] = state
# Run callback
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
return canvas
end
function anim_transition!(
trans::LinearTransition,
canvas::Canvas, renderer::GraphworldRenderer, domain::Domain,
state::State, action::Term = PDDL.no_op, t::Int = 1;
callback=nothing, overlay=nothing, options...
)
options = merge(renderer.anim_options, options)
# Copy starting node positions
node_start_pos = copy(canvas.observables[:node_pos][])
# Update canvas with new state
canvas.state[] = state
# Copy ending node positions
node_stop_pos = copy(canvas.observables[:node_pos][])
# Compute differences
node_diffs = node_stop_pos .- node_start_pos
# Temporarily disconnect graph layout from node positions
layout = canvas.observables[:layout][]
canvas.observables[:layout][] = node_start_pos
# Compute number of frames
move_speed = get(options, :move_speed, nothing)
if move_speed === nothing
frames_per_step = get(options, :frames_per_step, 24)
else
max_dist = maximum(GeometryBasics.norm.(node_diffs))
frames_per_step = round(Int, max_dist / move_speed)
end
# Linearly interpolate between start and stop positions
for t in 1:frames_per_step
node_pos = node_start_pos .+ node_diffs .* t / frames_per_step
canvas.observables[:layout][] = node_pos
# Run callbacks
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
end
# Reconnect graph layout to node positions
canvas.observables[:layout].val = layout
return canvas
end
function anim_transition!(
trans::ManhattanTransition,
canvas::Canvas, renderer::GraphworldRenderer, domain::Domain,
state::State, action::Term = PDDL.no_op, t::Int = 1;
callback=nothing, overlay=nothing, options...
)
options = merge(renderer.anim_options, options)
# Copy starting node positions
node_start_pos = copy(canvas.observables[:node_pos][])
# Update canvas with new state
canvas.state[] = state
# Copy ending node positions
node_stop_pos = copy(canvas.observables[:node_pos][])
# Temporarily disconnect graph layout from node positions
layout = canvas.observables[:layout][]
canvas.observables[:layout][] = node_start_pos
# Compute node displacements for each direction
diffs_per_dir = Vector{typeof(node_start_pos)}()
node_pos = node_start_pos
for (dir, stop_early) in zip(trans.order, trans.stop_early)
# Project node displacements onto direction
node_diffs = node_stop_pos .- node_start_pos
node_diffs = map(node_diffs) do diff
x, y = diff
if dir == :up
return Point2(zero(x), y > 0 ? y : zero(y))
elseif dir == :down
return Point2(zero(x), y < 0 ? y : zero(y))
elseif dir == :left
return Point2(x < 0 ? x : zero(x), zero(y))
elseif dir == :right
return Point2(x > 0 ? x : zero(x), zero(y))
elseif dir == :horizontal
return Point2(x, zero(y))
elseif dir == :vertical
return Point2(zero(x), y)
else
error("Invalid direction: $dir")
end
end
# Check if any nodes have moved in this direction
moved = any((d[1] != 0 || d[2] != 0) for d in node_diffs)
!moved && continue
# Add node displacements to list
push!(diffs_per_dir, node_diffs)
node_pos = node_pos + node_diffs
stop_early && break
end
# Compute number of frames per direction
move_speed = get(options, :move_speed, nothing)
n_dirs = length(diffs_per_dir)
if move_speed === nothing
frames_per_step = get(options, :frames_per_step, 24)
frames_per_dir = fill(frames_per_step ÷ n_dirs, n_dirs)
frames_per_dir[end] += frames_per_step % n_dirs
else
frames_per_dir = map(diffs_per_dir) do diffs
max_dist = maximum(GeometryBasics.norm.(diffs); init=0.0)
return round(Int, max_dist / move_speed)
end
end
# Iterate over node displacements per direction
for (node_diffs, frames) in zip(diffs_per_dir, frames_per_dir)
# Interpolate nodes along direction
for t in 1:frames
if t == frames
node_pos = node_start_pos .+ node_diffs
else
node_pos = node_start_pos .+ node_diffs .* t / frames
end
canvas.observables[:layout][] = node_pos
# Run callbacks
overlay !== nothing && overlay(canvas)
callback !== nothing && callback(canvas)
end
node_start_pos += node_diffs
end
# Reconnect graph layout to node positions
canvas.observables[:layout].val = layout
return canvas
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 8371 | export GraphworldRenderer, BlocksworldRenderer
include("layouts.jl")
"""
GraphworldRenderer(; options...)
Customizable renderer for domains with fixed locations and movable objects
connected in a graph. The layout of the graph can be controlled with the
`graph_layout` option, which takes a function that returns an `AbstractLayout`
given the number of locations.
By default, the graph is laid out using the `StressLocSpringMov` layout, which
arranges the first `n_locs` nodes via stress minimization, and uses
spring/repulsion for the remaining nodes.
# General options
$(TYPEDFIELDS)
"""
@kwdef mutable struct GraphworldRenderer <: Renderer
"Default figure resolution, in pixels."
resolution::Tuple{Int, Int} = (800, 800)
"Function `n_locs -> (graph -> positions)` that returns an AbstractLayout."
graph_layout::Function = n_locs -> StressLocSpringMov(n_locs=n_locs)
"Whether the edges between locations are directed."
is_loc_directed::Bool = false
"Whether the edges between movable objects are directed."
is_mov_directed::Bool = false
"Whether there are edges between movable objects."
has_mov_edges::Bool = false
"PDDL objects that correspond to fixed locations."
locations::Vector{Const} = Const[]
"PDDL object types that correspond to fixed locations."
location_types::Vector{Symbol} = Symbol[]
"PDDL objects that correspond to movable objects."
movables::Vector{Const} = Const[]
"PDDL object types that correspond to movable objects."
movable_types::Vector{Symbol} = Symbol[]
"Function `(dom, s, l1, l2) -> Bool` that checks if `l1` connects to `l2`."
loc_edge_fn::Function = (d, s, l1, l2) -> l1 != l2
"Function `(dom, s, l1, l2) -> String` that labels edge `(l1, l2)`."
loc_edge_label_fn::Function = (d, s, l1, l2) -> ""
"Function `(dom, s, obj, loc) -> Bool` that checks if `mov` is at `loc`."
mov_loc_edge_fn::Function = (d, s, mov, loc) -> false
"Function `(dom, s, obj, loc) -> String` that labels edge `(mov, loc)`."
mov_loc_edge_label_fn::Function = (d, s, mov, loc) -> ""
"Function `(dom, s, m1, m2) -> Bool` that checks if `m1` connects to `m2`."
mov_edge_fn::Function = (d, s, m1, m2) -> false
"Function `(dom, s, m1, m2) -> String` that labels edge `(m1, m2)`."
mov_edge_label_fn::Function = (d, s, o1, o2) -> ""
"Location object renderers, of the form `(domain, state, loc) -> Graphic`."
loc_renderers::Dict{Const, Function} = Dict{Const, Function}()
"Movable object renderers, of the form `(domain, state, obj) -> Graphic`."
mov_renderers::Dict{Const, Function} = Dict{Const, Function}()
"Per-type location renderers, of the form `(domain, state, loc) -> Graphic`."
loc_type_renderers::Dict{Symbol, Function} = Dict{Symbol, Function}()
"Per-type movable renderers, of the form `(domain, state, obj) -> Graphic`."
mov_type_renderers::Dict{Symbol, Function} = Dict{Symbol, Function}()
"Default options for graph rendering, passed to the `graphplot` recipe."
graph_options::Dict{Symbol, Any} = Dict{Symbol, Any}(
:node_size => 0.05,
:node_attr => (markerspace=:data,),
:nlabels_fontsize => 20,
:nlabels_align => (:center, :center),
:elabels_fontsize => 16,
)
"Default display options for axis."
axis_options::Dict{Symbol, Any} = Dict{Symbol, Any}(
:aspect => 1,
:autolimitaspect => 1,
:hidedecorations => true
)
"Default options for state rendering."
state_options::Dict{Symbol, Any} =
default_state_options(GraphworldRenderer)
"Default options for animation rendering."
anim_options::Dict{Symbol, Any} = Dict{Symbol, Any}()
end
function new_canvas(renderer::GraphworldRenderer)
figure = Figure()
resize!(figure.scene, renderer.resolution)
return Canvas(figure)
end
include("state.jl")
include("animate.jl")
# Add documentation for auxiliary options
Base.with_logger(Base.NullLogger()) do
@doc """
$(@doc GraphworldRenderer)
# State options
These options can be passed as keyword arguments to [`render_state`](@ref):
$(Base.doc(default_state_options, Tuple{Type{GraphworldRenderer}}))
"""
GraphworldRenderer
end
"""
BlocksworldRenderer(; options...)
Specialization of [`GraphworldRenderer`](@ref) for the blocksworld domain, which
uses a custom [`BlocksworldLayout`](@ref) and default renderers for blocks
and tables. The following blocksworld-specific options are supported:
# Options
- `block_type::Symbol`: PDDL type of blocks, defaults to `:block`
- `block_width::Real`: Width of blocks, defaults to `1.0`
- `block_height::Real`: Height of blocks, defaults to `1.0`
- `block_gap::Real`: Gap between blocks, defaults to `0.5`
- `table_height::Real`: Height of table, defaults to `block_height`
- `gripper_height::Real`: Height of blocks when they are picked up. Defaults
to slightly above the tallest block tower.
- `block_colors`: Colorscheme for blocks, defaults to a discretization of the
`plasma` colorscheme.
- `block_renderer`: Renderer for blocks, defaults to a colored square with the
block name as white text in the center.
"""
function BlocksworldRenderer(;
block_type::Symbol = :block,
block_width::Real = 1.0,
block_height::Real = 1.0,
block_gap::Real = 0.5,
table_height::Real = block_height,
gripper_height::Union{Real, Nothing} = nothing,
graph_layout = n_locs -> PDDLViz.BlocksworldLayout(;
n_locs, block_width, block_height, block_gap,
table_height, gripper_height
),
block_colors = Makie.colorschemes[:plasma][1:8:256],
block_renderer = (d, s, obj) -> begin
return MultiGraphic(
SquareShape(
0.0, 0.0, 1.0,
color=block_colors[mod(hash(obj.name), length(block_colors))+1],
strokewidth=2.0
),
TextGraphic(
string(obj.name), 0, 0, 3/4*length(string(obj.name)),
font=:bold, color=:white, strokecolor=:black, strokewidth=1.0
)
)
end,
table_renderer = (d, s, loc) -> begin
n_blocks = length(PDDL.get_objects(s, :block))
width = (block_width + block_gap) * n_blocks
return RectShape(0.0, 0.0, width, 1.0, color=:grey60, strokewidth=2.0)
end,
loc_edge_fn = (d, s, a, b) -> false,
mov_loc_edge_fn = (d, s, x, loc) -> begin
if x == loc
s[Compound(:ontable, [x])]
elseif loc.name == :gripper
s[Compound(:holding, [x])]
else
false
end
end,
mov_edge_fn = (d, s, x, y) -> s[Compound(:on, [x, y])],
is_loc_directed = true,
is_mov_directed = true,
has_mov_edges = true,
locations = [pddl"(table)", pddl"(gripper)", pddl"(ceiling)"],
location_types = [block_type],
movable_types = [block_type],
loc_renderers = Dict{Const, Function}(
locations[1] => table_renderer
),
mov_type_renderers = Dict{Symbol, Function}(
block_type => block_renderer
),
graph_options = Dict{Symbol, Any}(
:arrow_show => false,
:node_size => 0.0,
:edge_width => 0.0,
:node_attr => (markerspace=:data,),
),
axis_options = Dict{Symbol, Any}(
:aspect => DataAspect(),
:xautolimitmargin => (0.0, 0.0),
:limits => (0.0, nothing, 0.0, nothing),
:hidedecorations => true
),
state_options = Dict{Symbol, Any}(
:show_location_labels => false,
:show_movable_labels => false,
:show_edge_labels => false,
:show_location_graphics => true,
:show_movable_graphics => true
),
anim_options = Dict{Symbol, Any}(
:transition => ManhattanTransition(
order = [:up, :horizontal, :down],
stop_early = [true, false, false]
),
:move_speed => 0.4
),
kwargs...
)
return GraphworldRenderer(;
graph_layout,
is_loc_directed,
is_mov_directed,
has_mov_edges,
locations,
location_types,
movable_types,
loc_edge_fn,
mov_loc_edge_fn,
mov_edge_fn,
loc_renderers,
mov_type_renderers,
graph_options,
axis_options,
state_options,
anim_options,
kwargs...
)
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 5271 | using NetworkLayout: AbstractLayout
"""
StressLocSpringMov(; kwargs...)(adj_matrix)
Returns a layout that first places the first `n_locs` nodes using stress
minimization, then places the remaining nodes using spring/repulsion.
## Keyword Arguments
- `dim = 2`, `Ptype = Float64`: Dimension and output type.
- `n_locs = 0`: Number of nodes to place using stress minimization.
- `stress_kwargs = Dict{Symbol, Any}()`: Keyword arguments for `Stress`.
- `spring_kwargs = Dict{Symbol, Any}(:C => 0.3)`: Keyword arguments for `Spring`.
"""
struct StressLocSpringMov{Dim, Ptype} <: AbstractLayout{Dim, Ptype}
n_locs::Int
stress_kwargs::Dict{Symbol, Any}
spring_kwargs::Dict{Symbol, Any}
end
function StressLocSpringMov(;
dim = 2,
Ptype = Float64,
n_locs = 0,
stress_kwargs = Dict{Symbol, Any}(:seed => 1),
spring_kwargs = Dict{Symbol, Any}(:C => 0.3, :seed => 1)
)
return StressLocSpringMov{dim, Ptype}(n_locs, stress_kwargs, spring_kwargs)
end
function NetworkLayout.layout(
algo::StressLocSpringMov{Dim, Ptype}, adj_matrix::AbstractMatrix
) where {Dim, Ptype}
n_nodes = NetworkLayout.assertsquare(adj_matrix)
stress = Stress(;dim=Dim, Ptype=Ptype, algo.stress_kwargs...)
loc_positions = stress(adj_matrix[1:algo.n_locs, 1:algo.n_locs])
init_positions = resize!(copy(loc_positions), n_nodes)
for i in algo.n_locs+1:n_nodes
for j in 1:algo.n_locs
adj_matrix[i, j] == 0 && continue
init_positions[i] = loc_positions[j]
break
end
end
spring = Spring(;dim=Dim, Ptype=Ptype, pin=loc_positions,
initialpos=init_positions, algo.spring_kwargs...)
return spring(adj_matrix)
end
"""
BlocksworldLayout(; kwargs...)
Layout for blocksworld problems. Blocks are stacked bottom-up from a table,
except for the block that is currently held by the gripper.
## Keyword Arguments
- `Ptype = Float64`: Type of coordinates.
- `n_locs = 3`: Number of locations, including the table, gripper, ceiling,
and locations of the base blocks.
- `block_width = 1.0`: Width of each block.
- `block_height = 1.0`: Height of each block.
- `block_gap = 0.5`: Horizontal gap between blocks.
- `table_height = block_height`: Height of the table.
- `gripper_height`: Height of the gripper.
"""
struct BlocksworldLayout{Ptype} <: AbstractLayout{2, Ptype}
n_locs::Int
block_width::Ptype
block_height::Ptype
block_gap::Ptype
table_height::Ptype
gripper_height::Union{Ptype, Nothing}
end
function BlocksworldLayout(;
Ptype = Float64,
n_locs = 3,
block_width = Ptype(1.0),
block_height = Ptype(1.0),
block_gap = Ptype(0.5),
table_height = block_height,
gripper_height = nothing
)
return BlocksworldLayout{Ptype}(
n_locs,
block_width,
block_height,
block_gap,
table_height,
gripper_height
)
end
function NetworkLayout.layout(
algo::BlocksworldLayout{Ptype}, adj_matrix::AbstractMatrix
) where {Ptype}
n_nodes = NetworkLayout.assertsquare(adj_matrix)
n_blocks = n_nodes - algo.n_locs
graph = SimpleDiGraph(adj_matrix)
positions = Vector{Point2{Ptype}}(undef, n_nodes)
# Set table location
x_mid = n_blocks * (algo.block_width + algo.block_gap) / Ptype(2)
table_pos = Point2{Ptype}(x_mid, algo.table_height / Ptype(2))
positions[1] = table_pos
# Set ceiling location
ceil_height = algo.table_height + Ptype(n_blocks + 2.5) * algo.block_height
if !isnothing(algo.gripper_height)
ceil_height = max(ceil_height, algo.gripper_height)
end
ceil_pos = Point2{Ptype}(x_mid, ceil_height)
positions[3] = ceil_pos
# Compute base locations
x_start = (algo.block_width + algo.block_gap) / Ptype(2)
for i in 1:n_blocks
x = (i - 1) * (algo.block_width + algo.block_gap) + x_start
y = algo.table_height - algo.block_height / Ptype(2)
positions[3 + i] = Point2{Ptype}(x, y)
end
# Compute block locations for towers rooted at each base
max_tower_height = algo.table_height - algo.block_height / Ptype(2)
for base in 4:algo.n_locs
stack = [(i, base) for i in inneighbors(graph, base)]
while !isempty(stack)
(node, parent) = pop!(stack)
x, y = positions[parent]
y += algo.block_height
max_tower_height = max(y, max_tower_height)
positions[node] = Point2{Ptype}(x, y)
for child in inneighbors(graph, node)
push!(stack, (child, node))
end
end
end
if isnothing(algo.gripper_height)
# Automatically determine gripper height
gripper_height = max_tower_height + Ptype(1.5) * algo.block_height
if !isempty(inneighbors(graph, 2))
gripper_height += algo.block_height
end
gripper_height = min(gripper_height, ceil_height)
else
# Set fixed gripper height
gripper_height = ceil_height
end
# Set gripper location
gripper_pos = Point2{Ptype}(x_mid, gripper_height)
positions[2] = gripper_pos
# Set location of held blocks
for node in inneighbors(graph, 2)
positions[node] = copy(gripper_pos)
end
return positions
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 8611 | function render_state!(
canvas::Canvas, renderer::GraphworldRenderer,
domain::Domain, state::Observable;
replace::Bool=true, options...
)
# Update options
options = merge(renderer.state_options, options)
# Set canvas state observable (replacing any previous state)
if replace || canvas.state === nothing
canvas.state = state
end
# Extract or construct main axis
ax = get(canvas.blocks, 1) do
axis_options = copy(renderer.axis_options)
delete!(axis_options, :hidedecorations)
_ax = Axis(canvas.layout[1, 1]; axis_options...)
push!(canvas.blocks, _ax)
return _ax
end
# Extract objects from state
locations = [sort!(PDDL.get_objects(domain, state[], t), by=string)
for t in renderer.location_types]
locations = prepend!(reduce(vcat, locations, init=Const[]), renderer.locations)
movables = [sort!(PDDL.get_objects(domain, state[], t), by=string)
for t in renderer.movable_types]
movables = prepend!(reduce(vcat, movables, init=Const[]), renderer.movables)
# Build static location graph
is_directed = renderer.is_loc_directed || renderer.is_mov_directed
n_locs = length(locations)
loc_graph = is_directed ? SimpleDiGraph(n_locs) : SimpleGraph(n_locs)
for (i, a) in enumerate(locations), (j, b) in enumerate(locations)
renderer.loc_edge_fn(domain, state[], a, b) || continue
add_edge!(loc_graph, i, j)
is_directed && !renderer.is_loc_directed || continue
add_edge!(loc_graph, j, i)
end
# Add movable objects to graph
graph = @lift begin
g = copy(loc_graph)
# Add edges between locations and movable objects
for (i, mov) in enumerate(movables)
add_vertex!(g)
for (j, loc) in enumerate(locations)
if renderer.mov_loc_edge_fn(domain, $state, mov, loc)
add_edge!(g, n_locs + i, j)
break
end
end
end
# Add edges between movable objects
if renderer.has_mov_edges
for (i, a) in enumerate(movables), (j, b) in enumerate(movables)
renderer.mov_edge_fn(domain, $state, a, b) || continue
add_edge!(g, n_locs + i, n_locs + j)
is_directed && !renderer.is_mov_directed || continue
add_edge!(g, n_locs + j, n_locs + i)
end
end
g
end
# Construct layout for graph including movable objects
layout = renderer.graph_layout(n_locs)
# Define node and edge labels
loc_labels = get(options, :show_location_labels, true) ?
string.(locations) : fill("", length(locations))
mov_labels = get(options, :show_movable_labels, true) ?
string.(movables) : fill("", length(movables))
node_labels = [loc_labels; mov_labels]
if get(options, :show_edge_labels, false)
init_n_edges = ne(graph[])
edge_labels = @lift begin
n_edges = ne($graph)
if n_edges != init_n_edges
error("Cannot update edge labels for dynamic graphs.")
end
labels = Vector{String}(undef, n_edges)
for (i, e) in enumerate(edges($graph))
if e.src <= n_locs && e.dst <= n_locs
a, b = locations[e.src], locations[e.dst]
labels[i] = renderer.loc_edge_label_fn(domain, $state, a, b)
elseif e.src > n_locs && e.dst > n_locs
a = movables[e.src - n_locs]
b = movables[e.dst - n_locs]
labels[i] = renderer.mov_edge_label_fn(domain, $state, a, b)
elseif e.src <= n_locs && e.dst > n_locs
a = movables[e.dst - n_locs]
b = locations[e.src]
labels[i] =
renderer.mov_loc_edge_label_fn(domain, $state, a, b)
end
end
labels
end
else
edge_labels = nothing
end
# Define node and edge colors
node_colors = @lift map(vertices($graph)) do v
v > n_locs ? to_color(get(options, :movable_node_color, :gray)) :
to_color(get(options, :location_node_color, :black))
end
edge_colors = @lift map(edges($graph)) do e
e.src > n_locs || e.dst > n_locs ?
to_color(get(options, :movable_edge_color, (:mediumpurple, 0.75))) :
to_color(get(options, :location_edge_color, :black))
end
# Render graph
gp = graphplot!(ax, graph; layout=layout, node_color=node_colors,
nlabels=node_labels, elabels=edge_labels,
edge_color=edge_colors, renderer.graph_options...)
canvas.plots[:graphplot] = gp
canvas.observables[:graph] = graph
canvas.observables[:layout] = gp[:layout]
canvas.observables[:node_pos] = gp[:node_pos]
# Update node label offsets
label_offset = get(options, :label_offset, 0.15)
map!(gp.nlabels_offset, gp.node_pos) do node_pos
mean_pos = sum(node_pos[1:n_locs]) / n_locs
dir = node_pos .- mean_pos
mag = [GeometryBasics.norm(d) for d in dir]
dir = dir ./ mag
offsets = label_offset .* dir
return offsets
end
# Render location graphics
if get(options, :show_location_graphics, true)
for (i, loc) in enumerate(locations)
r = get(renderer.loc_renderers, loc, nothing)
if r === nothing
loc in PDDL.get_objects(state[]) || continue
type = PDDL.get_objtype(state[], loc)
r = get(renderer.loc_type_renderers, type, nothing)
r === nothing && continue
end
graphic_pos = Observable(gp.node_pos[][i], ignore_equal_values=true)
on(gp.node_pos, update=true) do positions
graphic_pos[] = positions[i]
end
graphic = @lift begin
pos = $graphic_pos
translate(r(domain, $state, loc), pos[1], pos[2])
end
plt = graphicplot!(ax, graphic)
canvas.plots[Symbol("$(loc)_graphic")] = plt
end
end
# Render movable object graphics
if get(options, :show_movable_graphics, true)
for (i, obj) in enumerate(movables)
r = get(renderer.mov_renderers, obj, nothing)
if r === nothing
obj in PDDL.get_objects(state[]) || continue
type = PDDL.get_objtype(state[], obj)
r = get(renderer.mov_type_renderers, type, nothing)
r === nothing && continue
end
graphic_pos = Observable(gp.node_pos[][n_locs + i],
ignore_equal_values=true)
on(gp.node_pos, update=true) do positions
graphic_pos[] = positions[n_locs + i]
end
graphic = @lift begin
pos = $graphic_pos
translate(r(domain, $state, obj), pos[1], pos[2])
end
plt = graphicplot!(ax, graphic)
canvas.plots[Symbol("$(obj)_graphic")] = plt
end
end
# Hide decorations if flag is specified
if get(renderer.axis_options, :hidedecorations, true)
hidedecorations!(ax)
end
return canvas
end
"""
- `show_location_graphics = true`: Whether to show location graphics.
- `show_location_labels = true`: Whether to show location labels.
- `show_movable_graphics = true`: Whether to show movable object graphics.
- `show_movable_labels = true`: Whether to show movable object labels.
- `show_edge_labels = false`: Whether to show edge labels.
- `location_node_color = :black`: Color of location nodes.
- `location_edge_color = :black`: Color of edges between locations.
- `movable_node_color = :gray`: Color of movable object nodes.
- `movable_edge_color = (:mediumpurple, 0.75)`: Color of edges between
locations and movable objects.
- `label_offset = 0.15`: How much labels are offset from the center of their
corresponding objects. Larger values move the labels further away.
"""
default_state_options(R::Type{GraphworldRenderer}) = Dict{Symbol,Any}(
:show_location_graphics => true,
:show_location_labels => true,
:show_movable_graphics => true,
:show_movable_labels => true,
:show_edge_labels => false,
:location_node_color => :black,
:location_edge_color => :black,
:movable_node_color => :gray,
:movable_edge_color => (:mediumpurple, 0.75),
:label_offset => 0.15
)
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 4257 | function (cb::AnimSolveCallback{GridworldRenderer})(
planner::Union{ForwardPlanner, BreadthFirstPlanner},
sol::PathSearchSolution, node_id::Union{UInt, Nothing}, priority
)
renderer, canvas, domain = cb.renderer, cb.canvas, cb.domain
options = isempty(cb.options) ? renderer.trajectory_options :
merge(renderer.trajectory_options, cb.options)
# Extract agent observables
if renderer.has_agent
agent_locs = get!(Point2fVecObservable,
canvas.observables, :search_agent_locs)
agent_dirs = get!(Point2fVecObservable,
canvas.observables, :search_agent_dirs)
else
agent_locs = nothing
agent_dirs = nothing
end
# Extract object observables
objects = get(options, :tracked_objects, Const[])
types = get(options, :tracked_types, Symbol[])
for ty in types
objs = PDDL.get_objects(domain, state, ty)
append!(objects, objs)
end
obj_locs = [get!(Point2fVecObservable, canvas.observables,
Symbol("search_$(obj)_locs")) for obj in objects]
obj_dirs = [get!(Point2fVecObservable, canvas.observables,
Symbol("search_$(obj)_dirs")) for obj in objects]
# Determine if search tree was reinitialized or rerooted
n_expanded = length(sol.search_tree) - length(sol.search_frontier)
n_expanded = max(n_expanded, sol.expanded)
if renderer.has_agent
tree_updated = length(agent_locs[]) != n_expanded-1
else
tree_updated = any(length(os[]) != n_expanded-1 for os in obj_locs)
end
# Rebuild search tree if tree was updated, otherwise add node to tree
if tree_updated
_build_tree!(agent_locs, agent_dirs, objects, obj_locs, obj_dirs,
renderer, sol, node_id)
elseif !isnothing(node_id)
_add_node_to_tree!(agent_locs, agent_dirs, objects, obj_locs, obj_dirs,
renderer, sol, node_id)
end
# Render search tree if necessary
ax = canvas.blocks[1]
node_marker = get(options, :search_marker, '⦿')
node_size = get(options, :search_size, 0.3)
edge_arrow = get(options, :search_arrow, '▷')
cmap = get(options, :search_colormap, cgrad([:blue, :red]))
if renderer.has_agent && !haskey(canvas.plots, :agent_search_nodes)
colors = @lift 1:length($agent_locs)
canvas.plots[:agent_search_nodes] = arrows!(
ax, agent_locs, agent_dirs, color=colors, colormap=cmap,
arrowsize=node_size, arrowhead=node_marker,
markerspace=:data, align=:head
)
edge_locs = @lift $agent_locs .- ($agent_dirs .* 0.5)
edge_rotations = @lift [atan(d[2], d[1]) for d in $agent_dirs]
edge_markers = @lift map($agent_dirs) do d
d == Point2f(0, 0) ? node_marker : edge_arrow
end
canvas.plots[:agent_search_arrows] = scatter!(
ax, edge_locs, rotation=edge_rotations,
marker=edge_markers, markersize=node_size, markerspace=:data,
color=colors, colormap=cmap
)
end
for (obj, ls, ds) in zip(objects, obj_locs, obj_dirs)
haskey(canvas.plots, Symbol("$(obj)_search_nodes")) && continue
colors = @lift 1:length($ls)
canvas.plots[Symbol("$(obj)_search_nodes")] = arrows!(
ax, ls, ds, colormap=cmap, color=colors, markerspace=:data,
arrowsize=node_size, arrowhead=node_marker, align=:head
)
e_ls = @lift $ls .- ($ds .* 0.5)
e_rs = @lift [atan(d[2], d[1]) for d in $ds]
e_ms = @lift map($ds) do d
d == Point2f(0, 0) ? node_marker : edge_arrow
end
canvas.plots[Symbol("$(obj)_search_arrows")] = scatter!(
ax, e_ls, rotation=e_rs, marker=e_ms, markersize=node_size,
markerspace=:data, colormap=cmap, color=colors
)
end
# Trigger updates
if renderer.has_agent
notify(agent_locs); notify(agent_dirs)
end
for (ls, ds) in zip(obj_locs, obj_dirs)
notify(ls); notify(ds)
end
# Run record callback if provided
!isnothing(cb.record_callback) && cb.record_callback(canvas)
cb.sleep_dur > 0 && sleep(cb.sleep_dur)
return nothing
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 5491 | function (cb::AnimSolveCallback{GridworldRenderer})(
planner::RealTimeDynamicPlanner,
sol::PolicySolution, n::Int, visited, stop_reason::Symbol
)
renderer, canvas, domain = cb.renderer, cb.canvas, cb.domain
options = isempty(cb.options) ? renderer.trajectory_options :
merge(renderer.trajectory_options, cb.options)
# Extract initial state
state = visited[1]
prev_state = state
height = size(state[renderer.grid_fluents[1]], 1)
# Extract agent observables
if renderer.has_agent
agent_locs = get!(Point2fVecObservable,
canvas.observables, :rtdp_agent_locs)
agent_dirs = get!(Point2fVecObservable,
canvas.observables, :rtdp_agent_dirs)
end
# Extract object observables
objects = get(options, :tracked_objects, Const[])
types = get(options, :tracked_types, Symbol[])
for ty in types
objs = PDDL.get_objects(domain, state, ty)
append!(objects, objs)
end
obj_locs = [get!(Point2fVecObservable, canvas.observables,
Symbol("rtdp_$(obj)_locs")) for obj in objects]
obj_dirs = [get!(Point2fVecObservable, canvas.observables,
Symbol("rtdp_$(obj)_dirs")) for obj in objects]
# Extract solution observables
sol_obs = get!(() -> Observable(sol), canvas.observables, :rtdp_solution)
state_obs = get!(() -> Observable(state), canvas.observables, :rtdp_state)
# Reset agent observables
if renderer.has_agent
empty!(agent_locs[])
empty!(agent_dirs[])
loc = gw_agent_loc(renderer, state, height)
prev_loc = gw_agent_loc(renderer, prev_state, height)
push!(agent_locs[], loc)
push!(agent_dirs[], loc .- prev_loc)
end
# Reset object observables
for (i, obj) in enumerate(objects)
empty!(obj_locs[i][])
empty!(obj_dirs[i][])
loc = gw_obj_loc(renderer, state, obj, height)
prev_loc = gw_obj_loc(renderer, prev_state, obj, height)
push!(obj_locs[i][], loc)
push!(obj_dirs[i][], loc .- prev_loc)
end
# Render rollout if necessary
ax = canvas.blocks[1]
node_marker = get(options, :search_marker, '⦿')
node_size = get(options, :search_size, 0.3)
edge_arrow = get(options, :search_arrow, '▷')
cmap = get(options, :search_colormap, cgrad([:blue, :red]))
if renderer.has_agent && !haskey(canvas.plots, :agent_rtdp_nodes)
colors = @lift 1:length($agent_locs)
canvas.plots[:agent_rtdp_nodes] = arrows!(
ax, agent_locs, agent_dirs, color=colors, colormap=cmap,
arrowsize=node_size, arrowhead=node_marker,
markerspace=:data, align=:head
)
edge_locs = @lift $agent_locs .- ($agent_dirs .* 0.5)
edge_rotations = @lift [atan(d[2], d[1]) for d in $agent_dirs]
edge_markers = @lift map($agent_dirs) do d
d == Point2f(0, 0) ? node_marker : edge_arrow
end
canvas.plots[:agent_rtdp_arrows] = scatter!(
ax, edge_locs, rotation=edge_rotations, color=colors, colormap=cmap,
marker=edge_markers, markersize=node_size, markerspace=:data,
)
end
for (obj, ls, ds) in zip(objects, obj_locs, obj_dirs)
haskey(canvas.plots, Symbol("$(obj)_rtdp_nodes")) && continue
colors = @lift 1:length($ls)
canvas.plots[Symbol("$(obj)_rtdp_nodes")] = arrows!(
ax, ls, ds, colormap=cmap, color=colors, markerspace=:data,
arrowsize=node_size, arrowhead=node_marker, align=:head
)
e_ls = @lift $ls .- ($ds .* 0.5)
e_rs = @lift [atan(d[2], d[1]) for d in $ds]
e_ms = @lift map($ds) do d
d == Point2f(0, 0) ? node_marker : edge_arrow
end
canvas.plots[Symbol("$(obj)_rtdp_arrows")] = scatter!(
ax, e_ls, rotation=e_rs, marker=e_ms, markersize=node_size,
markerspace=:data, colormap=cmap, color=colors
)
end
!isnothing(cb.record_callback) && cb.record_callback(canvas)
cb.sleep_dur > 0 && sleep(cb.sleep_dur)
# Iterate over visited states
for state in visited[2:end]
# Update observables
if renderer.has_agent
loc = gw_agent_loc(renderer, state, height)
prev_loc = gw_agent_loc(renderer, prev_state, height)
push!(agent_locs[], loc)
push!(agent_dirs[], loc .- prev_loc)
notify(agent_locs); notify(agent_dirs)
end
for (i, obj) in enumerate(objects)
loc = gw_obj_loc(renderer, state, obj, height)
prev_loc = gw_obj_loc(renderer, prev_state, obj, height)
push!(obj_locs[i][], loc)
push!(obj_dirs[i][], loc .- prev_loc)
notify(obj_locs[i]); notify(obj_dirs[i])
end
!isnothing(cb.record_callback) && cb.record_callback(canvas)
cb.sleep_dur > 0 && sleep(cb.sleep_dur)
prev_state = state
end
# Render / update value heatmap
if (renderer.has_agent && !haskey(canvas.plots, :agent_policy_values)) ||
(!isempty(objects) && !haskey(canvas.plots, Symbol("$(objects[1])_policy_values")))
render_sol!(canvas, renderer, domain, state_obs, sol_obs; options...)
else
state_obs.val = visited[1]
sol_obs[] = sol
end
!isnothing(cb.record_callback) && cb.record_callback(canvas)
cb.sleep_dur > 0 && sleep(cb.sleep_dur)
return nothing
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |
|
[
"Apache-2.0"
] | 0.1.13 | 6b474016099e29cea6f7a910c9c20eb1b539b48c | code | 4689 | function (cb::AnimSolveCallback{GridworldRenderer})(
planner::RealTimeHeuristicSearch, sol::ReusableTreePolicy,
init_state::Union{State, Nothing}, cur_state::State,
n::Int, act, cur_v, best_act
)
renderer, canvas, domain = cb.renderer, cb.canvas, cb.domain
options = merge(renderer.trajectory_options, cb.options)
options[:show_search] = false
if planner.reuse_paths
options[:show_goal_tree] = get(options, :show_goal_tree, true)
end
# Determine grid height
height = size(cur_state[renderer.grid_fluents[1]], 1)
# Extract agent observables
if renderer.has_agent
agent_loc = get!(canvas.observables, :rths_agent_loc) do
Observable(Point2f(gw_agent_loc(renderer, cur_state, height)))
end
agent_color = set_alpha(get(options, :agent_color, :black), 0.75)
search_agent_locs =
get!(Point2fVecObservable, canvas.observables, :search_agent_locs)
search_agent_dirs =
get!(Point2fVecObservable, canvas.observables, :search_agent_dirs)
else
search_agent_locs = nothing
search_agent_dirs = nothing
end
# Extract object observables
objects = get(options, :tracked_objects, Const[])
obj_colors = get(options, :object_colors, Symbol[]) .|> to_color_obs
types = get(options, :tracked_types, Symbol[])
types = get(options, :tracked_types, Symbol[])
type_colors = get(options, :type_colors, Symbol[]) .|> to_color_obs
for (ty, col) in zip(types, type_colors)
objs = PDDL.get_objects(domain, state, ty)
append!(objects, objs)
append!(obj_colors, fill(col, length(objs)))
end
obj_locs = map(objects) do obj
get!(canvas.observables, Symbol("rths_$(obj)_loc")) do
Observable(Point2f(gw_obj_loc(renderer, cur_state, obj, height)))
end
end
obj_colors = map(col -> set_alpha(col, 0.75), obj_colors)
search_obj_locs = [get!(Point2fVecObservable, canvas.observables,
Symbol("search_$(obj)_locs")) for obj in objects]
search_obj_dirs = [get!(Point2fVecObservable, canvas.observables,
Symbol("search_$(obj)_dirs")) for obj in objects]
# Extract solution observables
sol_obs = get!(() -> Observable(sol), canvas.observables, :rths_solution)
state_obs = get!(() -> Observable(cur_state), canvas.observables, :rths_state)
# Render current locations if necessary
loc_marker = get(options, :rths_loc_marker, '○')
loc_markersize = get(options, :rths_loc_markersize, 0.6)
ax = canvas.blocks[1]
if renderer.has_agent && !haskey(canvas.plots, :rths_agent_loc)
canvas.plots[:rths_agent_loc] =
scatter!(ax, agent_loc, color=agent_color, markerspace=:data,
marker=loc_marker, markersize=loc_markersize)
end
for (obj, loc, col) in zip(objects, obj_locs, obj_colors)
if !haskey(canvas.plots, Symbol("rths_$(obj)_loc"))
canvas.plots[Symbol("rths_$(obj)_loc")] =
scatter!(ax, loc, color=col, markerspace=:data,
marker=loc_marker, markersize=loc_markersize)
end
end
# Update location observables
if renderer.has_agent
agent_loc[] = Point2f(gw_agent_loc(renderer, cur_state, height))
end
for (obj, loc) in zip(objects, obj_locs)
loc[] = Point2f(gw_obj_loc(renderer, cur_state, obj, height))
end
# Reset/rebuild search locations if iteration has completed
if isnothing(act)
node_id = isempty(sol.search_sol.trajectory) ?
nothing : hash(sol.search_sol.trajectory[end])
_build_tree!(
search_agent_locs, search_agent_dirs,
objects, search_obj_locs, search_obj_dirs,
renderer, sol.search_sol, node_id
)
if renderer.has_agent && !isempty(search_agent_locs[])
notify(search_agent_locs)
notify(search_agent_dirs)
end
for (ls, ds) in zip(search_obj_locs, search_obj_dirs)
if !isempty(ls[])
notify(ls)
notify(ds)
end
end
end
# Render / update value heatmap
if (renderer.has_agent && !haskey(canvas.plots, :agent_policy_values)) ||
(!isempty(objects) && !haskey(canvas.plots, Symbol("$(objects[1])_policy_values")))
render_sol!(canvas, renderer, domain, state_obs, sol_obs; options...)
else
state_obs.val = cur_state
sol_obs[] = sol
end
# Run record callback if provided
!isnothing(cb.record_callback) && cb.record_callback(canvas)
cb.sleep_dur > 0 && sleep(cb.sleep_dur)
return nothing
end
| PDDLViz | https://github.com/JuliaPlanners/PDDLViz.jl.git |