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
|
---|---|---|---|---|---|---|---|---|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | code | 59 | module docs
greet() = print("Hello World!")
end # module
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | code | 9820 | module PoseComposition
import Base: @kwdef
import LinearAlgebra: dot, norm, cross
import Rotations: AngleAxis, Rotation, QuatRotation, RotZYX, RotMatrix
import StaticArrays: StaticVector, SVector, @SVector
include("docstring_extensions.jl")
"""
Struct representing the pose (position and orientation) of an object.
Can represent either a relative pose (relative to some parent coordinate frame
which must be supplied by context) or an absolute pose. An absolute pose is,
by definition, a pose relative to the world coordinate frame.
See [Operations on Poses](@ref) for documentation of this data structure and
the operations defined on it.
"""
@kwdef struct Pose
"""Origin of the object's coordinate frame."""
pos::StaticVector{3, <:Real}
"""Orientation of the object's coordinate frame."""
orientation::Rotation{3}
end
### Constructors ###
function Pose(x::Real, y::Real, z::Real, orientation::Rotation{3})::Pose
Pose(@SVector([x, y, z]), orientation)
end
function Pose(pos::AbstractVector{<:Real}, orientation::Rotation{3})::Pose
(x, y, z) = pos
Pose(@SVector([x, y, z]), orientation)
end
function Pose(pos::AbstractVector{<:Real}, ypr::NamedTuple{(:yaw, :pitch, :roll)})::Pose
Pose(pos, RotZYX(ypr.yaw, ypr.pitch, ypr.roll))
end
function Pose(x::Real, y::Real, z::Real, ypr::NamedTuple{(:yaw, :pitch, :roll)})::Pose
Pose(x, y, z, RotZYX(ypr.yaw, ypr.pitch, ypr.roll))
end
function Base.isapprox(a::Pose, b::Pose; kwargs...)::Bool
(isapprox(a.pos, b.pos; kwargs...) &&
isapprox(a.orientation, b.orientation; kwargs...))
end
### Constants ###
"""
The identity quaternion, representing the identity orientation.
"""
IDENTITY_ORN = one(QuatRotation)
"""
Identity pose, a.k.a. the relative pose of any coordinate frame relative to itself.
This is the identity element for the pose group (the identity element is the same in both
group structures).
"""
const IDENTITY_POSE = Pose([0, 0, 0], IDENTITY_ORN)
### Pretty-printing ###
function Base.show(io::IO, pose::Pose)
# Not sure whether most people will want (yaw, pitch, roll) or quaternion
# components here.
print(io, strWithQuat(pose))
end
function strWithYPR(pose::Pose)::String
(yaw, pitch, roll) = _yawPitchRoll(pose.orientation)
"Pose⟨pos=$(pose.pos), orientation=(yaw=$yaw, pitch=$pitch, roll=$roll)⟩"
end
function strWithQuat(pose::Pose)::String
q = QuatRotation(pose.orientation)
(w, x, y, z) = componentsWXYZ(q)
"Pose⟨pos=$(pose.pos), orientation=(w=$w, x=$x, y=$y, z=$z)⟩"
end
function _yawPitchRoll(orn::Rotation{3})
ypr = RotZYX(orn)
(yaw=ypr.theta1, pitch=ypr.theta2, roll=ypr.theta3)
end
componentsWXYZ(q::QuatRotation) = @SVector([q.q.s, q.q.v1, q.q.v2, q.q.v3])
"""
Like `isapprox`, but does not consider a quaternion to be equivalent to its
negative (even though they correspond to the same rotation matrix). Note that
this is stricter than `Base.isapprox`, since for a `Rotations.QuatRotation`
`q`, we have `-q ≈ q` and in fact `-q == q`.
"""
function isapproxIncludingQuaternionSign(a::Pose, b::Pose; kwargs)::Bool
(isapprox(a.pos, b.pos; kwargs...) &&
isapprox(componentsWXYZ(QuatRotation(a.orientation)),
componentsWXYZ(QuatRotation(b.orientation));
kwargs...))
end
# Operations for combining poses.
Base.:(*)(a::Pose, b::Pose)::Pose = Pose(
a.pos + a.orientation * b.pos,
a.orientation * b.orientation)
Base.:(/)(a::Pose, b::Pose)::Pose = Pose(
a.pos - (a.orientation / b.orientation) * b.pos,
a.orientation / b.orientation)
Base.:(\)(a::Pose, b::Pose)::Pose = Pose(
a.orientation \ (-a.pos + b.pos),
a.orientation \ b.orientation)
Base.:(^)(pose::Pose, t::Real) = Pose(t * pose.pos,
# quaternion exponentiation = SLERP
quatPow(QuatRotation(pose.orientation),
t))
function Base.inv(a::Pose)::Pose
Pose(a.orientation \ -a.pos,
inv(a.orientation))
end
# Action of a pose on a point.
function Base.:(*)(a::Pose, bpos::StaticVector{3, <:Real})
a.pos + a.orientation * bpos
end
function Base.:(\)(a::Pose, bpos::StaticVector{3, <:Real})
a.orientation \ (-a.pos + bpos)
end
# Convenience wrappers when the user supplies a Vector instead of a StaticVector
Base.:(*)(a::Pose, bpos::AbstractVector{<:Real}) = a * SVector{3}(bpos)
Base.:(\)(a::Pose, bpos::AbstractVector{<:Real}) = a \ SVector{3}(bpos)
"""
Vectorized pose–point multiplication. Returns the matrix whose `i`th column is
`a * bpoints[:, i]`.
The matrix `bpoints` must have 3 rows, as each column represents a point in 3D
space.
"""
function Base.:(*)(a::Pose, bpoints::AbstractMatrix{<:Real})
size(bpoints, 1) == 3 || error(
"Must pass a 3×N matrix (one column per point)")
a.pos .+ a.orientation * bpoints
end
"""
Vectorized version of pose–point left division. Returns the matrix whose `i`th
column is `a \\ bpoints[:, i]`.
The matrix `bpoints` must have 3 rows, as each column represents a point in 3D
space.
"""
function Base.:(\)(a::Pose, bpoints::AbstractMatrix{<:Real})
size(bpoints, 1) == 3 || error(
"Must pass a 3×N matrix (one column per point)")
a.orientation \ (-a.pos .+ bpoints)
end
"""
!!! note "TODO"
This code mostly duplicates `GenDirectionalStats.hopf`. The two should
probably be consolidated into one.
Returns a rotation that carries the z-axis to `newZ`, with the remaining degree
of freedom determined by `planarAngle` as described below.
Start with the case `planarAngle = 0`. In that case, the returned rotation is
the unique (except at singularities) rotation that carries `[0, 0, 1]` to
`newZ` "along a great circle" (more precisely: the unique rotation that carries
`[0, 0, 1]` to `newZ` and whose equator contains `[0, 0, 1]` and `newZ`;
"equator" means the unique great circle that is fixed setwise by the rotation).
Next consider the general case. This works the same as the above special case,
except that we precede that rotation with a rotation by angle `planarAngle`
around `[0, 0, 1]` (or equivalently, we follow that rotation with a rotation by
`planarAngle` around `newZ`).
The name of this function comes from the fact that we are using geodesics
(great circles) to define a coordinate chart on the fiber over `newZ` in the
Hopf fibration.
See also: [`invGeodesicHopf`](@ref)
"""
function geodesicHopf(newZ::StaticVector{3, <:Real}, planarAngle::Real)
@assert norm(newZ) ≈ 1
zUnit = @SVector([0, 0, 1])
if newZ ≈ -zUnit
@warn "Singularity: anti-parallel z-axis, rotation has an undetermined degree of freedom"
axis = @SVector([1, 0, 0])
geodesicAngle = π
elseif newZ ≈ zUnit
# Choice of axis doesn't matter here as long as it's nonzero
axis = @SVector([1, 0, 0])
geodesicAngle = 0
else
axis = cross(zUnit, newZ)
@assert !(axis ≈ zero(axis)) || newZ ≈ zUnit
geodesicAngle = let θ = asin(clamp(norm(axis), -1, 1))
dot(zUnit, newZ) > 0 ? θ : π - θ
end
end
return (AngleAxis(geodesicAngle, axis...) *
AngleAxis(planarAngle, zUnit...))
end
geodesicHopf(newZ::AbstractVector{<:Real}, planarAngle::Real) = geodesicHopf(
SVector{3}(newZ), planarAngle)
"""
Inverse function of [`geodesicHopf`](@ref).
Satisfies the round-trip conditions
geodesicHopf(invGeodesicHopf(r)...) == r
and
invGeodesicHopf(geodesicHopf(newZ, planarAngle))
== (newZ=newZ, planarAngle=planarAngle)
"""
function invGeodesicHopf(r::Rotation{3})::NamedTuple{(:newZ, :planarAngle)}
zUnit = @SVector([0, 0, 1])
newZ = r * zUnit
if newZ ≈ -zUnit
@warn "Singularity: anti-parallel z-axis, planarAngle is undetermined"
planarAngle = 0
else
# Solve `planarRot == AngleAxis(planarAngle, zUnit...)` for `planarAngle`
planarRot = AngleAxis(geodesicHopf(newZ, 0) \ r)
axis = @SVector([planarRot.axis_x, planarRot.axis_y, planarRot.axis_z])
# `axis` is either `zUnit` or `-zUnit`, and we need to ensure that it's
# `zUnit`. (Exception: the degenerate case `planarAngle == 0`)
if axis[3] < 0
axis = -axis
planarAngle = -planarRot.theta
else
planarAngle = planarRot.theta
end
atol = 1e-14
@assert isapprox(axis, zUnit; atol=atol) ||
abs(rem2pi(planarAngle, RoundNearest)) < atol
end
return (newZ=newZ, planarAngle=planarAngle)
end
# Second group structure on poses: Direct product ``ℝ^3 × SO_3(ℝ)``.
⊗(a::Pose, b::Pose) = Pose(a.pos + b.pos, a.orientation * b.orientation)
⊘(a::Pose, b::Pose) = Pose(a.pos - b.pos, a.orientation / b.orientation)
⦸(a::Pose, b::Pose) = Pose(b.pos - a.pos, a.orientation \ b.orientation)
"""
Interpolates between the identity pose and `b`.
Namely, `interp(b, 0) == IDENTITY_POSE` and `interp(b, 1) == b`. The position
is interpolated linearly and the orientation is interpolated by quaternion
SLERP. That is, this interpolation treats position and orientation
independently, as in the [`⊗`](@ref) operation (not the [`*`](@ref
Base.:*(::Pose, ::Pose)) operation).
"""
interp(b::Pose, t::Real) = Pose(t * b.pos,
quatPow(QuatRotation(b.orientation), t))
"""
Like [`interp`](@ref interp(::Pose, ::Real)), but interpolates between two
given poses rather than always starting at the identity. That is,
interp(a, b, 0) == a
interp(a, b, 1) == b
and as a special case, we have
interp(b, t) == interp(IDENTITY_POSE, b, t)
"""
interp(a::Pose, b::Pose, t::Real) = a * interp(a ⦸ b, t)
function quatPow(q::QuatRotation, t::Real)
# TODO: Once https://github.com/JuliaGeometry/Rotations.jl/issues/126 is
# fixed, this special case won't be necessary
if t == 0 || q == one(QuatRotation) || q == -one(QuatRotation)
return one(QuatRotation)
end
return RotMatrix{3}(exp(t * log(q)))
end
end # module PoseComposition
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | code | 351 | import DocStringExtensions
import DocStringExtensions: SIGNATURES, TYPEDSIGNATURES, DOCSTRING,
FIELDS, TYPEDFIELDS
DocStringExtensions.@template (FUNCTIONS, METHODS, MACROS) =
"""
$(TYPEDSIGNATURES)
$(DOCSTRING)
"""
DocStringExtensions.@template TYPES =
"""
Fields:
$(TYPEDFIELDS)
---
$(DOCSTRING)
"""
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | code | 3277 | import PoseComposition: Pose, IDENTITY_POSE, IDENTITY_ORN, interp, ⊗, ⊘
import Rotations: QuatRotation, RotZYX
import StaticArrays: SVector, @SVector
import Test: @test, @testset
@testset "Pose group operations" begin
p1 = Pose(1.0, 1.1, 1.2, QuatRotation(√(0.1), √(0.2), √(0.3), √(0.4)))
p2 = Pose(2.0, 2.1, 2.2, QuatRotation(√(0.2), √(0.2), √(0.3), √(0.3)))
p3 = Pose(3.0, 3.1, 3.2, QuatRotation(√(0.3), √(0.3), √(0.3), √(0.1)))
function testPosesApprox(a, b; kwargs...)
@test isapprox(a.pos, b.pos; kwargs...)
@test isapprox(a.orientation, b.orientation; kwargs...)
end
testPosesApprox((p1 * p2) * p3, p1 * (p2 * p3))
testPosesApprox((p1 * p2) / p2, p1)
testPosesApprox((p1 / p2) * p2, p1)
testPosesApprox(p1 * (p1 \ p2), p2)
testPosesApprox(inv(p1) * p1, IDENTITY_POSE; atol=1e-14)
testPosesApprox(p1 * inv(p1), IDENTITY_POSE; atol=1e-14)
end
@testset "Commutative diagram: a * b.pos == (a * b).pos" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpos = @SVector([7, 8, 9])
b = Pose(bpos, RotZYX(1.0, 1.1, 1.2))
@test a * bpos ≈ (a * b).pos
end
@testset "Associativity: (a * b) * cpos == a * (b * cpos)" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
b = Pose([7, 8, 9], RotZYX(1.0, 1.1, 1.2))
cpos = @SVector([13, 14, 15])
@test (a * b) * cpos ≈ a * (b * cpos)
end
@testset "Left division: a::Pose \\ bpos::StaticVector == inv(a) * bpos" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpos = @SVector([7, 8, 9])
@test a \ bpos ≈ inv(a) * bpos
end
@testset "Generic vector (non-`StaticVector`) wrappers, sanity check" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpos = @SVector([7, 8, 9])
bpos_ = [7, 8, 9]
@test a * bpos_ ≈ a * bpos
@test a \ bpos_ ≈ a \ bpos
end
@testset "Equivalence of `Pose * Matrix` with `Pose * StaticVector` on each column" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpoints = reshape(7:21, (3, 5))
@test a * bpoints ≈ reduce(hcat,
a * SVector{3}(bpoint) for bpoint in eachcol(bpoints))
end
@testset "Edge case: Pose * (3-by-0 Matrix)" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpoints = zeros(3, 0)
@test a * bpoints == zeros(3, 0)
end
@testset "Left division: a::Pose \\ bpoints::Matrix == inv(a) * bpoints" begin
a = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
bpoints = reshape(7:21, (3, 5))
@test a \ bpoints ≈ inv(a) * bpoints
end
@testset "`interp` endpoint conditions" begin
a = Pose([10, 11, 12], IDENTITY_ORN)
b = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
@test interp(a, b, 0) ≈ a
@test interp(a, b, 1) ≈ b
end
@testset "`t ↦ interp(b, t)` is a homomorphism from (ℝ, +) to (poses, ⊗)" begin
b = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
@test interp(b, 0.5) ⊗ interp(b, 0.7) ≈ interp(b, 1.2)
end
@testset "`interp(b, t) == b ⊗ ... ⊗ b` (`t` times) when `t` is an integer" begin
b = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
@test interp(b, -1) ≈ IDENTITY_POSE ⊘ b
@test interp(b, 2) ≈ b ⊗ b
@test interp(b, 0.5) ⊗ interp(b, 0.5) ≈ b
end
# Regression test for https://github.com/probcomp/PoseComposition.jl/issues/11
@testset "Can stringify, print and `show` with no crash" begin
pose = Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6))
string(pose)
print(devnull, pose)
show(devnull, "text/plain", pose)
end
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | docs | 375 | # PoseComposition.jl
[](https://probcomp.github.io/PoseComposition.jl/dev/)
[](https://travis-ci.com/probcomp/PoseComposition.jl)
Check out the [docs](https://probcomp.github.io/PoseComposition.jl/dev/)!
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | docs | 143 | # Further API Reference
```@meta
CurrentModule = PoseComposition
```
```@autodocs
Modules = [PoseComposition]
Order = [:type, :function]
```
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | docs | 4172 | # PoseComposition.jl
```@meta
CurrentModule = PoseComposition
```
---
[](imgs/intro_illustration.svg)
PoseComposition.jl is a library for representing and manipulating poses. It
places particular emphasis on:
* **Algebraic structure.** This package implements two different group
structures on poses. In the first group structure, composition corresponds
to change of coordinate frame. This enables easy manipulation of chains of
coordinate frames which occur commonly in operations on scene graphs:
```math
\text{pose}_{\text{floor} \to \text{napkin}} =
\text{pose}_{\text{floor} \to \text{table}} *
\text{pose}_{\text{table} \to \text{plate}} *
\text{pose}_{\text{plate} \to \text{napkin}}
```
In the second group structure, position and orientation are treated
independently; this models, e.g., inertial motion, where an object has
separate translational and rotational velocities:
```math
\begin{aligned}
\mathbf{x} &= \mathbf{x}_0 + \mathbf{v}_{\text{trans}} \Delta t \\
\boldsymbol{\omega} &= \boldsymbol{\omega}_0 \cdot \mathbf{v}_{\text{rot}}^{\Delta t}
\end{aligned}
```
Inertial continuous-time dynamics are implemented concisely as
[`interp`](@ref), which is itself a special case of the [exponential
map](https://en.wikipedia.org/wiki/Exponential_map_(Lie_theory)) on a Lie
algebra:
```math
\text{pose}_t = \texttt{interp}(\text{pose}_0,\, \mathbf{v}_{\text{pose}},\, t)
```
* **Clear documentation.** The geometric meaning of the data structures and
operations is clearly documented, so as to minimize confusion from the many
ambiguities that typically plague geometry code.
* **Simple equations, ergonomic code.** Because change of coordinate frame is
the basic algebraic operation, large equations involving many coordinate
frames can be solved via simple algebra to express the relative pose between
any two frames as a function of the others. For example, in "Pose Algebra In
Action[^1]," we solve the equation
```
pose1 * getContactPlane(getShape(g, :obj1), :top)
* planarContactTo6DOF(pc)
== pose2 * getContactPlane(getShape(g, :obj2), :curved, 0)
```
for `planarContactTo6DOF(pc)` by simple division in the pose group:
```
planarContactTo6DOF(pc) ==
(pose1 * getContactPlane(getShape(g, :obj1), :top))
\ (pose2 * getContactPlane(getShape(g, :obj2), :curved, 0))
```
By contrast, computing and expressing the position and orientation separately
would require a much larger expression with nested operations and
harder-to-understand code.
[^1]:
The "Pose Algebra in Action" doc is temporarily unavailable; please check
back soon!
## Quick Start
### Pose composition example
Define `p1`, the pose of a batter (relative to some arbitrary world coordinate
frame) in a game of baseball:
```julia
p1 = Pose([10, 10, 0], QuatRotation(1, 0, 0, 0))
```
Define `p1_2`, the relative pose of the baseball in the batter's coordinate
frame, and compute `p2`, the pose of the baseball in the world coordinate
frame:
```julia
p1_2 = Pose([0, 90, 5], RotZYX(0.3, 0.4, 0.5))
p2 = p1 * p1_2
```
Suppose the ball leaves the pitcher's hand at time $t=0$. If the pitch is a
fastball and there is negligible wind, then the ball's pose at time `t` can be
approximated as inertial:
```julia
# Translational and rotational velocity of the ball relative to the batter
v = Pose([0, -115, -0.2], RotZYX(0, 0, 10))
# Pose of the ball relative to the batter as a function of time
p1_2(t) = p2 ⊗ interp(v, t)
```
### Point cloud example
Suppose a robot views the world through a camera that has pose `pose_cam` in
the world coordinate frame, and perceives a point cloud (represented as a ``3
\times N`` matrix) `ptcloud_cam` in the camera's coordinate frame. Then the
same point cloud expressed in the world coordinate frame is
```julia
ptcloud_world = pose_cam * ptcloud_cam
```
Conversely, if we know of a point cloud `ptcloud_world` expressed in the world
coordinate frame and want to re-express it in the camera's coordinate frame:
```julia
ptcloud_cam = pose_cam \ ptcloud_world
```
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"Apache-2.0"
] | 0.1.2 | 86077741eb00a97823cf6806d964574a8dc631e2 | docs | 8056 | # Operations on Poses
```@meta
CurrentModule = PoseComposition
```
---
A [`Pose`](@ref) can represent either a relative pose (relative to some parent
coordinate frame which must be supplied by context) or an absolute pose. An
absolute pose is, by definition, a pose relative to the world coordinate frame.
## First group structure: change of coordinate frame
A central operation on poses is change of coordinate frame:
```
(absolute pose of frame2) = (absolute pose of frame1) * (relative pose of frame2 relative to frame1)
```
This operation gives the set of poses a group structure -- call it the "pose
group" ``G``. This ``G`` is the
[opposite group](https://en.wikipedia.org/wiki/Opposite_group) of the group of
[rigid transformations](https://en.wikipedia.org/wiki/Special_Euclidean_group)
``SE_3 = \mathbb{R}^3 \ltimes SO_3(\mathbb{R})``
(technical note[^1]), meaning that relative poses are "applied" on the right,
rather than written as function applications on the left.
[^1]:
In code, elements of ``G`` whose orientation is represented as a
`Rotations.QuatRotation` (as opposed to some other subtype of
`Rotations.Rotation{3}`) remember their sign (`q` and `-q` are considered
equal by `Base.:==`, but their fields are not equal).
The group operation is implemented via `Pose`-specific methods of the standard
Julia functions in `Base`:
* Multiplication: `pose1 * pose2`
* Inversion: `inv(pose)`, such that
`pose * inv(pose) == inv(pose) * pose == IDENTITY_POSE`
* Right-division: `pose1 / pose2 := pose1 * inv(pose2)`
* Left-division: `pose1 \ pose2 := inv(pose1) * pose2`
#### Convention: First translate, then rotate
Note that we define the group operation on the pose group by doing the
translation first, then the rotation. So the coordinate frame `pose1 * pose2`
has an origin whose coordinates in the frame of `pose1` are `pose2.pos` (the
translational component of `pose2`).
Note also that the orientation `orn := pose.orientation` represents the linear
operator
v ↦ Rotations.RotMatrix{3}(orn) * v =: orn * v
In other words, we are using the convention that matrix-vector multiplication
has the vector on the right. The x, y and z axes of an object with pose `pose`
are `pose.orientation * [1, 0, 0]`, `pose.orientation * [0, 1, 0]` and
`pose.orientation * [0, 0, 1]` respectively.
##### Example: Which order do I multiply things in?
Suppose we start with coordinate frame `p1`, and we want to translate its
origin by `p2.pos` and then rotate its coordinate axes via the linear map
`v ↦ p2.orientation * v`. Would the pose corresponding to the new coordinate
frame be written as `p1 * p2` or `p2 * p1`?
Answer: `p1 * p2`.
#### Mathematical details: contravariance, coordinate frames, and rigid motions
There are two ways to think about poses:
1. A pose is a coordinate frame, described with respect to some other base
coordinate frame. The `pos` says where the frame's origin is, and the
`orientation` says what directions its orthonormal axes point in.
2. A pose is a rigid motion. The translational component is `pos` and the
orientation component is the linear map `v ↦ orientation * v`.
When we talk about the [group
action](https://en.wikipedia.org/wiki/Group_action_(mathematics)) of ``G`` on
itself by multiplication, we want to say that a rigid transformation (way 2
above) acts on a coordinate frame (way 1 above), by moving the origin a
translational offset of `pos` and matrix-multiplying its rotation by
`orientation`. The thing to note is that, even though function application is
usually written on the left, this group action *right*-associative, so it must
be represented by right-multiplication, not left-multiplication (or else the
associative law breaks).
### Points and point clouds
Above we explained how a pose can act on another pose. It is also possible for
a pose to act on a point in ``\mathbb{R}^3``. To see how, note that for poses
`a` and `b`, the position of the product, `(a * b).pos`, does not depend on
`b.orientation`. Therefore it is valid to define, for any `a::Pose` and any
``\texttt{bpos} ∈ \mathbb{R}^3``,
a * bpos := (a * Pose(bpos, orn)).pos
where `orn` is any orientation (and its value does not affect the result).
In words, `a * bpos` is the coordinates in the world frame of the vector whose
coordinates in the frame represented by `a` are `bpos`.
From this it's straightforward to see that the usual associativity law holds:
a * (b * cpos) = (a * b) * cpos
Therefore pose–point multiplication is indeed a group action of ``G`` on
``\mathbb{R}^3``.
This package implements both `Pose * point` and a vectorized version, `Pose *
pointcloud`, where `pointcloud` is a ``3 × N`` matrix in which each column
represents a point:
```julia-repl
julia> Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6)) * @SVector([7, 8, 9])
3-element StaticArrays.SArray{Tuple{3},Float64,1,3} with indices SOneTo(3):
11.340627918648092
8.023198113213361
10.126885626769848
julia> Pose([1, 2, 3], RotZYX(0.4, 0.5, 0.6)) * [7 10 13 16;
8 11 14 17;
9 12 15 18]
3×4 Array{Float64,2}:
11.3406 15.3024 19.2641 23.2258
8.0232 10.5473 13.0714 15.5955
10.1269 12.3481 14.5693 16.7904
```
## Second group structure: direct product of position and orientation
The composition operation described above and denoted by `*` is useful when
manipulating chains of relative poses, which commonly occur in scene graphs.
We now define a second group structure on the set of `Pose`s: the direct
product ``\mathbb{R}^3 × SO_3(\mathbb{R})``. We denote the group operation in
this second structure by `⊗`, and it means "add the positions and (separately)
compose the orientations." This operation models inertial motion, where an
object has separate translational and rotational velocities:
```math
\begin{aligned}
\mathbf{x} &= \mathbf{x}_0 + Δ\mathbf{x} \\
\boldsymbol{ω} &= \boldsymbol{ω}_0 \cdot Δ\boldsymbol{ω}
\end{aligned}
```
or simply
```julia
pose1 = pose0 ⊗ Δpose
```
This second group operation is implemented via the following infix operators:
* Multiplication: `pose1 ⊗ pose2` (``\LaTeX``: `\otimes`)
* Right-division: `pose1 ⊘ pose2` (``\LaTeX``: `\oslash`)
* Left-division: `pose1 ⦸ pose2` (``\LaTeX``: `\obslash`)
The direct product structure is useful for performing computations that treat
translational and rotational components separately, such as computing the pose
of a moving object by integrating its velocity. The translational and
rotational components of the velocity are integrated separately -- in
differential geometry terms, motion is governed by the [exponential
map](https://en.wikipedia.org/wiki/Exponential_map_(Lie_theory)) on the Lie
algebra of ``\mathbb{R}^3 × SO_3(\mathbb{R})``, not the Lie algebra of
``SE_3``.
### Inter/Extrapolation, a.k.a. stepping time forward a fractional number of times
One nice property of the direct product (and its physical application of
integrating a velocity) is that there is a straightforward analogue of the
physics 101 equation
```math
\mathbf{x} = \mathbf{x}_0 + t \mathbf{v}
```
where ``\mathbf{x}_0`` is the initial displacement of an object, ``t`` is time,
and ``\mathbf{v}`` is the object's velocity, which is assumed to stay constant.
That analogue is
pose = pose0 ⊗ interp(v, t)
where `pose`, `pose0` and `v` are `Pose`s, and `t` is a `Real`. The function
[`interp`](@ref) defines how to interpolate between doing nothing and
translating by `v.pos` (namely, scalar multiplication) and how to interpolate
between doing nothing and applying the rotation `v.orientation` (namely,
[SLERP](https://en.wikipedia.org/wiki/Slerp#Quaternion_Slerp)).
There is also a variant of `interp` that takes two pose arguments and
interpolates between them:
pose = interp(pose0, pose1, t)
which is equivalent to
pose = pose0 ⊗ interp(pose0 ⦸ pose1, t)
In particular, we have `pose = pose0` when `t = 0` and `pose = pose1` when `t =
1`.
| PoseComposition | https://github.com/probcomp/PoseComposition.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 3389 | """
The script sets all QuantumElectrodynamics dependencies of QuantumElectrodynamics
dependencies to the version of the current development branch. For our example we use the
project QEDprocess which has a dependency to QEDfields and QEDfields has a dependency to
QEDcore (I haven't checked if this is the case, it's just hypothetical). If we install
the dev-branch version of QEDfields, the last registered version of QEDcore is still
installed. If QEDfields uses a function which only exist in dev branch of QEDcore and
is not released yet, the integration test will fail.
The script needs to be executed the project space, which should be modified.
"""
using Pkg
# TODO(SimeonEhrig): is copied from integTestGen.jl
"""
_match_package_filter(
package_filter::Union{<:AbstractString,Regex},
package::AbstractString
)::Bool
Check if `package_filter` contains `package`. Wrapper function for `contains()` and `in()`.
# Returns
- `true` if it matches.
"""
function _match_package_filter(
package_filter::Union{<:AbstractString,Regex}, package::AbstractString
)::Bool
return contains(package, package_filter)
end
"""
_match_package_filter(
package_filter::AbstractVector{<:AbstractString},
package::AbstractString
)::Bool
"""
function _match_package_filter(
package_filter::AbstractVector{<:AbstractString}, package::AbstractString
)::Bool
return package in package_filter
end
"""
get_filtered_dependencies(
name_filter::Union{<:AbstractString,Regex}=r".*",
project_source=Pkg.dependencies()
)::AbstractVector{Pkg.API.PackageInfo}
Takes the project_dependencies and filter it by the name_filter. Removes also the UUID as
dict key.
# Returns
- `Vector` of filtered dependencies.
"""
function get_filtered_dependencies(
name_filter::Union{<:AbstractString,Regex}=r".*",
project_dependencies=Pkg.dependencies(),
)::AbstractVector{Pkg.API.PackageInfo}
deps = Vector{Pkg.API.PackageInfo}(undef, 0)
for (uuid, dep) in project_dependencies
if _match_package_filter(name_filter, dep.name)
push!(deps, dep)
end
end
return deps
end
"""
set_dev_dependencies(
dependencies::AbstractVector{Pkg.API.PackageInfo},
custom_urls::AbstractDict{String,String}=Dict{String,String}(),
)
Set all dependencies to the development version, if they are not already development versions.
The dict custom_urls takes as key a dependency name and a URL as value. If a dependency is in
custom_urls, it will use the URL as development version. If the dependency does not exist in
custom_urls, it will set the URL https://github.com/QEDjl-project/<dependency_name>.jl
"""
function set_dev_dependencies(
dependencies::AbstractVector{Pkg.API.PackageInfo},
custom_urls::AbstractDict{String,String}=Dict{String,String}(),
)
for dep in dependencies
# if tree_hash is nothing, it is already a dev version
if !isnothing(dep.tree_hash)
if haskey(custom_urls, dep.name)
Pkg.develop(; url=custom_urls[dep.name])
else
Pkg.develop(; url="https://github.com/QEDjl-project/$(dep.name).jl")
end
end
end
end
if abspath(PROGRAM_FILE) == @__FILE__
deps = get_filtered_dependencies(r"^(QED*|QuantumElectrodynamics*)")
set_dev_dependencies(deps)
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 1647 | """
The script checks, if a custom dependency for unit tests via `CI_UNIT_PKG_URL_<package_name>` is set.
If so, the script fails, which means in practice, that the PR relies on non-merged code.
"""
"""
extract_env_vars_from_git_message!()
Parse the commit message, if set via variable `CI_COMMIT_MESSAGE` and set custom URLs.
"""
function extract_env_vars_from_git_message!()
if haskey(ENV, "CI_COMMIT_MESSAGE")
@info "Found env variable CI_COMMIT_MESSAGE"
for line in split(ENV["CI_COMMIT_MESSAGE"], "\n")
line = strip(line)
if startswith(line, "CI_UNIT_PKG_URL_")
(var_name, url) = split(line, ":"; limit=2)
@info "add " * var_name * "=" * strip(url)
ENV[var_name] = strip(url)
end
end
end
end
struct EnvironmentVerificationException <: Exception
envs::Set{AbstractString}
end
function Base.showerror(io::IO, e::EnvironmentVerificationException)
local err_str = "Found custom dependencies for unit tests.\n"
for env in e.envs
err_str *= " $env\n"
end
err_str *= "\nPlease merge the custom dependency before and run the CI with custom dependency again."
return print(io, "EnvironmentVerificationException: ", err_str)
end
if abspath(PROGRAM_FILE) == @__FILE__
extract_env_vars_from_git_message!()
filtered_env = filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV))
if isempty(filtered_env)
@info "No custom dependencies for unit tests detected."
exit(0)
else
throw(EnvironmentVerificationException(filtered_env))
end
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 3711 | module SetupDevEnv
using TOML
using Pkg
"""
extract_env_vars_from_git_message!()
Parse the commit message, if set via variable (usual `CI_COMMIT_MESSAGE`) and set custom URLs.
"""
function extract_env_vars_from_git_message!(var_name="CI_COMMIT_MESSAGE")
if haskey(ENV, var_name)
@info "Found env variable $var_name"
for line in split(ENV[var_name], "\n")
line = strip(line)
if startswith(line, "CI_UNIT_PKG_URL_")
(var_name, url) = split(line, ":"; limit=2)
@info "add " * var_name * "=" * strip(url)
ENV[var_name] = strip(url)
end
end
end
end
"""
get_dependencies(project_toml_path::AbstractString, package_prefix::Union{AbstractString,Regex}=r".*")::Set{AbstractString}
Parses a Project.toml located at `project_toml_path` and returns all dependencies, matching the regex `package_prefix`.
By default, the regex allows all dependencies.
"""
function get_dependencies(
project_toml_path::AbstractString, package_prefix::Union{AbstractString,Regex}=r".*"
)::Set{AbstractString}
project_toml = TOML.parsefile(project_toml_path)
if !haskey(project_toml, "deps")
return Set()
end
filtered_deps = filter(
(dep_name) -> startswith(dep_name, package_prefix), keys(project_toml["deps"])
)
return filtered_deps
end
"""
add_develop_dep(dependencies::Set{AbstractString})
Add all dependencies listed in `dependencies` as development version. By default, it takes the current development branch.
If the environment variable "CI_UNIT_PKG_URL_<dependency_name>" is set, take the URL defined in the value to set
develop version, instead the the default develop branch (see `Pkg.develop(url=)`).
"""
function add_develop_dep(dependencies::Set{AbstractString})
# check if specific url was set for a dependency
env_prefix = "CI_UNIT_PKG_URL_"
modified_urls = Dict{String,String}()
for (env_key, env_var) in ENV
if startswith(env_key, env_prefix)
modified_urls[env_key[(length(env_prefix) + 1):end]] = env_var
end
end
if !isempty(modified_urls)
local info_str = "Found following env variables"
for (pkg_name, url) in modified_urls
info_str *= "\n " * pkg_name * "=" * url
end
@info info_str
end
# add all dependencies as develop version to the current julia environment
for dep in dependencies
if haskey(modified_urls, dep)
split_url = split(modified_urls[dep], "#")
if length(split_url) > 2
error("Ill formed url: $(url)")
end
if length(split_url) == 1
@info "Pkg.develop(url=\"" * split_url[1] * "\")"
Pkg.add(; url=split_url[1])
else
@info "Pkg.develop(url=\"" *
split_url[1] *
";\" rev=\"" *
split_url[2] *
"\")"
Pkg.add(; url=split_url[1], rev=split_url[2])
end
else
@info "Pkg.develop(\"" * dep * "\")"
Pkg.develop(dep)
end
end
end
if abspath(PROGRAM_FILE) == @__FILE__
if length(ARGS) < 1
error("Set path to Project.toml as first argument.")
end
project_toml_path = ARGS[1]
# custom commit message variable can be set as second argument
if length(ARGS) < 2
extract_env_vars_from_git_message!()
else
extract_env_vars_from_git_message!(ARGS[2])
end
# get only dependencies, which starts with QED
deps = get_dependencies(project_toml_path, r"(QED)")
add_develop_dep(deps)
end
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 4890 | using SetupDevEnv
using Test
@testset "SetupDevEnv.jl" begin
message_var_name = "TEST_CI_COMMIT_MESSAGE"
@testset "test extraction from Git Message" begin
@test !haskey(ENV, message_var_name)
# should not throw an error if the environment CI_COMMIT_MESSAGE does not exist
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
ENV[message_var_name] = """This is a normal feature.
The feature can do someting useful.
Be carful, when you use the feature.
"""
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
@test isempty(
filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV))
)
ENV[message_var_name] = """This is a normal feature.
The feature can do someting useful.
Be carful, when you use the feature.
CI_UNIT_PKG_URL_QEDbase: https://foo.com
"""
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
deps = (filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV)))
@test length(deps) == 1
ENV[message_var_name] = """This is a normal feature.
The feature can do someting useful.
Be carful, when you use the feature.
CI_UNIT_PKG_URL_QEDbase: https://foo.com
CI_UNIT_PKG_URL_QEDbase: https://bar.com
"""
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
deps = (filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV)))
@test length(deps) == 1
ENV[message_var_name] = """This is a normal feature.
The feature can do someting useful.
Be carful, when you use the feature.
CI_UNIT_PKG_URL_QEDbase: https://foo.com
CI_UNIT_PKG_URL_QEDfields: https://bar.com
"""
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
deps = (filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV)))
@test length(deps) == 2
ENV[message_var_name] = """This is a normal feature.
The feature can do someting useful.
Be carful, when you use the feature.
CI_UNIT_PKG_URL_QEDbase: https://foo.com
CI_UNIT_PKG_URL_QEDfields: https://bar.com
CI_UNIT_PKG_URL_QEDevents: https://foobar.com
"""
SetupDevEnv.extract_env_vars_from_git_message!(message_var_name)
deps = (filter((env_name) -> startswith(env_name, "CI_UNIT_PKG_URL_"), keys(ENV)))
@test length(deps) == 3
end
@testset "test dependency extraction from Poject.toml" begin
tmp_path = mktempdir()
@testset "no dependencies" begin
project_path = joinpath(tmp_path, "Project1.toml")
open(project_path, "w") do f
write(
f,
"""
name = "QuantumElectrodynamics"
uuid = "bb1fba1d-cf9b-41b3-874e-4b81465537b9"
authors = ["Uwe Hernandez Acosta <u.hernandez@hzdr.de>", "Simeon Ehrig", "Klaus Steiniger", "Tom Jungnickel", "Anton Reinhard"]
version = "0.1.0"
[compat]
julia = "1.9"
""",
)
end
@test isempty(SetupDevEnv.get_dependencies(project_path))
end
@testset "test filter" begin
project_path = joinpath(tmp_path, "Project2.toml")
open(project_path, "w") do f
write(
f,
"""
name = "QuantumElectrodynamics"
uuid = "bb1fba1d-cf9b-41b3-874e-4b81465537b9"
authors = ["Uwe Hernandez Acosta <u.hernandez@hzdr.de>", "Simeon Ehrig", "Klaus Steiniger", "Tom Jungnickel", "Anton Reinhard"]
version = "0.1.0"
[deps]
QEDbase = "10e22c08-3ccb-4172-bfcf-7d7aa3d04d93"
QEDevents = "fc3ce04a-5be5-4f3a-acff-eceaab723759"
QEDfields = "ac3a6c97-e859-4b9f-96bb-63d2a216042c"
QEDprocesses = "46de9c38-1bb3-4547-a1ec-da24d767fdad"
PhysicalConstants = "5ad8b20f-a522-5ce9-bfc9-ddf1d5bda6ab"
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
SimpleTraits = "699a6c99-e7fa-54fc-8d76-47d257e15c1d"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[compat]
julia = "1.9"
""",
)
end
@test length(SetupDevEnv.get_dependencies(project_path)) == 8
@test length(SetupDevEnv.get_dependencies(project_path, r"^QED")) == 4
@test length(SetupDevEnv.get_dependencies(project_path, r"^Simple")) == 1
@test length(SetupDevEnv.get_dependencies(project_path, r"^S")) == 2
@test length(SetupDevEnv.get_dependencies(project_path, "SparseArrays")) == 1
end
end
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 4099 | using HTTP
using JSON
using Pkg
"""
is_pull_request()::Bool
Checks whether the GitLab CI mirror branch was created by a GitHub pull request.
# Return
true if is a Pull Request branch, otherwise false
"""
function is_pull_request()::Bool
# GitLab CI provides the environemnt variable with the following pattern
# # pr-<PR number>/<repo owner of the source branch>/<project name>/<source branch name>
# e.g. pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps
if !haskey(ENV, "CI_COMMIT_REF_NAME")
error("Environment variable CI_COMMIT_REF_NAME is not set.")
end
return startswith(ENV["CI_COMMIT_REF_NAME"], "pr-")
end
"""
get_build_branch()::AbstractString
Returns the build branch except for version tags. In this case, main is returned.
# Return
build branch name
"""
function get_build_branch()::AbstractString
if !haskey(ENV, "CI_COMMIT_REF_NAME")
error("Environment variable CI_COMMIT_REF_NAME is not set.")
end
ci_commit_ref_name = string(ENV["CI_COMMIT_REF_NAME"])
try
VersionNumber(ci_commit_ref_name)
# branch is a version tag
return "main"
catch
return ci_commit_ref_name
end
end
"""
get_target_branch_pull_request()::AbstractString
Returns the name of the target branch of the pull request. The function is required for our special
setup where we mirror a PR from GitHub to GitLab CI. No merge request will be open on GitLab.
Instead, a feature branch will be created and the commit will be pushed. As a result, we lose
information about the original PR. So we need to use the GitHub Rest API to get the information
depending on the repository name and PR number.
"""
function get_target_branch_pull_request()::AbstractString
# GitLab CI provides the environemnt variable with the following pattern
# # pr-<PR number>/<repo owner of the source branch>/<project name>/<source branch name>
# e.g. pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps
if !haskey(ENV, "CI_COMMIT_REF_NAME")
error("Environment variable CI_COMMIT_REF_NAME is not set.")
end
splited_commit_ref_name = split(ENV["CI_COMMIT_REF_NAME"], "/")
if (!startswith(splited_commit_ref_name[1], "pr-"))
# fallback for unknown branches and dev branch
return "dev"
end
# parse to Int only to check if it is a number
pr_number = parse(Int, splited_commit_ref_name[1][(length("pr-") + 1):end])
if (pr_number <= 0)
error(
"a PR number always needs to be a positive integer number bigger than 0: $pr_number",
)
end
repository_name = splited_commit_ref_name[3]
try
headers = (
("Accept", "application/vnd.github+json"),
("X-GitHub-Api-Version", "2022-11-28"),
)
# in all cases, we assume that the PR targets the repositories in QEDjl-project
# there is no environment variable with the information, if the target repository is
# the upstream repository or a fork.
url = "https://api.github.com/repos/QEDjl-project/$repository_name/pulls/$pr_number"
response = HTTP.get(url, headers)
response_text = String(response.body)
repository_data = JSON.parse(response_text)
return repository_data["base"]["ref"]
catch e
# if for unknown reason, the PR does not exist, use fallback the dev branch
if isa(e, HTTP.Exceptions.StatusError) && e.status == 404
return "dev"
else
# Only the HTML code 404, page does not exist is handled. All other error will abort
# the script.
throw(e)
end
end
return "dev"
end
"""
get_target()::AbstractString
Return the correct target branch name for our GitLab CI mirror setup.
# Return
target branch name
"""
function get_target()::AbstractString
if is_pull_request()
return get_target_branch_pull_request()
else
return get_build_branch()
end
end
if abspath(PROGRAM_FILE) == @__FILE__
print(get_target())
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 15108 | module integTestGen
include("get_target_branch.jl")
using Pkg: Pkg
using PkgDependency: PkgDependency
using YAML: YAML
using Logging
"""
Contains all git-related information about a package.
# Fields
- `url`: Git url of the original project.
- `modified_url`: Stores the Git url set by the environment variable.
- `env_var`: Name of the environment variable to set the modified_url.
"""
mutable struct PackageInfo
url::String
modified_url::String
env_var::String
PackageInfo(url, env_var) = new(url, "", env_var)
end
"""
create_working_env(project_path::AbstractString, package_infos::AbstractDict{String,PackageInfo})
Create a temporary folder, and set up a new Project.toml and activate it. Checking the dependencies of
a project only works, if it is a dependency of the integTestGen.jl. The package to be analyzed
is only a temporary dependency, it must not change the Project.toml of integTestGen.jl permanently.
Therefore, the script generates a temporary Julia environment and adds the package
to analyze as a dependency.
# Args
`project_path::AbstractString`: Absolute path to the project folder of the package to be analyzed
`package_infos::AbstractDict{String,PackageInfo}`: List depending QED pojects of QuantumElectrodynamics.jl. Use the list to
add the current dev branch version of the packages to the environment or a custom repository with
custom branch.
"""
function create_working_env(
project_path::AbstractString, package_infos::AbstractDict{String,PackageInfo}
)
tmp_path = mktempdir()
Pkg.activate(tmp_path)
# same dependency like in the Project.toml of integTestGen.jl
Pkg.add("Pkg")
Pkg.add("PkgDependency")
Pkg.add("YAML")
# add main project as dependency
Pkg.develop(; path=project_path)
for package_info in values(package_infos)
if package_info.modified_url == ""
# add current dev branch version of the package
Pkg.add(; url=package_info.url)
continue
end
split_url = split(package_info.modified_url, "#")
if length(split_url) == 2
# add custom branch version of a custom repository
Pkg.add(; url=split_url[1], rev=split_url[2])
else
# add current dev branch version of a custom repository
Pkg.add(; url=split_url[1])
end
end
end
"""
extract_env_vars_from_git_message!(package_infos::AbstractDict{String, PackageInfo}, var_name = "CI_COMMIT_MESSAGE")
Parse the commit message, if set via variable (usual `CI_COMMIT_MESSAGE`), and set custom URLs.
"""
function extract_env_vars_from_git_message!(
package_infos::AbstractDict{String,PackageInfo}, var_name="CI_COMMIT_MESSAGE"
)
if haskey(ENV, var_name)
for line in split(ENV[var_name], "\n")
line = strip(line)
for pkg_info in values(package_infos)
if startswith(line, pkg_info.env_var * ": ")
ENV[pkg_info.env_var] = SubString(
line, length(pkg_info.env_var * ": ") + 1
)
end
end
end
end
end
"""
modify_package_url!(package_infos::AbstractDict{String, PackageInfo})
Iterate over all entries of package_info. If an environment variable exists with the same name as,
the `env_var` entry, set the value of the environment variable to `modified_url`.
"""
function modify_package_url!(package_infos::AbstractDict{String,PackageInfo})
for package_info in values(package_infos)
if haskey(ENV, package_info.env_var)
package_info.modified_url = ENV[package_info.env_var]
end
end
end
"""
modified_package_name(package_infos::AbstractDict{String, PackageInfo})
Read the name of the modified (project) package from the environment variable `CI_DEPENDENCY_NAME`.
# Returns
- The name of the modified (project) package
"""
function modified_package_name(package_infos::AbstractDict{String,PackageInfo})
for env_var in ["CI_DEPENDENCY_NAME", "CI_PROJECT_DIR"]
if !haskey(ENV, env_var)
error("Environment variable $env_var is not set.")
end
end
if !haskey(package_infos, ENV["CI_DEPENDENCY_NAME"])
package_name = ENV["CI_DEPENDENCY_NAME"]
error("Error unknown package name $package_name}")
else
return ENV["CI_DEPENDENCY_NAME"]
end
end
"""
depending_projects(package_name, package_prefix, project_tree)
Return a list of packages, which have the package `package_name` as a dependency. Ignore all packages, which do not start with `package_prefix`.
# Arguments
- `package_name::String`: Name of the dependency
- `package_filter`: If the package name is not included in package_filter, the dependency is not checked.
- `project_tree=PkgDependency.builddict(Pkg.project().uuid, Pkg.project())`: Project tree, where to search the dependent packages. Needs to be a nested dict.
Each (sub-) package needs to be AbstractDict{String, AbstractDict}
# Returns
- `::AbstractVector{String}`: all packages which have the search dependency
"""
function depending_projects(
package_name::String,
package_filter::AbstractVector{<:AbstractString},
project_tree=PkgDependency.builddict(Pkg.project().uuid, Pkg.project()),
)::AbstractVector{String}
packages::AbstractVector{String} = []
visited_packages::AbstractVector{String} = []
traverse_tree!(package_name, package_filter, project_tree, packages, visited_packages)
return packages
end
function clean_pkg_name(pkg_name::AbstractString)
# remove color tags (?) from the package names
return replace(pkg_name, r"\{[^}]*\}" => "")
end
"""
traverse_tree!(package_name::String, package_filter, project_tree, packages::AbstractVector{String}, visited_packages::AbstractVector{String})
Traverse a project tree and add any package to `packages`, that has the package `package_name` as a dependency. Ignore all packages that are not included in `package_filter`.
See [`depending_projects`](@ref)
"""
function traverse_tree!(
package_name::String,
package_filter::AbstractVector{<:AbstractString},
project_tree::AbstractVector{<:PkgDependency.PkgTree},
packages::AbstractVector{String},
visited_packages::AbstractVector{String},
)
for pkg_tree in project_tree
project_name_version = clean_pkg_name(pkg_tree.name)
# remove project version from string -> usual shape: `packageName.jl version`
project_name = split(project_name_version)[1]
# fullfil the requirements
# - package starts with the prefix
# - the dependency is not nothing (I think this representate, that the package was already set as dependency of a another package and therefore do not repead the dependencies)
# - has dependency
# - was not already checked
if project_name in package_filter &&
!isempty(pkg_tree.children) &&
!(project_name in visited_packages)
# only investigate each package one time
# assumption: package name with it's dependency is unique
push!(visited_packages, project_name)
for dependency in pkg_tree.children
dependency_name_version = clean_pkg_name(dependency.name)
# dependency matches, add to packages
if startswith(dependency_name_version, package_name)
push!(packages, project_name)
break
end
end
# independent of a match, investigate all dependencies too, because they can also have the package as dependency
traverse_tree!(
package_name, package_filter, pkg_tree.children, packages, visited_packages
)
end
end
end
"""
generate_job_yaml!(package_name::String, job_yaml::Dict)
Generate GitLab CI job yaml for integration testing of a given package.
# Args
- `package_name::String`: Name of the package to test.
- `target_branch::AbstractString`: Name of the target branch of the pull request.
- `ci_project_dir::AbstractString`: Path of QED project which should be used for the integration test.
- `job_yaml::Dict`: Add generated job to this dict.
- `package_infos::AbstractDict{String,PackageInfo}`: Contains serveral information about QED packages
- `can_fail::Bool=false`: If true add `allow_failure=true` to the job yaml
"""
function generate_job_yaml!(
package_name::String,
target_branch::AbstractString,
ci_project_dir::AbstractString,
job_yaml::Dict,
package_infos::AbstractDict{String,PackageInfo},
can_fail::Bool=false,
)
package_info = package_infos[package_name]
# if modified_url is empty, use original url
if package_info.modified_url == ""
url = package_info.url
else
url = package_info.modified_url
end
script = ["apt update", "apt install -y git", "cd /"]
split_url = split(url, "#")
if length(split_url) > 2
error("Ill formed url: $(url)")
end
push!(script, "git clone -b $target_branch $(split_url[1]) integration_test")
if (target_branch != "main")
push!(
script,
"git clone -b dev https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git /integration_test_tools",
)
end
push!(script, "cd integration_test")
# checkout specfic branch given by the environemnt variable
# CI_INTG_PKG_URL_<dep_name>=https://url/to/the/repository#<commit_hash>
if length(split_url) == 2
push!(script, "git checkout $(split_url[2])")
end
push!(
script,
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/QEDjl-project/registry.git\"));'",
)
push!(
script,
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/JuliaRegistries/General\"));'",
)
push!(
script, "julia --project=. -e 'import Pkg; Pkg.develop(path=\"$ci_project_dir\");'"
)
if (target_branch != "main")
push!(
script, "julia --project=. /integration_test_tools/.ci/set_dev_dependencies.jl"
)
end
push!(script, "julia --project=. -e 'import Pkg; Pkg.test(; coverage = true)'")
current_job_yaml = Dict(
"image" => "julia:1.9",
"interruptible" => true,
"tags" => ["cpuonly"],
"script" => script,
)
if can_fail
current_job_yaml["allow_failure"] = true
return job_yaml["IntegrationTest$(package_name)ReleaseTest"] = current_job_yaml
else
return job_yaml["IntegrationTest$package_name"] = current_job_yaml
end
end
"""
generate_dummy_job_yaml!(job_yaml::Dict)
Generates a GitLab CI dummy job, if required.
# Args
- `job_yaml::Dict`: Add generated job to this dict.
"""
function generate_dummy_job_yaml!(job_yaml::Dict)
return job_yaml["DummyJob"] = Dict(
"image" => "alpine:latest",
"interruptible" => true,
"script" => ["echo \"This is a dummy job so that the CI does not fail.\""],
)
end
"""
get_package_info()::Dict{String,PackageInfo}
Returns a list with QED project package information.
"""
function get_package_info()::Dict{String,PackageInfo}
return Dict(
"QuantumElectrodynamics" => PackageInfo(
"https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git",
"CI_INTG_PKG_URL_QED",
),
"QEDfields" => PackageInfo(
"https://github.com/QEDjl-project/QEDfields.jl.git",
"CI_INTG_PKG_URL_QEDfields",
),
"QEDbase" => PackageInfo(
"https://github.com/QEDjl-project/QEDbase.jl.git", "CI_INTG_PKG_URL_QEDbase"
),
"QEDevents" => PackageInfo(
"https://github.com/QEDjl-project/QEDevents.jl.git",
"CI_INTG_PKG_URL_QEDevents",
),
"QEDprocesses" => PackageInfo(
"https://github.com/QEDjl-project/QEDprocesses.jl.git",
"CI_INTG_PKG_URL_QEDprocesses",
),
"QEDcore" => PackageInfo(
"https://github.com/QEDjl-project/QEDcore.jl.git", "CI_INTG_PKG_URL_QEDcore"
),
)
end
if abspath(PROGRAM_FILE) == @__FILE__
if !haskey(ENV, "CI_COMMIT_REF_NAME")
@warn "Environemnt variable CI_COMMIT_REF_NAME not defined. Use default branch `dev`."
target_branch = "dev"
else
target_branch = get_target()
end
package_infos = get_package_info()
# custom commit message variable can be set as first argument
if length(ARGS) < 1
extract_env_vars_from_git_message!(package_infos)
else
extract_env_vars_from_git_message!(package_infos, ARGS[1])
end
modify_package_url!(package_infos)
modified_pkg = modified_package_name(package_infos)
# the script is locate in ci/integTestGen/src
# so we need to go 3 steps upwards in hierarchy to get the QuantumElectrodynamics.jl Project.toml
create_working_env(abspath(joinpath((@__DIR__), "../../..")), package_infos)
depending_pkg = depending_projects(modified_pkg, collect(keys(package_infos)))
job_yaml = Dict()
if !isempty(depending_pkg)
for p in depending_pkg
# Handles the case of merging in the main branch. If we want to merge in the main branch,
# we do it because we want to publish the package. Therefore, we need to be sure that there
# is an existing version of the dependent QED packages that works with the new version of
# the package we want to release. The integration tests are tested against the development
# branch and the release version.
# - The dev branch version must pass, as this means that the latest version of the other
# QED packages is compatible with our release version.
# - The release version integration tests may or may not pass.
# 1. If all of these pass, we will not need to increase the minor version of this package.
# 2. If they do not all pass, the minor version must be increased and the failing packages
# must also be released later with an updated compat entry.
# In either case the release can proceed, as the released packages will continue to work
# because of their current compat entries.
if target_branch == "main" && is_pull_request()
generate_job_yaml!(p, "dev", ENV["CI_PROJECT_DIR"], job_yaml, package_infos)
generate_job_yaml!(
p, "main", ENV["CI_PROJECT_DIR"], job_yaml, package_infos, true
)
else
generate_job_yaml!(
p, target_branch, ENV["CI_PROJECT_DIR"], job_yaml, package_infos
)
end
end
else
generate_dummy_job_yaml!(job_yaml)
end
println(YAML.write(job_yaml))
end
end # module integTestGen
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 8301 | using YAML
"""
yaml_diff(given, expected)::AbstractString
Generates an error string that shows a given and an expected data structure in yaml
representation.
# Returns
- Human readable error message for the comparison of two job yaml's.
"""
function yaml_diff(given, expected)::AbstractString
output = "\ngiven:\n"
output *= String(YAML.yaml(given))
output *= "\nexpected:\n"
output *= String(YAML.yaml(expected))
return output
end
@testset "generate_job_yaml()" begin
package_infos = integTestGen.get_package_info()
@testset "target main branch, no PR" begin
job_yaml = Dict()
integTestGen.generate_job_yaml!(
"QEDcore", "main", "/path/to/QEDcore.jl", job_yaml, package_infos
)
@test length(job_yaml) == 1
expected_job_yaml = Dict()
expected_job_yaml["IntegrationTestQEDcore"] = Dict(
"image" => "julia:1.9",
"interruptible" => true,
"tags" => ["cpuonly"],
"script" => [
"apt update",
"apt install -y git",
"cd /",
"git clone -b main $(package_infos["QEDcore"].url) integration_test",
"cd integration_test",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/QEDjl-project/registry.git\"));'",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/JuliaRegistries/General\"));'",
"julia --project=. -e 'import Pkg; Pkg.develop(path=\"/path/to/QEDcore.jl\");'",
"julia --project=. -e 'import Pkg; Pkg.test(; coverage = true)'",
],
)
@test (
@assert job_yaml["IntegrationTestQEDcore"]["script"] ==
expected_job_yaml["IntegrationTestQEDcore"]["script"] yaml_diff(
job_yaml["IntegrationTestQEDcore"]["script"],
expected_job_yaml["IntegrationTestQEDcore"]["script"],
);
true
)
@test (
@assert job_yaml["IntegrationTestQEDcore"] ==
expected_job_yaml["IntegrationTestQEDcore"] yaml_diff(
job_yaml["IntegrationTestQEDcore"],
expected_job_yaml["IntegrationTestQEDcore"],
);
true
)
end
@testset "target non main branch, if PR or not is the same" begin
job_yaml = Dict()
integTestGen.generate_job_yaml!(
"QEDcore", "feature3", "/path/to/QEDcore.jl", job_yaml, package_infos
)
@test length(job_yaml) == 1
expected_job_yaml = Dict()
expected_job_yaml["IntegrationTestQEDcore"] = Dict(
"image" => "julia:1.9",
"interruptible" => true,
"tags" => ["cpuonly"],
"script" => [
"apt update",
"apt install -y git",
"cd /",
"git clone -b feature3 $(package_infos["QEDcore"].url) integration_test",
"git clone -b dev https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git /integration_test_tools",
"cd integration_test",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/QEDjl-project/registry.git\"));'",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/JuliaRegistries/General\"));'",
"julia --project=. -e 'import Pkg; Pkg.develop(path=\"/path/to/QEDcore.jl\");'",
"julia --project=. /integration_test_tools/.ci/set_dev_dependencies.jl",
"julia --project=. -e 'import Pkg; Pkg.test(; coverage = true)'",
],
)
@test (
@assert job_yaml["IntegrationTestQEDcore"]["script"] ==
expected_job_yaml["IntegrationTestQEDcore"]["script"] yaml_diff(
job_yaml["IntegrationTestQEDcore"]["script"],
expected_job_yaml["IntegrationTestQEDcore"]["script"],
);
true
)
@test (
@assert job_yaml["IntegrationTestQEDcore"] ==
expected_job_yaml["IntegrationTestQEDcore"] yaml_diff(
job_yaml["IntegrationTestQEDcore"],
expected_job_yaml["IntegrationTestQEDcore"],
);
true
)
end
@testset "target main branch, PR" begin
job_yaml = Dict()
integTestGen.generate_job_yaml!(
"QEDcore", "dev", "/path/to/QEDcore.jl", job_yaml, package_infos
)
integTestGen.generate_job_yaml!(
"QEDcore", "main", "/path/to/QEDcore.jl", job_yaml, package_infos, true
)
@test length(job_yaml) == 2
expected_job_yaml = Dict()
expected_job_yaml["IntegrationTestQEDcore"] = Dict(
"image" => "julia:1.9",
"interruptible" => true,
"tags" => ["cpuonly"],
"script" => [
"apt update",
"apt install -y git",
"cd /",
"git clone -b dev $(package_infos["QEDcore"].url) integration_test",
"git clone -b dev https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git /integration_test_tools",
"cd integration_test",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/QEDjl-project/registry.git\"));'",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/JuliaRegistries/General\"));'",
"julia --project=. -e 'import Pkg; Pkg.develop(path=\"/path/to/QEDcore.jl\");'",
"julia --project=. /integration_test_tools/.ci/set_dev_dependencies.jl",
"julia --project=. -e 'import Pkg; Pkg.test(; coverage = true)'",
],
)
@test (
@assert job_yaml["IntegrationTestQEDcore"]["script"] ==
expected_job_yaml["IntegrationTestQEDcore"]["script"] yaml_diff(
job_yaml["IntegrationTestQEDcore"]["script"],
expected_job_yaml["IntegrationTestQEDcore"]["script"],
);
true
)
@test (
@assert job_yaml["IntegrationTestQEDcore"] ==
expected_job_yaml["IntegrationTestQEDcore"] yaml_diff(
job_yaml["IntegrationTestQEDcore"],
expected_job_yaml["IntegrationTestQEDcore"],
);
true
)
expected_job_yaml["IntegrationTestQEDcoreReleaseTest"] = Dict(
"image" => "julia:1.9",
"interruptible" => true,
"tags" => ["cpuonly"],
"allow_failure" => true,
"script" => [
"apt update",
"apt install -y git",
"cd /",
"git clone -b main $(package_infos["QEDcore"].url) integration_test",
"cd integration_test",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/QEDjl-project/registry.git\"));'",
"julia --project=. -e 'import Pkg; Pkg.Registry.add(Pkg.RegistrySpec(url=\"https://github.com/JuliaRegistries/General\"));'",
"julia --project=. -e 'import Pkg; Pkg.develop(path=\"/path/to/QEDcore.jl\");'",
"julia --project=. -e 'import Pkg; Pkg.test(; coverage = true)'",
],
)
@test (
@assert job_yaml["IntegrationTestQEDcoreReleaseTest"]["script"] ==
expected_job_yaml["IntegrationTestQEDcoreReleaseTest"]["script"] yaml_diff(
job_yaml["IntegrationTestQEDcoreReleaseTest"]["script"],
expected_job_yaml["IntegrationTestQEDcoreReleaseTest"]["script"],
);
true
)
@test (
@assert job_yaml["IntegrationTestQEDcoreReleaseTest"] ==
expected_job_yaml["IntegrationTestQEDcoreReleaseTest"] yaml_diff(
job_yaml["IntegrationTestQEDcoreReleaseTest"],
expected_job_yaml["IntegrationTestQEDcoreReleaseTest"],
);
true
)
end
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 2004 | @testset "test is_pull_request()" begin
@testset "no environemnt variable CI_COMMIT_REF_NAME set" begin
if haskey(ENV, "CI_COMMIT_REF_NAME")
delete!(ENV, "CI_COMMIT_REF_NAME")
end
@test_throws ErrorException integTestGen.is_pull_request()
end
@testset "empty CI_COMMIT_REF_NAME" begin
ENV["CI_COMMIT_REF_NAME"] = ""
@test integTestGen.is_pull_request() == false
end
for (ref_name, expected_result) in (
("pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps", true),
("main", false),
("dev", false),
("v0.1.0", false),
)
@testset "CI_COMMIT_REF_NAME=$(ref_name)" begin
ENV["CI_COMMIT_REF_NAME"] = ref_name
@test integTestGen.is_pull_request() == expected_result
end
end
end
@testset "test get_build_branch()" begin
@testset "no environemnt variable CI_COMMIT_REF_NAME set" begin
if haskey(ENV, "CI_COMMIT_REF_NAME")
delete!(ENV, "CI_COMMIT_REF_NAME")
end
@test_throws ErrorException integTestGen.get_build_branch()
end
for (ref_name, expected_result) in (
(
"pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps",
"pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps",
),
("main", "main"),
("dev", "dev"),
("v0.1.0", "main"),
("v0.asd.0", "v0.asd.0"),
("feature3", "feature3"),
)
@testset "CI_COMMIT_REF_NAME=$(ref_name)" begin
ENV["CI_COMMIT_REF_NAME"] = ref_name
@test integTestGen.get_build_branch() == expected_result
end
end
end
@testset "test get_target_branch_pull_request()" begin
@testset "no environemnt variable CI_COMMIT_REF_NAME set" begin
if haskey(ENV, "CI_COMMIT_REF_NAME")
delete!(ENV, "CI_COMMIT_REF_NAME")
end
@test_throws ErrorException integTestGen.get_target_branch_pull_request()
end
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 5627 | using PkgDependency
import Term.Trees: Tree
import PkgDependency.PkgTree
# set environment variable PRINTTREE=on to visualize the project trees of the testsets
# TODO(SimeonEhrig): add type ::Bool , when minimum version is Julia 1.9
printTree = haskey(ENV, "PRINTTREE")
@testset "direct dependency to main" begin
project_tree = [PkgTree("MyMainProject.jl 1.0.0", [PkgTree("MyDep1.jl 1.0.0", [])])]
if printTree
display(
PkgDependency.Tree(
PkgTree("Direct dependency to main tree", project_tree);
printkeys=false,
print_node_function=PkgDependency.writenode,
),
)
end
# dependency exist and prefix is correct
@test integTestGen.depending_projects(
"MyDep1.jl", ["MyMainProject.jl"], project_tree
) == ["MyMainProject.jl"]
# dependency does not exist and prefix is correct
@test isempty(
integTestGen.depending_projects("MyDep2.jl", ["MyMainProject.jl"], project_tree)
)
# dependency exist and prefix is incorrect
@test isempty(
integTestGen.depending_projects("MyDep1.jl", ["ExternProject.jl"], project_tree)
)
# dependency does not exist and prefix is incorrect
@test isempty(
integTestGen.depending_projects("MyDep2.jl", ["ExternProject.jl"], project_tree)
)
end
@testset "complex dependencies" begin
#! format: off
project_tree = [
PkgTree("MyMainProject.jl 1.0.0", [
PkgTree("MyDep1.jl 1.0.0", []),
PkgTree("MyDep2.jl 1.0.0", [
PkgTree("MyDep3.jl 1.0.0", []),
PkgTree("ForeignDep1.jl 1.0.0", [])
]),
PkgTree("ForeignDep2.jl 1.0.0", [
PkgTree("ForeignDep3.jl 1.0.0", []),
PkgTree("ForeignDep4.jl 1.0.0", [])
]),
PkgTree("MyDep4.jl 1.0.0", [
PkgTree("MyDep5.jl 1.0.0", [
PkgTree("MyDep3.jl 1.0.0", [])
])
]),
PkgTree("ForeignDep2.jl 1.0.0", [
PkgTree("MyDep5.jl 1.0.0", [
PkgTree("MyDep3.jl 1.0.0", [])
]),
PkgTree("MyDep3.jl 1.0.0", []),
PkgTree("MyDep6.jl 1.0.0", [
PkgTree("MyDep3.jl 1.0.0", [])
])
]),
PkgTree("MyDep7.jl 1.0.0", [
PkgTree("MyDep5.jl 1.0.0", [
PkgTree("MyDep3.jl 1.0.0", [])
]),
PkgTree("MyDep3.jl 1.0.0", [])
])
])
]
#! format: on
if printTree
display(
PkgDependency.Tree(
PkgTree("Complex dependency tree", project_tree);
printkeys=false,
print_node_function=PkgDependency.writenode,
),
)
end
package_filter = [
"MyMainProject.jl",
"MyDep1.jl",
"MyDep2.jl",
"MyDep3.jl",
"MyDep4.jl",
"MyDep5.jl",
"MyDep6.jl",
"MyDep7.jl",
]
# sort all vectors to guaranty the same order -> guaranty is not important for the actual result, onyl for comparison
@test sort(
integTestGen.depending_projects("MyDep1.jl", package_filter, project_tree)
) == sort(["MyMainProject.jl"])
@test sort(
integTestGen.depending_projects("MyDep2.jl", package_filter, project_tree)
) == sort(["MyMainProject.jl"])
# MyDep5.jl should only appears one time -> MyDep4.jl and MyDep7.jl has the same MyDep5.jl dependency
@test sort(
integTestGen.depending_projects("MyDep3.jl", package_filter, project_tree)
) == sort(["MyDep2.jl", "MyDep5.jl", "MyDep7.jl"])
@test sort(
integTestGen.depending_projects("MyDep5.jl", package_filter, project_tree)
) == sort(["MyDep4.jl", "MyDep7.jl"])
# cannot find MyDep6.jl, because it is only a dependency of a foreign package
@test isempty(
integTestGen.depending_projects("MyDep6.jl", package_filter, project_tree)
)
@test isempty(integTestGen.depending_projects("MyDep3.jl", ["Foo"], project_tree))
end
@testset "circular dependency" begin
# I cannot create a real circular dependency with this data structur, but if Circulation appears in an output, we passed MyDep1.jl and MyDep2.jl two times, which means it is a circle
#! format: off
project_tree = [
PkgTree("MyMainProject.jl 1.0.0", [
PkgTree("MyDep1.jl 1.0.0", [
PkgTree("MyDep2.jl 1.0.0", [
PkgTree("MyDep1.jl 1.0.0", [
PkgTree("MyDep2.jl 1.0.0", [
PkgTree("Circulation", [])
])
])
])
])
])
]
#! format: on
if printTree
display(
PkgDependency.Tree(
PkgTree("Circular dependency tree", project_tree);
printkeys=false,
print_node_function=PkgDependency.writenode,
),
)
end
package_filter = ["MyMainProject.jl", "MyDep1.jl", "MyDep2.jl"]
@test sort(
integTestGen.depending_projects("MyDep1.jl", package_filter, project_tree)
) == sort(["MyMainProject.jl", "MyDep2.jl"])
@test sort(
integTestGen.depending_projects("MyDep2.jl", package_filter, project_tree)
) == sort(["MyDep1.jl"])
@test isempty(integTestGen.depending_projects("MyDep2.jl", ["Foo"], project_tree))
@test isempty(
integTestGen.depending_projects("Circulation", package_filter, project_tree)
)
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 128 | using integTestGen
using Test
include("./integTestGen.jl")
include("./get_target_branch.jl")
include("./generate_job_yaml.jl")
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 408 | using JuliaFormatter
# we asume the format_all.jl script is located in QEDbase.jl/.formatting
project_path = Base.Filesystem.joinpath(Base.Filesystem.dirname(Base.source_path()), "..")
not_formatted = format(project_path; verbose=true)
if not_formatted
@info "Formatting verified."
else
@warn "Formatting verification failed: Some files are not properly formatted!"
end
exit(not_formatted ? 0 : 1)
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 916 | using QuantumElectrodynamics
using Documenter
DocMeta.setdocmeta!(
QuantumElectrodynamics, :DocTestSetup, :(using QuantumElectrodynamics); recursive=true
)
makedocs(;
modules=[QuantumElectrodynamics],
authors="Uwe Hernandez Acosta <u.hernandez@hzdr.de>, Simeon Ehrig, Klaus Steiniger, Tom Jungnickel, Anton Reinhard",
repo=Documenter.Remotes.GitHub("QEDjl-project", "QuantumElectrodynamics.jl"),
sitename="QuantumElectrodynamics.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://qedjl-project.github.io/QuantumElectrodynamics.jl/",
edit_link="dev",
assets=String[],
),
pages=[
"Home" => "index.md",
"Automatic Testing" => "ci.md",
"Development Guide" => "dev_guide.md",
],
)
deploydocs(;
repo="github.com/QEDjl-project/QuantumElectrodynamics.jl.git", push_preview=false
)
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 181 | module QuantumElectrodynamics
using Reexport
@reexport using QEDbase
@reexport using QEDcore
@reexport using QEDprocesses
@reexport using QEDevents
@reexport using QEDfields
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 628 | using QuantumElectrodynamics
# just test one basic symbol of each project to make sure the project has been reexported into QuantumElectrodynamics.jl
@testset "QEDbase" begin
@test isdefined(QuantumElectrodynamics, :AbstractParticle)
end
@testset "QEDcore" begin
@test isdefined(QuantumElectrodynamics, :ParticleStateful)
end
@testset "QEDprocesses" begin
@test isdefined(QuantumElectrodynamics, :Compton)
end
@testset "QEDfields" begin
@test isdefined(QuantumElectrodynamics, :AbstractBackgroundField)
end
@testset "QEDevents" begin
@test isdefined(QuantumElectrodynamics, :SingleParticleDistribution)
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | code | 116 | using QuantumElectrodynamics
using SafeTestsets
@time @safetestset "Reexport" begin
include("reexport.jl")
end
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 4859 | # Changelog
## Version 0.1.0
**Initial Release**
This release includes the incorporation of the following packages:
- [`QEDbase.jl`](https://github.com/QEDjl-project/QEDbase.jl)
- [`QEDcore.jl`](https://github.com/QEDjl-project/QEDcore.jl)
- [`QEDprocesses.jl`](https://github.com/QEDjl-project/QEDprocesses.jl)
- [`QEDevents.jl`](https://github.com/QEDjl-project/QEDevents.jl)
- [`QEDfields.jl`](https://github.com/QEDjl-project/QEDfields.jl)
Most of the functionality outside of these packages is concerned with continuous integration workflow files and generating integration tests.
### New features
- [#2](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/2): Add QED subpackages as dependencies
- [#3](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/3): Enable unit testing with custom URLs via commit message
- [#4](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/4): Add integration test generation
- [#15](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/15): Add code formatting to CI
- [#20](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/20): Add compat helper to CI
- [#24](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/24): Add documentation build job to CI
- [#41](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/41): Add script to set dependencies to their dev versions in integration tests for PRs to `main`
- [#43](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/43): Add script to determine PR target branch in GitLab CI
- [#44](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/44): Add script to set all dependencies to their `dev` versions
- [#45](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/45): Set dependencies to dev versions in doc building job when target is not main
- [#57](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/57): Correctly handle dev and main branches in `get_target_branch.jl`
- [#58](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/58): Add a template for release issues in QEDjl-project repositories to the docs
- [#62](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/62): Add more documentation for the release process of QEDjl-project repositories
- [#64](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/64): Rename the project and repository to `QuantumElectrodynamics.jl` (previously `QED.jl`, rejected in the general registry because of only 3 letters)
### Fixes
- [#5](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/5): Disable custom subpackage URLs in dependent packages on `dev` and `main` branches
- [#10](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/10): Remove Compat helper
- [#14](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/14): Remove `Manifest.toml` since libraries should not rely on this
- [#19](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/19): Use dev branches instead of the registry to build dependency graph for integration tests
- [#25](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/25): Run compat helper only on upstream repositories
- [#31](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/31): Fix integration test generation after dependency updated
- [#32](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/32): Second fix for dependency update, changed overlooked function signature
- [#52](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/52): Fix CI script for docs deployment
- [#53](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/53): Fix stable docs badge link
- [#63](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/63): Fix integration tests for merges to the main branch
- [#66](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/66): Fix regex in `dev_dependencies`, introduced while renaming the project in #64
### Maintenance
- [#11](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/11): Add install instructions
- [#17](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/17): Run unit tests with Julia versions `1.6` to `1.10` and `rc`
- [#26](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/26): Add compat entry for QEDprocesses (`v0.1`)
- [#38](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/38): Remove QEDprocesses compat
- [#39](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/39): Add new package QEDcore.jl to integration test package info
- [#51](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/51): Add Reexport compat entry (v1.2)
- [#60](https://github.com/QEDjl-project/QuantumElectrodynamics.jl/pull/60): Refactoring of `get_target_branch.jl`
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 943 | # QuantumElectrodynamics
[](https://qedjl-project.github.io/QuantumElectrodynamics.jl/stable)
[](https://qedjl-project.github.io/QuantumElectrodynamics.jl/dev)
[](https://github.com/invenia/BlueStyle)
## Installation
To install the current stable version of `QuantumElectrodynamics.jl`, you may use the standard julia package manager within the julia REPL:
```julia
julia> using Pkg
julia> Pkg.add("QuantumElectrodynamics")
```
or you use the Pkg prompt by hitting `]` within the Julia REPL and then type
```julia
(@v1.10) pkg> add QuantumElectrodynamics
```
To install the locally downloaded package on Windows, change to the parent directory and type within the Pkg prompt
```julia
(@v1.10) pkg> add ./QuantumElectrodynamics.jl
```
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 971 | # Usage
The application `SetupDevEnv.jl` takes a `Project.toml` and adds all dependencies which match a filter rule as the development version to the current Julia environment. The first application parameter sets the Project.toml path.
```bash
julia --project=/path/to/the/julia/environment src/SetupDevEnv.jl /path/to/Project.toml
```
# Optional Environment variables
All dependencies are added via `Pkg.develop("dep_name")` by default. Therefore the default development branch is used. To set a custom URL, you can define the environment variables `CI_UNIT_PKG_URL_<dep_name>`. For example, you set the environment variable `CI_UNIT_PKG_URL_QEDbase=https://github.com/User/QEDbase.jl#feature1`, the script will execute the command `Pkg.develop(url="https://github.com/User/QEDbase.jl#feature1")`, when the dependency QEDbase was found and matched in the `Project.toml`. Then the branch `feature1` from `https://github.com/User/QEDbase.jl` is used as a dependency.
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 1584 | # Usage
The application `integTestGen.jl` searches for all packages that depend on the searched package. For each package found, a job yaml is generated. The script is configured via environment variables.
## Required Environment Variables
- **CI_DEPENDENCY_NAME**: Name of the searched dependency.
- **CI_PROJECT_DIR**: Directory path of a package (containing the `Project.toml`) providing the dependency graph. Usually it is the absolute base path of the `QuantumElectrodynamics.jl` project.
You can set the environment variables in two different ways:
1. Permanent for the terminal session via: `export CI_PROJECT_DIR=/path/to/the/project`
2. Only for a single command (Julia call): `CI_PROJECT_DIR=/path/to/the/project CI_DEPENDENCY_NAME=QEDproject julia --project=. src/integTestGen.jl`
## Optional Environment Variables
By default, if an integration test is generated it clones the develop branch of the upstream project. The clone can be overwritten by the environment variable `CI_INTG_PKG_URL_<dep_name>=https://url/to/the/repository#<commit_hash>`. You can find all available environment variables in the dictionary `package_infos` in the `integTestGen.jl`.
Set the environment variable `CI_COMMIT_REF_NAME` to determine the target branch of a GitHub pull request. The form must be `CI_COMMIT_REF_NAME=pr-<PR number>/<repo owner of source branch>/<project name>/<source branch name>`. Here is an example: `CI_COMMIT_REF_NAME=pr-41/SimeonEhrig/QuantumElectrodynamics.jl/setDevDepDeps`. If the environment variable is not set, the default target branch `dev` is used.
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 14892 | # Automatic Testing
In the `QuantumElectrodynamics.jl` eco-system, we use [Continuous integration](https://en.wikipedia.org/wiki/Continuous_integration) (CIs) for running automatic tests. Each time, when a pull request is opened on GitHub.com or changes are committed to an existing pull request, the CI pipeline is triggered and starts a test script. The result of the tests will be reported in the pull request. In `QuantumElectrodynamics.jl`, we distinguish between two kinds of tests
- **Unit tests**: tests which check the functionality of the modified (sub-) package. Those tests can either run standalone or use the functionality of other (third-party) packages.
- **Integration tests**: tests which check the interoperatebility of the modified package with all sub-packages. For example, if package `A` depends on package `B` and you change package `B`, the integration test will check, if package `A` still works with the new version of package `B`.
The CI will first execute the unit tests. Then, if all unit tests are passed, the integration tests will be started.
Our CI uses the [GitLab CI](https://docs.gitlab.com/ee/ci/) because it allows us to use CI resources provided by [HIFIS](https://www.hifis.net/). There, we can use strong CPU runners and special runners for testing on Nvidia and AMD GPUs.
# Unit Tests for CI Users
The unit tests are automatically triggered, if you open a pull request, which target the `main` or `dev` branch. Before the tests start, the CI sets up the test environment. Thus, the `Project.toml` of the project is taken and the latest development version of each QuantumElectrodynamics.jl dependency is added. Other dependencies will regularly be resolved by the Julia Package manager. Afterwards the unit tests will be executed.
You can also modify which version of a `QuantumElectrodynamics.jl` dependency should be used. For example if you need to test your code with a function, which is not merged in the development branch yet. Thus, you need to add a specific line to your commit message with the following format:
```
CI_UNIT_PKG_URL_<dep_name>: https://github.com/<user>/<dep_name>#<commit_hash>
```
You can find the `<dep_name>` name in the `Project.toml` of the dependent project. For example, let's assume the name of the dependent package is `depLibrary`. The url of the fork is https://github.com/user/depLibrary.jl and the required feature has the commit sha `45a753b`.
```
This commit extends function foo with a new
function argument.
The function argument is required to control
the new functionality.
If you pass a 0, it has a special meaning.
CI_UNIT_PKG_URL_depLibrary: https://github.com/user/depLibrary.jl#45a753b
```
It is also possible to set a custom URL for more than one package. Simply add an additional line with the format `CI_UNIT_PKG_URL_<dep_name>: https://github.com/<user>/<dep_name>#<commit_hash>` to the commit message.
!!! note
You don't need to add a new commit to set custom URLs. You can modify the commit message with `git commit --amend` and force push to the branch. This also starts the CI pipeline again.
There is a last job, which checks if lines starting with `CI_UNIT_PKG_URL_` exist in the commit message of the latest commit. If so, the unit test will fail. This is required, because otherwise the merged code would depend on non merged changes in sub-packages and would be non-compatible.
!!! note
If you use `CI_UNIT_PKG_URL_`, the CI pipeline will fail which does not mean that the actual tests are failing.
# Integration Tests for CI Users
The integration tests are automatically triggered if you open a pull request that targets the `main` or `dev` branch, and the unit tests have passed. The integration tests itself are in an extra stage of the CI.

If the tests pass successfully, you don't need to do anything. If they fail, i.e. the change breaks the interoperability with another package in the `QuantumElectrodynamics.jl` ecosystem, the pull request will suspend, and one has two options to proceed:
1. One can solve the problem locally, by changing the code of the modified (sub-) package. The workflow is the same as for fixing unit tests.
2. One needs to modify the depending package, which failed in the integration test. In the following, we describe how to provide the necessary changes to the downstream package and make the CI pass the integration tests, which will resume the pull request.
For better understanding, the package currently modified by the pull request is called `orig`, and the package that depends on it is referred to as `dep`. This means in practice, the `Project.toml` of the project `dep` contains the dependency to `orig`. First, one should fork the package `dep` and checkout a new feature branch on this fork. The fix of the integration issue for `dep` is now developed on the feature branch. Once finished, the changes to `dep` are push to GitHub, and a pull request on `dep` is opened to check in the changes. By default, the unit test for `dep` should fail, because the CI in `dep` needs to use the modified version of `orig`. The solution for this problem is explained in the section [Unit Test for CI Users](#Unit-Test-for-CI-Users). Using this, one should develop the fix on the feature branch until the CI of `dep` passes all unit tests. In this case, the original pull request in the upstream package `orig` can be resumed. Therefore, one needs to tell the CI of `orig` that the integration tests should use the fixed version package `dep`, which is still on the feature branch in a pull request on `dep`. In order to proceed, the CI on `orig` needs information on where the fix for `dep` is located. This is given to the CI of `orig` in a commit message on the origin branch of the pull request on `orig`, one just needs to add a new line with the following format to the commit message:
```
CI_INTG_PKG_URL_<dep_name>: https://github.com/<user>/<dep_name>#<commit_hash>
```
You can find the names of the environment variables in the section [Environment Variables](#Environment-Variables). For an example let's assume the name of the `dep` package is `dep1.jl`, `user1` forked the package and the commit hash of the fix for package `dep1.jl` is `45a723b`. Then, an example message could look like this:
```
This commit extends function foo with a new
function argument.
The function argument is required to control
the new functionality.
If you pass a 0, it has a special meaning.
CI_INTG_PKG_URL_DEP1JL: https://github.com/user1/dep1.jl#45a723b
```
It is also possible to set a custom URL for more than one package, which depends on `orig`. Simply add an additional line of the shape `CI_INTG_PKG_URL_<dep_name>: https://github.com/<user>/<dep_name>#<commit_hash>` to the commit message.
!!! note
You don't need to add a new commit to set custom URLs. You can modify the commit message with `git commit --amend` and force push to the branch. This also starts the CI pipeline again.
# Environment Variables
The following table shows the names of the environment variables to use custom URLs for the unit and integration tests.
Package Name | Unit Test | Integration Test
----------------|--------------------------------|-------------------------------
QEDbase.jl | `CI_UNIT_PKG_URL_QEDbase` | `CI_INTG_PKG_URL_QEDbase`
QEDcore.jl | `CI_UNIT_PKG_URL_QEDcore` | `CI_INTG_PKG_URL_QEDcore`
QEDevents.jl | `CI_UNIT_PKG_URL_QEDevents` | `CI_INTG_PKG_URL_QEDevents`
QEDfields.jl | `CI_UNIT_PKG_URL_QEDfields` | `CI_INTG_PKG_URL_QEDfields`
QEDprocesses.jl | `CI_UNIT_PKG_URL_QEDprocesses` | `CI_INTG_PKG_URL_QEDprocesses`
# Unit Tests for CI Develops
In this section, we explain how the unit tests are prepared and executed. It is not mandatory to read the section if you only want to use the CI.
Before the unit tests are executed, the `SetupDevEnv.jl` is executed, which prepares the project environment for the unit test. It reads the `Project.toml` of the current project and adds the version of the `dev` branch of all QED dependency (`Pkg.develop()`) if no line starting with `CI_UNIT_PKG_URL_` was defined in the commit message. If `CI_UNIT_PKG_URL_` was defined, it will use the custom URL.
The commit message is defined in the environment variable `CI_COMMIT_MESSAGE` by GitLab CI. If the variable is not defined, the script ignores the commit message. If you want to disable reading the commit message, you can set the name of the commit message variable to an undefined variable via the first argument of the `integTestGen.jl` script. We use this when executing the CI on the `main` or `dev` branch. On these branches, it should not be possible to use custom URLs for unit or integration tests. Therefore we disable it, which also allows the use of `CI_INTG_PKG_URL_` variables as regular part of the merge commit message.
## Running Locally
If you want to run the script locally, you can set custom URLs via environment variables. For example:
```bash
CI_UNIT_PKG_URL_QEDbase="www.github.com/User/QEDbase#0e1593b" CI_UNIT_PKG_URL_QEDfields="www.github.com/User/QEDfields#60324ad" julia --project=/path/to/QED/repo SetupDevEnv.jl`
```
# Integration Tests for CI Develops
In this section, we explain how the integration tests are created and executed. It is not mandatory to read the section if you only want to use the CI. The following figure shows the stages of the CI pipeline:

All of the following stages are executed in the CI pipeline of the package, where the code is modified. We name the package `orig` for easier understanding of the documentation. A package who uses `orig` is called `user`. In practice, this means the `Project.toml` of the project `user` contains the dependency to `orig`. A list of `user` is called `users`.
## Stage: Unit Tests
This stage executes the unit tests of `orig` via `Pkg.test()`. The integration tests are only executed, when the unit tests are passed. If the unit tests would not pass, it would test other (sub-) packages with the broken package `orig` and therefore we cannot expect, that the integration tests pass.
## Stage: Generate integration Tests
The integration tests checks, if all (sub-) packages which use the package `orig` as dependency still work with the code modification of the current pull request.
Before we talk about the details, here is a small overview on what the `integTestGen.jl` script is doing. First the CI needs to determine, which (sub-) packages has `orig` as dependency. Therefore the CI downloads the `integTestGen.jl` script from the `QuantumElectrodynamics.jl` project via `git clone`. The `integTestGen.jl` script finds out, which (sub-) package use `orig` and generates for each (sub-) package a new CI test job. So the output of the `integTestGen.jl` is a GitLab CI yaml file, which can be executed via [GitLab CI child pipeline](https://about.gitlab.com/blog/2020/04/24/parent-child-pipelines/#dynamically-generating-pipelines).
The `integTestGen.jl` script traverses the dependency tree of `QuantumElectrodynamics.jl` package. Because each QED sub-package is a dependency of the `QuantumElectrodynamics.jl` package, the `QuantumElectrodynamics.jl` dependency tree contains implicitly all dependency trees of the sub-packages. So the script is traversing the tree and creating a list of sub-packages who depends on `orig`. This list is called `users`.
For each `user` from the list of `users` we need to define a separate CI job. First, the job checkouts the `dev` branch of the git repository of `user`. Then it sets the modified version of `orig` as dependency (`Pkg.develop(path="$CI_package_DIR")`). Finally, it executes the unit tests of `user`. The unit tests of `user` are tested with the code changes of the current pull request.
If the `dev` branch of `user` does not work, it is also possible to define a custom git commit to a working commit via the git commit message of the pull request of `orig`. For more details see [Integration Tests for CI Users](#Integration-Tests-for-CI-Users).
!!! note
If a sub-package triggers an integration test, the main package `QuantumElectrodynamics.jl` is passive. It does not get any notification or trigger any script. The repository is simply cloned.
!!! note
The commit message is defined in the environment variable `CI_COMMIT_MESSAGE` by GitLab CI.
If the variable is not defined, the script ignores the commit message. If you want to disable
reading the commit message, you can set the name of the commit message variable to an
undefined variable via the first argument of the `integTestGen.jl` script. We use this when
executing the CI on the `main` or `dev` branch. On these branches, it should not be possible
to use custom URLs for unit or integration tests. Therefore we disable it, which also allows
the use of `CI_INTG_PKG_URL_` variables as regular part of the merge commit message.
## Stage: Run Integration Tests
This stage uses the generated job yaml to create and run new test jobs. It uses the [GitLab CI child pipeline](https://about.gitlab.com/blog/2020/04/24/parent-child-pipelines/#dynamically-generating-pipelines) mechanism.
## Stage: Integration Tests of Sub-Packages N
Each job clones the repository of the sub-package. After the clone, it uses the Julia function `Pkg.develop(path="$CI_package_DIR")` to replace the dependency to the package `orig` with the modified version of the pull request and execute the tests of the sub-package via `Pkg.test()`.
The integration tests of each sub-package are executed in parallel. So, if the integration tests of a package fails, the integration tests of the other packages are still executed and can pass.
## Running Locally
The `integTestGen.jl` script has a special behavior. It creates its own `Project.toml` in a temporary folder and switches its project environment to it. Therefore, you need to start the script with the project path `--project=ci/integTestGen`. You also need to set two environment variables:
- **CI\_DEPENDENCY\_NAME:** Name of the `orig`. For example `QEDbase`.
- **CI\_PROJECT\_DIR:** Path to the project root directory of `orig`. This path is used in the generated integration test, to set the dependency the modified code of `orig`.
The following example assumes that the `QuantumElectrodynamics.jl` project is located at `$HOME/projects/QuantumElectrodynamics.jl` and the project to test is `QEDbase.jl` and is located at `$HOME/projects/QEDbase.jl`.
```bash
CI_DEPENDENCY_NAME=QEDbase CI_PROJECT_DIR="$HOME/projects/QEDbase.jl" julia --project=$HOME/projects/QuantumElectrodynamics.jl/ci/integTestGen $HOME/projects/QuantumElectrodynamics.jl/ci/integTestGen/src/integTestGen.jl
```
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 5211 | # Development Guide
In this file we explain the release and developing processes we follow in all of the QED-project Julia packages.
## General
We use the [GitFlow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) workflow. In short, this means we use a `dev` branch to continuously develop on, and a `main` branch that has the latest released version. Once enough changes have been merged into dev to warrant a new release, a release branch is created from `dev`, adding the latest changelog and increasing the version number. It is then merged into `main` and also back into `dev` to create the new common root of the two branches.
In the following, the different possible situations are explained in more detail.
## Merging a Feature Branch
To create a new feature, create a new branch from the current `dev` and push it onto a fork. Once you have developed, committed, and pushed the changes to the repository, open a pull request to `dev` of the official repository. Automatic tests will then check that the code is properly formatted, that the documentation builds, and that tests pass. If all of these succeed, the feature branch can be merged after approval of one of the maintainers of the repository.
### CI Testing
There are two types of tests that run automatically when a pull request is opened: Unit tests, which only test the functionality in the current repository, and integration tests, which check whether other downstream packages (i.e. packages that depend on the current repository) still work with the code updates.
In case breaking changes are introduced by the pull request the integration tests will fail and an additional pull request has to be opened in each breaking package, fixing the incompatibility. For details on how this works, refer to the [CI documentation](ci.md#Integration-Tests-for-CI-Users).
## Releasing a New Version
Several steps are involved in releasing a new version of a package. For versioning, we follow [Julia's versioning guidelines](https://julialang.org/blog/2019/08/release-process/). However, we do not provide patches for previous minor or major versions.
### Release Issue Template
The following is a template that can be used to open issues for a specific release of one of the QED-project packages. Customize it by simply replacing `<version>` with the version to-be-released.
```md
With this issue, we keep track of the workflow for version `<version>` release.
## Preparation for the release
- [ ] Tag all PRs that are part of this release by adding them to a milestone named `Release-<version>`.
- [ ] Create a release branch `release-<version>` on your fork.
- [ ] Adjust `./Project.toml` on the new `release-<version>` branch by ticking up the version.
- [ ] Check if it is necessary to adjust the `compat` entry of upstream QED-project packages.
- [ ] Add/Update the file `./CHANGELOG.md` on the `release-<version>` branch by appending a summary section. This can be done by using the tagged PRs associated with this release.
## Release procedure
- [ ] Open a PR for merging `release-<version>` into the `main`-branch of the QEDjl-project repository with at least one reviewer who only needs to check the points above, the code additions were reviewed in the respective PRs. Do not delete the `release-<version>` branch yet. :warning: **Do not squash this PR, use a simple merge commit** :warning:
- [ ] *After* the release branch is merged into `main`, open another PR for merging `release-<version>` into the `dev`-branch of the QEDjl-project repository. This can be merged without much review because the relevant changes were already reviewed in the PR `release-<version> -> main`. After this merge, you are free to delete the `release-<version>`-branch on your fork. :warning: **Do not squash this PR, use a simple merge commit** :warning:
- [ ] Registration: Go to the issues and search for `Release`. There, write a comment with `<at>JuliaRegistrator register(branch="main")` with a real `@` to trigger the registration bot opening a PR on Julia's general registry.
- [ ] *After* the registration bot reports back the correct registration, tag the HEAD of `main` (which should still be the merge commit from the release branch merge) with `v<version>`. This will trigger a new deployment of the stable docs for the new version.
- [ ] Build a GitHub release from the latest tagged commit on `main` and add the respective section from `CHANGELOG.md` to the release notes.
```
### Releasing Breaking Changes
Just as with merging breaking changes into `dev`, when releasing breaking changes, extra care has to be taken. When a release contains breaking changes, some of the release-version integration tests will fail. In this case, the major version should be increased (or the minor version for versions `0.x.y`). This prevents the released downstream packages from failing since they have a `compat` entry, choosing the latest working version.
The dev-integration tests assure that the latest `dev`s of all packages still work together. This means that the depending package can now be released, after changing the `compat` entry of the base package in the release branch accordingly.
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.0 | 6370375cb3fce27de9cf69b381d84d31011dc123 | docs | 1505 | ```@meta
CurrentModule = QuantumElectrodynamics
```
# QuantumElectrodynamics.jl
This is the documentation for [`QuantumElectrodynamics.jl`](https://github.com/QEDjl-project/QuantumElectrodynamics.jl). It represents the combination of the following subpackages:
**The two fundamental packages**:
- [`QEDbase.jl`](https://github.com/QEDjl-project/QEDbase.jl): Interfaces and some functionality on abstract types. [Docs](https://qedjl-project.github.io/QEDbase.jl/stable/)
- [`QEDcore.jl`](https://github.com/QEDjl-project/QEDcore.jl): Implementation of core functionality that is needed across all or most content packages. [Docs](https://qedjl-project.github.io/QEDcore.jl/stable/)
**The content packages**:
- [`QEDprocesses.jl`](https://github.com/QEDjl-project/QEDprocesses.jl): Scattering process definitions, models, and calculation of cross-sections and probabilities. [Docs](https://qedjl-project.github.io/QEDprocesses.jl/stable/)
- [`QEDevents.jl`](https://github.com/QEDjl-project/QEDevents.jl): Monte-Carlo event generation for scattering processes. [Docs](https://qedjl-project.github.io/QEDevents.jl/stable/)
- [`QEDfields.jl`](https://github.com/QEDjl-project/QEDfields.jl): Description of classical electromagnetic fields used in background-field approximations. [Docs](https://qedjl-project.github.io/QEDfields.jl/stable/)
For detailed information on the packages, please refer to their respective docs, linked above.
```@index
```
```@autodocs
Modules = [QuantumElectrodynamics]
```
| QuantumElectrodynamics | https://github.com/QEDjl-project/QuantumElectrodynamics.jl.git |
|
[
"MIT"
] | 0.1.1 | 1b2773b6e69f82af0405ab23f41be77c1b88936d | code | 1179 | module NotMacro
export @not
"""
@not someboolean
a human readable alternative to `!`
Example
-------
```jldoctest
julia> using NotMacro
julia> if @not isodd(2) && @not iseven(3) && true
println("works")
end
works
julia> @macroexpand if @not isodd(2) & @not iseven(3) & true
println("works")
end
:(if !(isodd(2)) & (!(iseven(3)) & true)
#= none:2 =#
println("works")
end)
```
"""
macro not(expr)
# macroexpand solves `@not @not true && false` case
esc(_not_impl(Base.macroexpand(__module__, expr)))
end
function _not_impl(expr)
isbinaryoperator = Meta.isexpr(expr, :call) && Meta.isbinaryoperator(expr.args[1])
isbinaryboolsyntax = isa(expr, Expr) && expr.head ∈ (:&&, :||)
if isbinaryoperator
# go into any binary+ operator
not2 = _not_impl(expr.args[2])
Expr(:call, expr.args[1], not2, expr.args[3:end]...)
elseif isbinaryboolsyntax
# go into any binary bool syntax
not1 = _not_impl(expr.args[1])
Expr(expr.head, not1, expr.args[2:end]...)
else # we are at the farest left of all binary operators
Expr(:call, :!, expr)
end
end
end
| NotMacro | https://github.com/jolin-io/NotMacro.jl.git |
|
[
"MIT"
] | 0.1.1 | 1b2773b6e69f82af0405ab23f41be77c1b88936d | code | 1840 | using NotMacro
using Test
using Documenter
doctest(NotMacro, manual=false)
@testset "NotMacro.jl" begin
@test (@not true || false) == false
@test (@not false && true) == true
@test (@not true | false) == false
@test (@not false & true) == true
@test (@not false ⊻ false) == true
if isdefined(Base, :⊼)
@test (@not false ⊼ true) == false
end
if isdefined(Base, :⊽)
@test (@not true ⊽ false) == true
end
# double negation
@test (@not @not true && false) == false
# test three operators
@test (@not true && false || false) == false
for a in [true, false],
b in [true, false],
c in [true, false],
expr in [
:((a && b) && c),
:((a && b) || c),
:((a || b) && c),
:((a || b) || c),
:(a && (b && c)),
:(a && (b || c)),
:(a || (b && c)),
:(a || (b || c)),
:((a & b) & c),
:((a & b) | c),
:((a | b) & c),
:((a | b) | c),
:(a & (b & c)),
:(a & (b | c)),
:(a | (b & c)),
:(a | (b | c)),
:((a && b) & c),
:((a & b) && c),
:((a && b) | c),
:((a & b) || c),
:((a || b) & c),
:((a | b) && c),
:((a || b) | c),
:((a | b) || c),
:(a && (b & c)),
:(a & (b && c)),
:(a && (b | c)),
:(a & (b || c)),
:(a || (b & c)),
:(a | (b && c)),
:(a || (b | c)),
:(a | (b || c)),
]
exclamation = :( ((a, b, c) -> $expr)(!$a, $b, $c) )
notmacro = :( ((a, b, c) -> $NotMacro.@not $expr)($a, $b, $c) )
@test @eval $exclamation == $notmacro
end
end
| NotMacro | https://github.com/jolin-io/NotMacro.jl.git |
|
[
"MIT"
] | 0.1.1 | 1b2773b6e69f82af0405ab23f41be77c1b88936d | docs | 473 | # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
## Released [0.1.1] - 2023-01-16
### Fixed
- recursive case got fixed, including large testset for nesting 3 operators.
- double negation `@not @not ...`
## Released [0.1.0] - 2023-01-16
initial release
| NotMacro | https://github.com/jolin-io/NotMacro.jl.git |
|
[
"MIT"
] | 0.1.1 | 1b2773b6e69f82af0405ab23f41be77c1b88936d | docs | 939 | # NotMacro
[](https://github.com/jolin-io/NotMacro.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/jolin-io/NotMacro.jl)
NotMacro exports `@not` which can be used instead of the negation operator `!` to make
code easier to read. The syntax is borrowed from Python and will feel much more intuitive
for Python users.
There is no performance penalty when using `@not`, it just compiles to plain `!`.
```julia
julia> using NotMacro
julia> if @not isodd(2) && @not iseven(3) && true
println("works")
end
works
julia> @macroexpand if @not isodd(2) & @not iseven(3) & true
println("works")
end
:(if (!)(isodd(2)) & ((!)(iseven(3)) & true)
#= none:2 =#
println("works")
end)
``` | NotMacro | https://github.com/jolin-io/NotMacro.jl.git |
|
[
"MIT"
] | 0.1.4 | ad9e966e1b072d0ae3e74c8a6137912c092fb9d0 | code | 3874 | module FunctionBarrier
using Base.Meta
export @barrier
struct Var
name::Symbol
num_esc::Int
end
function makelet(v::Var)
ex = v.name
for i=1:v.num_esc
ex = esc(ex)
end
return ex
end
# Wrap `barrier_expression` in a `function` block to improve efficiency.
function wrap_barrier(module_, barrier_expression)
ex = macroexpand(module_, barrier_expression)
bound_vars, captured_vars = [Var(:end, 0), Var(:begin, 0)], Var[]
find_var_uses!(captured_vars, bound_vars, ex, 0)
fname = gensym()
lastex = ex.args[end]
args = map(makelet, captured_vars)
if lastex isa Symbol || last isa Expr &&
lastex.head == :tuple &&
all(a -> a isa Symbol, lastex.args)
retvar = lastex
else
retvar = gensym()
end
quote
function $fname($(args...))
$barrier_expression
end
$retvar = $fname($(args...))
end
end
macro barrier(ex)
esc(wrap_barrier(__module__, ex))
end
function find_var_uses!(varlist, bound_vars, ex, num_esc)
if isa(ex, Symbol)
var = Var(ex,num_esc)
if !(var in bound_vars)
var ∈ varlist || push!(varlist, var)
end
return varlist
elseif isa(ex, Expr)
if ex.head == :quote || ex.head == :line || ex.head == :inbounds
return varlist
end
if ex.head == :(=)
find_var_uses_lhs!(varlist, bound_vars, ex.args[1], num_esc)
find_var_uses!(varlist, bound_vars, ex.args[2], num_esc)
elseif ex.head == :kw
find_var_uses!(varlist, bound_vars, ex.args[2], num_esc)
elseif ex.head == :for || ex.head == :while || ex.head == :comprehension || ex.head == :let
# New scopes
inner_bindings = copy(bound_vars)
find_var_uses!(varlist, inner_bindings, ex.args, num_esc)
elseif ex.head == :try
# New scope + ex.args[2] is a new binding
find_var_uses!(varlist, copy(bound_vars), ex.args[1], num_esc)
catch_bindings = copy(bound_vars)
!isa(ex.args[2], Symbol) || push!(catch_bindings, Var(ex.args[2],num_esc))
find_var_uses!(varlist,catch_bindings,ex.args[3], num_esc)
if length(ex.args) > 3
finally_bindings = copy(bound_vars)
find_var_uses!(varlist,finally_bindings,ex.args[4], num_esc)
end
elseif ex.head == :call
find_var_uses!(varlist, bound_vars, ex.args[2:end], num_esc)
elseif ex.head == :local
foreach(ex.args) do e
if !isa(e, Symbol)
find_var_uses!(varlist, bound_vars, e, num_esc)
end
end
elseif ex.head == :(::)
find_var_uses_lhs!(varlist, bound_vars, ex, num_esc)
elseif ex.head == :escape
find_var_uses!(varlist, bound_vars, ex.args[1], num_esc+1)
else
find_var_uses!(varlist, bound_vars, ex.args, num_esc)
end
end
varlist
end
find_var_uses!(varlist, bound_vars, exs::Vector, num_esc) =
foreach(e->find_var_uses!(varlist, bound_vars, e, num_esc), exs)
function find_var_uses_lhs!(varlist, bound_vars, ex, num_esc)
if isa(ex, Symbol)
var = Var(ex,num_esc)
var ∈ bound_vars || push!(bound_vars, var)
elseif isa(ex, Expr)
if ex.head == :tuple
find_var_uses_lhs!(varlist, bound_vars, ex.args, num_esc)
elseif ex.head == :(::)
find_var_uses!(varlist, bound_vars, ex.args[2], num_esc)
find_var_uses_lhs!(varlist, bound_vars, ex.args[1], num_esc)
else
find_var_uses!(varlist, bound_vars, ex.args, num_esc)
end
end
end
find_var_uses_lhs!(varlist, bound_vars, exs::Vector, num_esc) = foreach(e->find_var_uses_lhs!(varlist, bound_vars, e, num_esc), exs)
end
| FunctionBarrier | https://github.com/AStupidBear/FunctionBarrier.jl.git |
|
[
"MIT"
] | 0.1.4 | ad9e966e1b072d0ae3e74c8a6137912c092fb9d0 | code | 349 | using FunctionBarrier
using Test
@testset "FunctionBarrier.jl" begin
a, b = 1, 2
local c, d
@barrier begin
c = a + b
d = c + 1
c, d
end
@test c == a + b
@test d == c + 1
@test (@barrier a * b) == a * b
x = [1, 2, 4]
@test (@barrier x[end]) == x[end]
@test (@barrier x[1]) == x[1]
end
| FunctionBarrier | https://github.com/AStupidBear/FunctionBarrier.jl.git |
|
[
"MIT"
] | 0.1.4 | ad9e966e1b072d0ae3e74c8a6137912c092fb9d0 | docs | 649 | # FunctionBarrier
[](https://github.com/AStupidBear/FunctionBarrier.jl/actions)
[](https://codecov.io/gh/AStupidBear/FunctionBarrier.jl)
Most of the code in this package is borrowed from [FastClosures.jl](https://github.com/c42f/FastClosures.jl).
## Usage
```julia
a, b = 1, 2
@barrier begin
c = a + b
d = c + 1
c, d
end
```
is equivalent to
```julia
a, b = 1, 2
function foo(a, b)
c = a + b
d = c + 1
(c, d)
end
(c, d) = foo(a, b)
``` | FunctionBarrier | https://github.com/AStupidBear/FunctionBarrier.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | code | 569 | using Documenter, KnetNLPModels
makedocs(
modules = [KnetNLPModels],
doctest = true,
# linkcheck = true,
strict = true,
format = Documenter.HTML(
assets = ["assets/style.css"],
prettyurls = get(ENV, "CI", nothing) == "true",
),
sitename = "KnetNLPModels.jl",
pages = Any[
"Home" => "index.md",
"Tutorial" => "tutorial.md",
"Reference" => "reference.md",
"LeNet training" => "LeNet_Training.md",
],
)
deploydocs(
repo = "github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git",
push_preview = true,
devbranch = "main",
)
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | code | 5090 | module KnetNLPModels
using Knet, NLPModels
export Chain
export AbstractKnetNLPModel, KnetNLPModel
export vector_params, accuracy
export reset_minibatch_train!, rand_minibatch_train!, minibatch_next_train!, set_size_minibatch!
export reset_minibatch_test!, rand_minibatch_test!, minibatch_next_test!
export build_nested_array_from_vec, build_nested_array_from_vec!
export create_minibatch, set_vars!, vcat_arrays_vector
# abstract type Chain end
abstract type AbstractKnetNLPModel{T, S} <: AbstractNLPModel{T, S} end
"""
KnetNLPModel{T, S, C} <: AbstractNLPModel{T, S}
Data structure that makes the interfaces between neural networks defined with [Knet.jl](https://github.com/denizyuret/Knet.jl) and [NLPModels](https://github.com/JuliaSmoothOptimizers/NLPModels.jl).
A KnetNLPModel has fields
* `meta` and `counters` retain informations about the `KnetNLPModel`;
* `chain` is the chained structure representing the neural network;
* `data_train` is the complete data training set;
* `data_test` is the complete data test;
* `size_minibatch` parametrizes the size of an training and test minibatches, which are of size `1/size_minibatch * length(ytrn)` and `1/size_minibatch * length(ytst)`;
* `training_minibatch_iterator` is an iterator over an training minibatches;
* `test_minibatch_iterator` is an iterator over the test minibatches;
* `current_training_minibatch` is the training minibatch used to evaluate the neural network;
* `current_minibatch_test` is the current test minibatch, it is not used in practice;
* `w` is the vector of weights/variables;
* `layers_g` is a nested array used for internal purposes;
* `nested_array` is a vector of `Array{T,N}`; its shape matches that of `chain`.
"""
mutable struct KnetNLPModel{T, S, C, V, Z} <: AbstractKnetNLPModel{T, S}
meta::NLPModelMeta{T, S}
chain::C
counters::Counters
data_train
data_test
size_minibatch::Int
training_minibatch_iterator
test_minibatch_iterator
current_training_minibatch
current_test_minibatch
w::S
layers_g::Z
nested_array::V
i_train::Int
i_test::Int
end
"""
KnetNLPModel(chain_ANN; size_minibatch=100, data_train=MLDatasets.MNIST.traindata(Float32), data_test=MLDatasets.MNIST.testdata(Float32))
Build a `KnetNLPModel` from the neural network represented by `chain_ANN`.
`chain_ANN` is built using [Knet.jl](https://github.com/denizyuret/Knet.jl), see the [tutorial](https://JuliaSmoothOptimizers.github.io/KnetNLPModels.jl/dev/tutorial/) for more details.
The other data required are: an iterator over the training dataset `data_train`, an iterator over the test dataset `data_test` and the size of the minibatch `size_minibatch`.
Suppose `(xtrn,ytrn) = knetnlp.data_train`, then the size of each training minibatch will be `1/size_minibatch * length(ytrn)`.
By default, the other data are respectively set to the training dataset and test dataset of `MLDatasets.MNIST`, with each minibatch a hundredth of the dataset.
"""
function KnetNLPModel(
chain_ANN::T;
size_minibatch::Int = 100,
data_train = begin
(xtrn, ytrn) = MLDatasets.MNIST(split = :train)[:]
ytrn[ytrn .== 0] .= 10
(xtrn, ytrn)
end,
data_test = begin
(xtst, ytst) = MLDatasets.MNIST(split = :test)[:]
ytst[ytst .== 0] .= 10
(xtst, ytst)
end,
) where {T}
x0 = vector_params(chain_ANN)
n = length(x0)
meta = NLPModelMeta(n, x0 = x0)
(xtrn, ytrn) = data_train
(xtst, ytst) = data_test
training_minibatch_iterator = create_minibatch(xtrn, ytrn, size_minibatch)
test_minibatch_iterator = create_minibatch(xtst, ytst, size_minibatch)
current_training_minibatch = rand(training_minibatch_iterator)
current_test_minibatch = rand(test_minibatch_iterator)
nested_array = build_nested_array_from_vec(chain_ANN, x0)
layers_g = similar.(params(chain_ANN)) # create a Vector of layer variables
return KnetNLPModel(
meta,
chain_ANN,
Counters(),
data_train,
data_test,
size_minibatch,
training_minibatch_iterator,
test_minibatch_iterator,
current_training_minibatch,
current_test_minibatch,
x0,
layers_g,
nested_array,
1, #initialize the batch current i to 1
1,
)
end
"""
set_size_minibatch!(knetnlp::AbstractKnetNLPModel, size_minibatch::Int)
Change the size of both training and test minibatches of the `knetnlp`.
Suppose `(xtrn,ytrn) = knetnlp.data_train`, then the size of each training minibatch will be `1/size_minibatch * length(ytrn)`; the test minibatch follows the same logic.
After a call of `set_size_minibatch!`, you must call `reset_minibatch_train!(knetnlp)` to use a minibatch of the expected size.
"""
function set_size_minibatch!(knetnlp::AbstractKnetNLPModel, size_minibatch::Int)
knetnlp.size_minibatch = size_minibatch
knetnlp.training_minibatch_iterator =
create_minibatch(knetnlp.data_train[1], knetnlp.data_train[2], knetnlp.size_minibatch)
knetnlp.test_minibatch_iterator =
create_minibatch(knetnlp.data_test[1], knetnlp.data_test[2], knetnlp.size_minibatch)
return knetnlp
end
include("utils.jl")
include("KnetNLPModels_methods.jl")
end
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | code | 856 | """
f = obj(nlp, x)
Evaluate `f(x)`, the objective function of `nlp` at `x`.
"""
function NLPModels.obj(nlp::AbstractKnetNLPModel{T, S}, w::AbstractVector{T}) where {T, S}
increment!(nlp, :neval_obj)
set_vars!(nlp, w)
f_w = nlp.chain(nlp.current_training_minibatch)
return f_w
end
"""
g = grad!(nlp, x, g)
Evaluate `∇f(x)`, the gradient of the objective function at `x` in place.
"""
function NLPModels.grad!(
nlp::AbstractKnetNLPModel{T, S},
w::AbstractVector{T},
g::AbstractVector{T},
) where {T, S}
@lencheck nlp.meta.nvar w g
increment!(nlp, :neval_grad)
set_vars!(nlp, w)
L = Knet.@diff nlp.chain(nlp.current_training_minibatch)
vars = Knet.params(nlp.chain)
for (index, wᵢ) in enumerate(vars)
nlp.layers_g[index] .= Param(Knet.grad(L, wᵢ))
end
g .= Vector(vcat_arrays_vector(nlp.layers_g))
return g
end
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | code | 8956 | """
flag_dim(x)
Returns true if x has 3 dimensions.
This function is used to reshape X in `create_minibatch(X, Y, minibatch_size)` in case x has only 3 dimensions.
"""
flag_dim(x) = length(size(x)) == 3
"""
create_minibatch(X, Y, minibatch_size)
Create a minibatch's iterator of the data `X`, `Y` of size `1/minibatch_size * length(Y)`.
"""
function create_minibatch(x_data, y_data, minibatch_size; _reshape::Bool = flag_dim(x_data))
mb = minibatch(
x_data,
y_data,
minibatch_size;
xsize = (size(x_data, 1), size(x_data, 2), size(x_data, 3), :),
)
if _reshape
mb.xsize = (size(x_data, 1), size(x_data, 2), 1, :) # To force x_data to take 1 as third dimension
end
return mb
end
"""
vector_params(chain :: Chain) where Chain
vector_params(nlp :: AbstractKnetNLPModel)
Retrieve the variables within `chain` or `nlp.chain` as a vector.
"""
vector_params(chain::Chain) where {Chain} = Array(vcat_arrays_vector(params(chain)))
vector_params(nlp::AbstractKnetNLPModel) = nlp.w
"""
vcat_arrays_vector(nested_vectors::AbstractVector{Param})
Flatten a vector of arrays `nested_vectors` to a vector.
It concatenates the vectors produced by the application of `Knet.cat1d` to each array.
"""
vcat_arrays_vector(nested_vectors::AbstractVector{P}) where {P} =
vcat(Knet.cat1d.(nested_vectors)...)
"""
reset_minibatch_train!(nlp::AbstractKnetNLPModel)
Select the first training minibatch for `nlp`.
"""
function reset_minibatch_train!(nlp::AbstractKnetNLPModel)
nlp.current_training_minibatch = first(nlp.training_minibatch_iterator)
nlp.i_train = 1
end
"""
rand_minibatch_train!(nlp::AbstractKnetNLPModel)
Select a training minibatch for `nlp` randomly.
"""
function rand_minibatch_train!(nlp::AbstractKnetNLPModel)
nlp.i_train = rand(1:(nlp.training_minibatch_iterator.imax))
nlp.current_training_minibatch = iterate(nlp.training_minibatch_iterator, nlp.i_train)
end
"""
minibatch_next_train!(nlp::AbstractKnetNLPModel)
Selects the next minibatch from `nlp.training_minibatch_iterator`.
Returns the new current location of the iterator `nlp.i_train`.
If it returns 1, the current training minibatch is the first of `nlp.training_minibatch_iterator` and the previous minibatch was the last of `nlp.training_minibatch_iterator`.
`minibatch_next_train!` aims to be used in a loop or method call.
Refer to KnetNLPModelProblems.jl for more use cases.
"""
function minibatch_next_train!(nlp::AbstractKnetNLPModel)
nlp.i_train += nlp.size_minibatch # update the i by mini_batch size
result = iterate(nlp.training_minibatch_iterator, nlp.i_train)
if result === nothing
# reset to the begining
reset_minibatch_train!(nlp)
else
(next, indice) = result
nlp.current_training_minibatch = next
end
return nlp.i_train
end
"""
reset_minibatch_test!(nlp::AbstractKnetNLPModel)
Select a new test minibatch for `nlp` at random.
"""
function rand_minibatch_test!(nlp::AbstractKnetNLPModel)
nlp.i_test = rand(1:(nlp.test_minibatch_iterator.imax))
nlp.current_test_minibatch = iterate(nlp.test_minibatch_iterator, nlp.i_test)
end
"""
reset_minibatch_test!(nlp::AbstractKnetNLPModel)
Select the first test minibatch for `nlp`.
"""
function reset_minibatch_test!(nlp::AbstractKnetNLPModel)
nlp.current_test_minibatch = first(nlp.test_minibatch_iterator)
nlp.i_test = 1
end
"""
minibatch_next_test!(nlp::AbstractKnetNLPModel)
Selects the next minibatch from `test_minibatch_iterator`.
Returns the new current location of the iterator `nlp.i_test`.
If it returns 1, the current training minibatch is the first of `nlp.test_minibatch_iterator` and the previous minibatch was the last of `nlp.test_minibatch_iterator`.
`minibatch_next_test!` aims to be used in a loop or method call - refere to KnetNLPModelProblems.jl for more use cases
"""
function minibatch_next_test!(nlp::AbstractKnetNLPModel)
nlp.i_test += nlp.size_minibatch #TODO in the futue we might want to have different size for minbatch test vs train
result = iterate(nlp.test_minibatch_iterator, nlp.i_test)
if result === nothing
# reset to the begining
reset_minibatch_test!(nlp)
else
(next, indice) = result
nlp.current_test_minibatch = next
end
return nlp.i_test
end
"""
accuracy(nlp::AbstractKnetNLPModel)
Compute the accuracy of the network `nlp.chain` on the entire test dataset.
"""
accuracy(nlp::AbstractKnetNLPModel) = Knet.accuracy(nlp.chain; data = nlp.test_minibatch_iterator)
"""
build_layer_from_vec!(array :: AbstractArray{T, N}, v :: AbstractVector{T}, index :: Int) where {T <: Number, N}
Inverse of the function `Knet.cat1d`; set `array` to the values of `v` in the range `index+1:index+consumed_index`.
"""
function build_layer_from_vec!(
array::AbstractArray{T, N},
v::AbstractVector{T},
index::Int,
) where {T <: Number, N}
sizearray = reduce(*, size(array))
copyto!(array, v[(index + 1):(index + sizearray)])
return sizearray
# size_array is consume_index in the method
# build_nested_array_from_vec!(nested_array,new_w)
end
"""
nested_array = build_nested_array_from_vec(model::AbstractKnetNLPModel{T, S}, v::AbstractVector{T}) where {T <: Number, S}
nested_array = build_nested_array_from_vec(chain_ANN::C, v::AbstractVector{T}) where {C, T <: Number}
nested_array = build_nested_array_from_vec(nested_array::AbstractVector{<:AbstractArray{T,N} where {N}}, v::AbstractVector{T}) where {T <: Number}
Build a vector of `AbstractArray` from `v` similar to `Knet.params(model.chain)`, `Knet.params(chain_ANN)` or `nested_array`.
Call iteratively `build_layer_from_vec` to build each intermediate `AbstractArray`.
This method is not optimized; it allocates memory.
"""
build_nested_array_from_vec(
model::AbstractKnetNLPModel{T, S},
v::AbstractVector{T},
) where {T <: Number, S} = build_nested_array_from_vec(model.chain, v)
function build_nested_array_from_vec(
chain_ANN::Chain,
v::AbstractVector{T},
) where {Chain, T <: Number}
param_chain = params(chain_ANN) # :: Param
size_param = mapreduce((var_layer -> reduce(*, size(var_layer))), +, param_chain)
size_param == length(v) || error(
"Dimension of Vector v mismatch, function build_nested_array $(size_param) != $(length(v))",
)
nested_w_value = (w -> w.value).(param_chain)
nested_array = build_nested_array_from_vec(nested_w_value, v)
return nested_array
end
function build_nested_array_from_vec(
nested_array::AbstractVector{<:AbstractArray{T, N} where {N}},
v::AbstractVector{T},
) where {T <: Number}
similar_nested_array = map(array -> similar(array), nested_array)
build_nested_array_from_vec!(similar_nested_array, v)
return similar_nested_array
end
"""
build_nested_array_from_vec!(model::AbstractKnetNLPModel{T,S}, new_w::AbstractVector{T}) where {T, S}
build_nested_array_from_vec!(nested_array :: AbstractVector{<:AbstractArray{T,N} where {N}}, new_w :: AbstractVector{T}) where {T <: Number}
Build a vector of `AbstractArray` from `new_w` similar to `Knet.params(model.chain)` or `nested_array`.
Call iteratively `build_layer_from_vec!` to build each intermediate `AbstractArray`.
This method is not optimized; it allocates memory.
"""
build_nested_array_from_vec!(
model::AbstractKnetNLPModel{T, S},
new_w::AbstractVector{T},
) where {T, S} = build_nested_array_from_vec!(model.nested_array, new_w)
function build_nested_array_from_vec!(
nested_array::AbstractVector{<:AbstractArray{T, N} where {N}},
new_w::AbstractVector{T},
) where {T <: Number}
index = 0
for variable_layer in nested_array
consumed_indices = build_layer_from_vec!(variable_layer, new_w, index)
index += consumed_indices
end
nested_array
end
"""
set_vars!(model::AbstractKnetNLPModel{T,S}, new_w::AbstractVector{T}) where {T<:Number, S}
set_vars!(chain_ANN :: Chain, nested_w :: AbstractVector{<:AbstractArray{T,N} where {N}}) where {Chain, T <: Number}
set_vars!(vars :: Vector{Param}, nested_w :: AbstractVector{<:AbstractArray{T,N} where {N}})
)
Set the variables of `model` (resp. `chain_ANN` and `vars`) to `new_w` (resp. `nested_w`).
Build `nested_w`: a vector of `AbstractArray` from `new_v` similar to `Knet.params(model.chain)`.
Then, set the variables `vars` of the neural netword `model` (resp. `chain_ANN`) to `new_w` (resp. `nested_w`).
`set_vars!(model, new_w)` allocates memory.
"""
set_vars!(
vars::AbstractVector{Param},
nested_w::AbstractVector{<:AbstractArray{T, N} where {N}},
) where {T <: Number} = map(i -> vars[i].value .= nested_w[i], 1:length(vars))
set_vars!(
chain_ANN::Chain,
nested_w::AbstractVector{<:AbstractArray{T, N} where {N}},
) where {Chain, T <: Number} = set_vars!(params(chain_ANN), nested_w)
function set_vars!(
model::AbstractKnetNLPModel{T, S},
new_w::AbstractVector{T},
) where {T <: Number, S}
build_nested_array_from_vec!(model, new_w)
set_vars!(model.chain, model.nested_array)
model.w .= new_w
end
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | code | 2945 | using Test
using CUDA, Knet, MLDatasets, NLPModels
using KnetNLPModels
@testset "KnetNLPModels tests" begin
struct Conv
w
b
f
end
(c::Conv)(x) = c.f.(pool(conv4(c.w, x) .+ c.b))
Conv(w1, w2, cx, cy, f = relu) = Conv(param(w1, w2, cx, cy), param0(1, 1, cy, 1), f)
struct Dense
w
b
f
p
end
(d::Dense)(x) = d.f.(d.w * mat(dropout(x, d.p)) .+ d.b)
Dense(i::Int, o::Int, f = sigm; pdrop = 0.0) = Dense(param(o, i), param0(o), f, pdrop)
struct Chainnll
layers
Chainnll(layers...) = new(layers)
end
(c::Chainnll)(x) = (for l in c.layers
x = l(x)
end;
x)
(c::Chainnll)(x, y) = Knet.nll(c(x), y) # nécessaire
(c::Chainnll)(data::Tuple{T1, T2}) where {T1, T2} = c(first(data, 2)...)
(c::Chainnll)(d::Knet.Data) = Knet.nll(c; data = d, average = true)
ENV["DATADEPS_ALWAYS_ACCEPT"] = true # download datasets without having to manually confirm the download
CUDA.allowscalar() do
xtrn, ytrn = MNIST(split = :train)[:]
ytrn[ytrn .== 0] .= 10
xtst, ytst = MNIST(split = :test)[:]
ytst[ytst .== 0] .= 10
dtrn = minibatch(xtrn, ytrn, 100; xsize = (size(xtrn, 1), size(xtrn, 2), 1, :))
dtst = minibatch(xtst, ytst, 100; xsize = (size(xtst, 1), size(xtst, 2), 1, :))
LeNet =
Chainnll(Conv(5, 5, 1, 20), Conv(5, 5, 20, 50), Dense(800, 500), Dense(500, 10, identity))
LeNetNLPModel = KnetNLPModel(LeNet; data_train = (xtrn, ytrn), data_test = (xtst, ytst))
x1 = copy(LeNetNLPModel.w)
x2 = (x -> x + 50).(Array(LeNetNLPModel.w))
obj_x1 = obj(LeNetNLPModel, x1)
grad_x1 = NLPModels.grad(LeNetNLPModel, x1)
@test x1 == LeNetNLPModel.w
@test params(LeNetNLPModel.chain)[1].value[1] == x1[1]
@test params(LeNetNLPModel.chain)[1].value[2] == x1[2]
obj_x2 = obj(LeNetNLPModel, x2)
grad_x2 = NLPModels.grad(LeNetNLPModel, x2)
@test x2 == LeNetNLPModel.w
@test params(LeNetNLPModel.chain)[1].value[1] == x2[1]
@test params(LeNetNLPModel.chain)[1].value[2] == x2[2]
@test obj_x1 != obj_x2
@test grad_x1 != grad_x2
minibatch_size = rand(200:300)
set_size_minibatch!(LeNetNLPModel, minibatch_size)
@test LeNetNLPModel.size_minibatch == minibatch_size
@test length(LeNetNLPModel.training_minibatch_iterator) == floor(length(ytrn) / minibatch_size)
@test length(LeNetNLPModel.test_minibatch_iterator) == floor(length(ytst) / minibatch_size)
rand_minibatch_train!(LeNetNLPModel)
@test LeNetNLPModel.i_train >= 1
@test LeNetNLPModel.i_train <= LeNetNLPModel.training_minibatch_iterator.length - minibatch_size
reset_minibatch_train!(LeNetNLPModel)
@test LeNetNLPModel.i_train == 1
minibatch_next_train!(LeNetNLPModel)
i = 1
i += LeNetNLPModel.size_minibatch
(next, indice) = iterate(LeNetNLPModel.training_minibatch_iterator, i)
@test LeNetNLPModel.i_train == i
@test isequal(LeNetNLPModel.current_training_minibatch, next)
end
end
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | docs | 3140 | # KnetNLPModels : An NLPModels Interface to Knet
| **Documentation** | **Linux/macOS/Windows** | **Coverage** | **DOI** |
|:-----------------:|:-------------------------------:|:------------:|:-------:|
| [![docs-stable][docs-stable-img]][docs-stable-url] [![docs-dev][docs-dev-img]][docs-dev-url] | [![build-gh][build-gh-img]][build-gh-url] | [![codecov][codecov-img]][codecov-url] | [![doi][doi-img]][doi-url] |
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://JuliaSmoothOptimizers.github.io/KnetNLPModels.jl/stable
[docs-dev-img]: https://img.shields.io/badge/docs-dev-purple.svg
[docs-dev-url]: https://JuliaSmoothOptimizers.github.io/KnetNLPModels.jl/dev
[build-gh-img]: https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl/workflows/CI/badge.svg?branch=main
[build-gh-url]: https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl/actions
[codecov-img]: https://codecov.io/gh/JuliaSmoothOptimizers/KnetNLPModels.jl/branch/main/graph/badge.svg
[codecov-url]: https://app.codecov.io/gh/JuliaSmoothOptimizers/KnetNLPModels.jl
[doi-img]: https://zenodo.org/badge/447176402.svg
[doi-url]: https://zenodo.org/badge/latestdoi/447176402
## How to Cite
If you use KnetNLPModels.jl in your work, please cite using the format given in [`CITATION.bib`](CITATION.bib).
## Compatibility
Julia ≥ 1.6.
## How to install
This module can be installed with the following command:
```julia
pkg> add KnetNLPModels
pkg> test KnetNLPModels
```
## Synopsis
KnetNLPModels is an interface between [Knet.jl](https://github.com/denizyuret/Knet.jl.git)'s classification neural networks and [NLPModels.jl](https://github.com/JuliaSmoothOptimizers/NLPModels.jl.git).
A `KnetNLPModel` gives the user access to:
- the values of the neural network variables/weights `w`;
- the value of the objective/loss function `L(X, Y; w)` at `w` for a given minibatch `(X,Y)`;
- the gradient `∇L(X, Y; w)` of the objective/loss function at `w` for a given minibatch `(X,Y)`.
In addition, it provides tools to:
- switch the minibatch used to evaluate the neural network;
- change the minibatch size;
- measure the neural network's accuracy at the current `w`.
## How to use
Check the [tutorial](https://juliasmoothoptimizers.github.io/KnetNLPModels.jl/stable/).
## How to Cite
If you use KnetNLPModels.jl in your work, please cite using the format given in [`CITATION.bib`](https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl/blob/main/CITATION.bib).
# Bug reports and discussions
If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl/issues).
Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please.
If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers), so questions about any of our packages are welcome.
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | docs | 4077 | # Training a LeNet architecture with JSO optimizers
## Neural network architecture
Define the layer Julia structures, how these structures are linked and evaluated.
We choose the negative log likelihood loss function.
```@example LeNetTraining
using Knet
struct ConvolutionnalLayer
weight
bias
activation_function
end
# evaluation of a ConvolutionnalLayer layer given an input x
(c::ConvolutionnalLayer)(x) = c.activation_function.(pool(conv4(c.weight, x) .+ c.bias))
# Constructor of a ConvolutionnalLayer structure
ConvolutionnalLayer(kernel_width, kernel_height, channel_input,
channel_output, activation_function = relu) =
ConvolutionnalLayer(
param(kernel_width, kernel_height, channel_input, channel_output),
param0(1, 1, channel_output, 1),
activation_function
)
struct DenseLayer
weight
bias
activation_function
end
# evaluation of a DenseLayer given an input x
(d::DenseLayer)(x) = d.activation_function.(d.weight * mat(x) .+ d.bias)
# Constructor of a DenseLayer structure
DenseLayer(input::Int, output::Int, activation_function = sigm) =
DenseLayer(param(output, input), param0(output), activation_function)
# A chain of layers ended by a negative log likelihood loss function
struct Chainnll
layers
Chainnll(layers...) = new(layers) # Chainnll constructor
end
# Evaluate successively each layer
# A layer's input is the precedent layer's output
(c::Chainnll)(x) = (for l in c.layers
x = l(x)
end;
x)
# Apply the negative log likelihood function
# on the result of the neural network forward pass
(c::Chainnll)(x, y) = Knet.nll(c(x), y)
(c::Chainnll)(data::Tuple{T1, T2}) where {T1, T2} = c(first(data, 2)...)
(c::Chainnll)(d::Knet.Data) = Knet.nll(c; data = d, average = true)
output_classes = 10
LeNet = Chainnll(ConvolutionnalLayer(5,5,1,6),
ConvolutionnalLayer(5,5,6,16),
DenseLayer(256, 120),
DenseLayer(120, 84),
DenseLayer(84,output_classes)
)
```
## MNIST dataset loading
Accordingly to LeNet architecture, we chose the MNIST dataset from MLDataset:
```@example LeNetTraining
using MLDatasets
ENV["DATADEPS_ALWAYS_ACCEPT"] = true
T = Float32
xtrain, ytrain = MLDatasets.MNIST(Tx = T, split = :train)[:]
xtest, ytest = MLDatasets.MNIST(Tx = T, split = :test)[:]
ytrain[ytrain.==0] .= output_classes # re-arrange indices
ytest[ytest.==0] .= output_classes # re-arrange indices
data_train = (xtrain, ytrain)
data_test = (xtest, ytest)
```
## KnetNLPModel instantiation
From these elements, we transfer the Knet.jl architecture to a `KnetNLPModel`:
```@example LeNetTraining
using KnetNLPModels
size_minibatch = 100
LeNetNLPModel = KnetNLPModel(
LeNet;
data_train,
data_test,
size_minibatch,
)
```
which will instantiate automatically the mandatory data-structures as `Vector` or `CuVector` if the code is launched either on a CPU or on a GPU.
The following code snippet executes the R2 solver with a `callback` that changes the training minibatch at each iteration:
```@example LeNetTraining
using JSOSolvers
max_time = 30.
callback = (nlp, solver, stats) -> KnetNLPModels.minibatch_next_train!(nlp)
solver_stats = R2(LeNetNLPModel; callback, max_time)
test_accuracy = KnetNLPModels.accuracy(LeNetNLPModel)
```
Other solvers may also be applied for any KnetNLPModel:
```@example LeNetTraining
solver_stats = lbfgs(LeNetNLPModel; callback, max_time)
test_accuracy = KnetNLPModels.accuracy(LeNetNLPModel)
```
In the last case, `LeNetNLPModel` is wrapped with a LSR1 approximation of loss Hessian to define a `lsr1_LeNet` NLPModel.
The callback must be adapted to work on `LeNetNLPModel` which is accessible from `lsr1_LeNet.model`.
```@example LeNetTraining
using NLPModelsModifiers
lsr1_LeNet = NLPModelsModifiers.LSR1Model(LeNetNLPModel)
callback_lsr1 = (lsr1_nlpmodel, solver, stats) -> KnetNLPModels.minibatch_next_train!(lsr1_nlpmodel.model)
solver_stats = trunk(lsr1_LeNet; callback = callback_lsr1, max_time)
test_accuracy = KnetNLPModels.accuracy(LeNetNLPModel)
``` | KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | docs | 1642 | # KnetNLPModels.jl
## Compatibility
Julia ≥ 1.6.
## How to install
This module can be installed with the following command:
```julia
pkg> add KnetNLPModels
pkg> test KnetNLPModels
```
## Synopsis
KnetNLPModels is an interface between [Knet.jl](https://github.com/denizyuret/Knet.jl.git)'s classification neural networks and [NLPModels.jl](https://github.com/JuliaSmoothOptimizers/NLPModels.jl.git).
A `KnetNLPModel` gives the user access to:
- the values of the neural network variables/weights `w`;
- the value of the objective/loss function `L(X, Y; w)` at `w` for a given minibatch `(X,Y)`;
- the gradient `∇L(X, Y; w)` of the objective/loss function at `w` for a given minibatch `(X,Y)`.
In addition, it provides tools to:
- switch the minibatch used to evaluate the neural network;
- change the minibatch size;
- measure the neural network's accuracy at the current `w`.
## How to use
Check the [tutorial](https://juliasmoothoptimizers.github.io/KnetNLPModels.jl/stable/).
# Bug reports and discussions
If you think you found a bug, feel free to open an [issue](https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl/issues).
Focused suggestions and requests can also be opened as issues. Before opening a pull request, start an issue or a discussion on the topic, please.
If you want to ask a question not suited for a bug report, feel free to start a discussion [here](https://github.com/JuliaSmoothOptimizers/Organization/discussions). This forum is for general discussion about this repository and the [JuliaSmoothOptimizers](https://github.com/JuliaSmoothOptimizers), so questions about any of our packages are welcome.
| KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | docs | 166 | # Reference
## Contents
```@contents
Pages = ["reference.md"]
```
## Index
```@index
Pages = ["reference.md"]
```
```@autodocs
Modules = [KnetNLPModels]
``` | KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MPL-2.0"
] | 0.2.3 | e9396e69da7fdb95f9241a1100b3f16ac5c87e06 | docs | 4921 | # KnetNLPModels.jl Tutorial
## Preliminaries
This step-by-step example assume prior knowledge of [julia](https://julialang.org/) and [Knet.jl](https://github.com/denizyuret/Knet.jl.git).
See the [Julia tutorial](https://julialang.org/learning/) and the [Knet.jl tutorial](https://github.com/denizyuret/Knet.jl/tree/master/tutorial) for more details.
### Define the layers of interest
The following code defines a dense layer as a callable julia structure for use on a CPU, via `Matrix` and `Vector` or on a GPU via [CUDA.jl](https://github.com/JuliaGPU/CUDA.jl) and `CuArray`:
```@example KnetNLPModel
using Knet, CUDA
mutable struct Dense{T, Y}
w :: Param{T}
b :: Param{Y}
f # activation function
end
(d :: Dense)(x) = d.f.(d.w * mat(x) .+ d.b) # evaluate the layer for a given input x
# define a dense layer with input size i and output size o
Dense(i :: Int, o :: Int, f=sigm) = Dense(param(o, i), param0(o), f)
```
More sophisticated layers may be defined.
Once again, see the [Knet.jl tutorial](https://github.com/denizyuret/Knet.jl/tree/master/tutorial) for more details.
### Definition of the loss function (negative log likelihood)
Next, we define a chain that stacks layer, to evaluate them successively.
```@example KnetNLPModel
using KnetNLPModels
struct ChainNLL
layers
ChainNLL(layers...) = new(layers)
end
(c :: ChainNLL)(x) = (for l in c.layers; x = l(x); end; x) # evaluate the network for a given input x
(c :: ChainNLL)(x, y) = Knet.nll(c(x), y) # compute the loss function given input x and expected output y
(c :: ChainNLL)(data :: Tuple{T1,T2}) where {T1,T2} = c(first(data,2)...) # evaluate loss given data inputs (x,y)
(c :: ChainNLL)(d :: Knet.Data) = Knet.nll(c; data=d, average=true) # evaluate loss using a minibatch iterator d
DenseNet = ChainNLL(Dense(784, 200), Dense(200, 50), Dense(50, 10))
```
### Load datasets and define minibatch
In this example, and to fit the architecture proposed, we use the [MNIST](https://juliaml.github.io/MLDatasets.jl/stable/datasets/MNIST/) dataset from [MLDatasets.jl](https://github.com/JuliaML/MLDatasets.jl.git).
```@example KnetNLPModel
using MLDatasets
# download datasets without user intervention
ENV["DATADEPS_ALWAYS_ACCEPT"] = true
T = Float32
xtrain, ytrain = MLDatasets.MNIST(Tx = T, split = :train)[:]
xtest, ytest = MLDatasets.MNIST(Tx = T, split = :test)[:]
ytrain[ytrain.==0] .= 10 # re-arrange indices
xtest, ytest = MNIST.testdata(Float32) # MNIST test dataset
ytest[ytest.==0] .= 10 # re-arrange indices
dtrn = minibatch(xtrain, ytrain, 100; xsize=(size(xtrain, 1), size(xtrain, 2), 1, :)) # training minibatch
dtst = minibatch(xtest, ytest, 100; xsize=(size(xtest, 1), size(xtest, 2), 1, :)) # test minibatch
```
## Definition of the neural network and KnetNLPModel
Finally, we define the `KnetNLPModel` from the neural network.
By default, the size of each minibatch is 1% of the corresponding dataset offered by MNIST.
```@example KnetNLPModel
DenseNetNLPModel = KnetNLPModel(DenseNet; size_minibatch=100, data_train=(xtrain, ytrain), data_test=(xtest, ytest))
```
All the methods provided by KnetNLPModels.jl support both `CPU` and `GPU`.
## Tools associated with a KnetNLPModel
The problem dimension `n`, where `w` ∈ ℝⁿ:
```@example KnetNLPModel
n = DenseNetNLPModel.meta.nvar
```
### Get the current network weights:
```@example KnetNLPModel
w = vector_params(DenseNetNLPModel)
```
### Evaluate the loss function (i.e. the objective function) at `w`:
```@example KnetNLPModel
using NLPModels
NLPModels.obj(DenseNetNLPModel, w)
```
The length of `w` must be `DenseNetNLPModel.meta.nvar`.
### Evaluate the gradient at `w`:
```@example KnetNLPModel
g = similar(w)
NLPModels.grad!(DenseNetNLPModel, w, g)
```
The result is stored in `g :: Vector{T}`, `g` is similar to `v` (of size `DenseNetNLPModel.meta.nvar`).
### Evaluate the network accuracy:
The accuracy of the network can be evaluated with:
```@example KnetNLPModel
KnetNLPModels.accuracy(DenseNetNLPModel)
```
`accuracy()` uses the full training dataset.
That way, the accuracy will not fluctuate with the minibatch.
## Default behavior
By default, the training minibatch that evaluates the neural network doesn't change between evaluations.
To change the training minibatch, use one of the following methods:
* To select a minibatch randomly
```@example KnetNLPModel
rand_minibatch_train!(DenseNetNLPModel)
```
* To select the next minibatch from the current minibatch iterator (can be used in a loop to go over the whole dataset)
```@example KnetNLPModel
minibatch_next_train!(DenseNetNLPModel)
```
* Reset to the first minibatch
```@example KnetNLPModel
reset_minibatch_train!(DenseNetNLPModel)
```
The size of the new minibatch is the size defined earlier.
The size of the training and test minibatch can be set to `1/p` the size of the dataset with:
```@example KnetNLPModel
p = 120
set_size_minibatch!(DenseNetNLPModel, p) # p::Int > 1
``` | KnetNLPModels | https://github.com/JuliaSmoothOptimizers/KnetNLPModels.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 8198 | using UnfoldSim
using TopoPlots
using Unfold
using Random
"""
example_data(String)
Creates example data or model. Currently, 3 datasets and 6 models are available.
Datasets:
- `TopoPlots.jl` (default) - 2 DataFrames from `TopoPlots.jl`:\\
- DataFrame with estimate, time, 64 channels, topopositions, sterror and pvalue and 800 ms time range.\\
- Posiions for 64 electrodes.
- `UnfoldLinearModelMultiChannel` - DataFrame with 5 channels, 3 coefnames, sterror, time and estimate.
- `sort_data` - 2 DataFrames:
- `dat` for EEG recordings and `evts` with event variables occured during experiment.\\
- `evts` could be used for sorting EEG data in ERP image.
Models:
- `UnfoldLinearModel` - Model with formula `1 + condition + continuous`.
- `UnfoldLinearModelContinuousTime` - Model with formula `timeexpand(1 + condition + continuous)` for times [0.0, 0.01 ... 0.5].
- `UnfoldLinearModelwith1Spline` - Model with formula `1 + condition + spl(continuous, 4)`.
- `UnfoldLinearModelwith2Splines` - Model with formula ` 1 + condition + spl(continuous, 4) + spl(continuous2, 6)`.
- `7channels` - Model with formula `timeexpand(1 + condA)` for times [-0.1, -0.09 ... 0.5].
- `UnfoldTimeExpanded` - Model with formula `timeexpand(1 + condition + continuous)` for times [-0.4, -0.39 ... 0.8].
**Return Value:** `DataFrame`.
"""
function example_data(example = "TopoPlots.jl")
if example == "UnfoldLinearModel"
# load and generate a simulated Unfold Design
data, evts = UnfoldSim.predef_eeg(; noiselevel = 12, return_epoched = true)
data = reshape(data, (1, size(data)...))
f = @formula 0 ~ 1 + condition + continuous
# generate ModelStruct
se_solver = (x, y) -> Unfold.solver_default(x, y, stderror = true)
return fit(
UnfoldModel,
[Any => (f, range(0, length = size(data, 2), step = 1 / 100))],
evts,
data;
solver = se_solver,
)
elseif example == "UnfoldLinearModelMultiChannel"
# load and generate a simulated Unfold Design
cAll = DataFrame()
sfreq = 100
for ch = 1:5
data, evts = UnfoldSim.predef_eeg(;
p1 = (p100(; sfreq = sfreq), @formula(0 ~ 1), [5], Dict()),
n1 = (
n170(; sfreq = sfreq),
@formula(0 ~ 1 + condition),
[5, -ch * 0.5],
Dict(),
),
p3 = (p300(; sfreq = sfreq), @formula(0 ~ 1 + continuous), [ch, 1], Dict()),
return_epoched = true,
)
data = reshape(data, 1, size(data)...)
f = @formula 0 ~ 1 + condition + continuous
# generate ModelStruct
m = fit(
UnfoldModel,
[(Any => (f, range(0, length = size(data, 2), step = 1 / 100)))],
evts,
data,
)
d = coeftable(m)
d.channel .= ch
cAll = append!(cAll, d)
end
return cAll
elseif example == "UnfoldLinearModelContinuousTime"
# load and generate a simulated Unfold Design
data, evts = UnfoldSim.predef_eeg(;)
data = reshape(data, 1, size(data)...)
f = @formula 0 ~ 1 + condition + continuous
basis = firbasis([0, 0.5], 100)
# generate ModelStruct
return fit(UnfoldModel, [Any => (f, basis)], evts, data)
elseif example == "UnfoldLinearModelwith1Spline"
# load and generate a simulated Unfold Design
data, evts = UnfoldSim.predef_eeg(; noiselevel = 12, return_epoched = true)
data = reshape(data, (1, size(data)...))
evts.continuous2 .=
log10.(6 .+ rand(MersenneTwister(1), length(evts.continuous))) .^ 2
f = @formula 0 ~ 1 + condition + spl(continuous, 4)
# generate ModelStruct
se_solver = (x, y) -> Unfold.solver_default(x, y, stderror = true)
return fit(
UnfoldModel,
[Any => (f, range(0, length = size(data, 2), step = 1 / 100))],
evts,
data;
solver = se_solver,
)
elseif example == "UnfoldLinearModelwith2Splines"
# load and generate a simulated Unfold Design
data, evts = UnfoldSim.predef_eeg(; noiselevel = 12, return_epoched = true)
data = reshape(data, (1, size(data)...))
evts.continuous2 .=
log10.(6 .+ rand(MersenneTwister(1), length(evts.continuous))) .^ 2
f = @formula 0 ~ 1 + condition + spl(continuous, 4) + spl(continuous2, 6)
# generate ModelStruct
se_solver = (x, y) -> Unfold.solver_default(x, y, stderror = true)
return fit(
UnfoldModel,
[Any => (f, range(0, length = size(data, 2), step = 1 / 100))],
evts,
data;
solver = se_solver,
)
elseif example == "7channels"
design =
SingleSubjectDesign(conditions = Dict(:condA => ["levelA", "levelB"])) |>
x -> RepeatDesign(x, 20)
c = LinearModelComponent(;
basis = p100(),
formula = @formula(0 ~ 1 + condA),
β = [1, 0.5],
)
mc = MultichannelComponent(c, [1, 2, -1, 3, 5, 2.3, 1])
onset = UniformOnset(; width = 20, offset = 4)
df, evnts =
simulate(MersenneTwister(1), design, [mc], onset, PinkNoise(noiselevel = 0.05))
basisfunction = firbasis((-0.1, 0.5), 100)
f = @formula 0 ~ 1 + condA
bf_dict = [Any => (f, basisfunction)]
return fit(UnfoldModel, bf_dict, evnts, df)
elseif example == "UnfoldTimeExpanded"
df, evts = UnfoldSim.predef_eeg()
f = @formula 0 ~ 1 + condition + continuous
basisfunction = firbasis(τ = (-0.4, 0.8), sfreq = 100, name = "stimulus")
#basisfunction = firbasis(τ = (-0.4, -0.3), sfreq = 10)
bfDict = [Any => (f, basisfunction)]
return fit(UnfoldModel, bfDict, evts, df)
elseif example == "TopoPlots.jl"
data, chanlocs = TopoPlots.example_data()
df = DataFrame(
estimate = Float64[],
time = Float64[],
channel = Int64[],
coefname = String[],
topo_positions = [],
se = Float64[],
pval = Float64[],
)
pos = TopoPlots.points2mat(chanlocs)
for ch = 1:size(data, 1)
for t = 1:size(data, 2)
append!(
df,
DataFrame(
estimate = data[ch, t, 1],
se = data[ch, t, 2],
pval = data[ch, t, 3],
time = t,
channel = ch,
coefname = "A",
topo_positions = (pos[1, ch], pos[2, ch]),
),
)
end
end
df.time = range(-0.3, 0.5, step = 1 / 500)[Int.(df.time)]
return df, chanlocs
elseif example == "sort_data" #this should be reviewed
dat, evts =
UnfoldSim.predef_eeg(; onset = LogNormalOnset(μ = 3.5, σ = 0.4), noiselevel = 5)
dat_e, times = Unfold.epoch(dat, evts, [-0.1, 1], 100)
evts, dat_e = UnfoldMakie.drop_missing_epochs(evts, dat_e)
evts.Δlatency = vcat(diff(evts.latency), 0)
dat_e = dat_e[1, :, :]
#evts = filter(row -> row.Δlatency > 0, evts)
return dat_e, evts, times
elseif example == "raw_ch_names"
return [
"FP1",
"F3",
"F7",
"FC3",
"C3",
"C5",
"P3",
"P7",
"P9",
"PO7",
"PO3",
"O1",
"Oz",
"Pz",
"CPz",
"FP2",
"Fz",
"F4",
"F8",
"FC4",
"FCz",
"Cz",
"C4",
"C6",
"P4",
"P8",
"P10",
"PO8",
"PO4",
"O2",
]
else
error("unknown example data")
end
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2907 | using UnfoldMakie
using Documenter
using DocStringExtensions
# preload once
using CairoMakie
const Makie = CairoMakie # - for references
using AlgebraOfGraphics
using Unfold
using DataFrames
using DataFramesMeta
using Literate
using Glob
GENERATED = joinpath(@__DIR__, "src", "generated")
SOURCE = joinpath(@__DIR__, "literate")
for subfolder ∈ ["how_to", "intro", "tutorials", "explanations"]
local SOURCE_FILES = Glob.glob(subfolder * "/*.jl", SOURCE)
foreach(fn -> Literate.markdown(fn, GENERATED * "/" * subfolder), SOURCE_FILES)
end
DocMeta.setdocmeta!(UnfoldMakie, :DocTestSetup, :(using UnfoldMakie); recursive = true)
makedocs(;
modules = [UnfoldMakie],
authors = "Vladimir Mikheev, Sören Döring, Niklas Gärtner, Daniel Baumgartner, Benedikt Ehinger",
repo = Documenter.Remotes.GitHub("unfoldtoolbox", "UnfoldMakie.jl"),
sitename = "UnfoldMakie.jl",
warnonly = :cross_references,
format = Documenter.HTML(;
prettyurls = get(ENV, "CI", "false") == "true",
canonical = "https://unfoldtoolbox.github.io/UnfoldMakie.jl",
assets = String[],
),
pages = [
"UnfoldMakie Documentation" => "index.md",
"Intro" => [
"Installation" => "generated/intro/installation.md",
"Plot types" => "generated/intro/plot_types.md",
"Code principles" => "generated/intro/code_principles.md",
],
"ERP Visualizations" => [
"ERP plot" => "generated/tutorials/erp.md",
"Butterfly plot" => "generated/tutorials/butterfly.md",
"Topoplot" => "generated/tutorials/topoplot.md",
"Topoplot series" => "generated/tutorials/topoplotseries.md",
"ERP grid" => "generated/tutorials/erp_grid.md",
"ERP image" => "generated/tutorials/erpimage.md",
"Channel image" => "generated/tutorials/channel_image.md",
"Parallel coordinates" => "generated/tutorials/parallelcoordinates.md",
"Circular topoplots" => "generated/tutorials/circ_topo.md",
],
"Unfold-specific Visualisations" => [
"Design matrix" => "generated/tutorials/designmatrix.md",
"Spline plot" => "generated/tutorials/splines.md",
],
"How To" => [
"Change colormap of Butterfly plot" => "generated/how_to/position2color.md",
"Hide decorations and axis spines" => "generated/how_to/hide_deco.md",
"Include multiple figures in one" => "generated/how_to/mult_vis_in_fig.md",
],
"Explanations" => [
"Convert electrode positions from 3D to 2D" => "generated/explanations/positions.md",
],
"API / DocStrings" => "api.md",
"Utilities" => "helper.md",
],
)
deploydocs(;
repo = "github.com/unfoldtoolbox/UnfoldMakie.jl",
devbranch = "main",
versions = "v#.#",
push_preview = true,
)
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 175 | using LiveServer
servedocs(
skip_dir = joinpath("src", "generated"),
literate_dir = joinpath("literate"),
literate = joinpath("literate"),
foldername = ".",
)
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1302 | # # Convert electrode positions form 3D to 2D
# Sometimes you have 3D montage but you need 2D montage. How to convert one to another? The function `to_positions` should help.
using UnfoldMakie
using CairoMakie
using TopoPlots
using PyMNE;
# # Get positions from MNE
# Generate an MNE structure [taken from mne documentation](https://mne.tools/0.24/auto_examples/visualization/eeglab_head_sphere.html)
biosemi_montage = PyMNE.channels.make_standard_montage("biosemi64")
n_channels = length(biosemi_montage.ch_names)
fake_info =
PyMNE.create_info(ch_names = biosemi_montage.ch_names, sfreq = 250.0, ch_types = "eeg")
data = rand(n_channels, 1) * 1e-6
fake_evoked = PyMNE.EvokedArray(data, fake_info)
fake_evoked.set_montage(biosemi_montage)
pos = to_positions(fake_evoked)
# # Projecting from 3D montage to 2D
pos3d = hcat(values(pyconvert(Dict, biosemi_montage.get_positions()["ch_pos"]))...)
pos2 = to_positions(pos3d)
f = Figure(size = (600, 300))
scatter(f[1, 1], pos3d[1:2, :], axis = (title = "Dropping third dimension",))
scatter(f[1, 2], pos2, axis = (title = "Projection form 3D to 2D",))
f
# As you can see, the "naive" transformation of simply dropping the third dimension does not really work (left). Instead, we have to project the channels onto a sphere and unfold it (right).
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2250 | # # Hiding decorations and spines
# You have several options for efficiently hiding decorations and axis spines in a plot.
# # Package input
using TopoPlots
using UnfoldMakie
using CairoMakie
using DataFrames
include("../../../example_data.jl")
data, pos = example_data("TopoPlots.jl")
dat, evts = UnfoldSim.predef_eeg(; noiselevel = 10, return_epoched = true)
# # Hiding
#=
First, you can specify the axis settings with `axis = (; ...)`.
`Makie.Axis` provides multiple variables for different aspects of the plot. This means that removing all decorations is only possible by setting many variables each time.
Second, `Makie` does provide methods like `hidespines!` and `hidedecorations!`. Unforunately, user may lose access to a plot after it is drawn in.
Third, `hidespines!` and `hidedecorations!` can be called by setting variables with `layout = (; hidespines = (), hidedecorations = ())`.
You still will able to specify it flexibly: `hidespines = (:r, :t)` will remove the top and right borders.
=#
f = Figure()
plot_butterfly!(
f[1, 1],
data;
positions = pos,
topomarkersize = 10,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
axis = (; title = "With decorations"),
)
plot_butterfly!(
f[2, 1],
data;
positions = pos,
topomarkersize = 10,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
axis = (; title = "Without decorations"),
layout = (; hidedecorations = (:label => true, :ticks => true, :ticklabels => true)),
)
f
# You can also completely remove all spines, decorations, color bars, and even padding.
f = Figure(; figure_padding = 0)
plot_erpimage!(
f,
dat;
layout = (; hidespines = (), hidedecorations = (), use_colorbar = false),
)
# # Showing
#=
Some plots hide features by default. This could be reverted by setting the variables to `nothing`
=#
data, positions = TopoPlots.example_data()
plot_topoplot(
data[:, 340, 1];
positions = positions,
layout = (; hidespines = nothing, hidedecorations = nothing),
)
# For more information on the input of these functions refer to the [Makie dokumentation on Axis.](https://makie.juliaplots.org/v0.15.2/examples/layoutables/axis/#hiding_axis_spines_and_decorations)
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 5449 | # # [Include multiple Visualizations in one Figure](@id ht_mvf)
#=
This section discusses how users can incorporate multiple plots into a single figure.
=#
# # Setup
# ## Library load
using UnfoldMakie
using CairoMakie
using DataFramesMeta
using UnfoldSim
using Unfold
using MakieThemes
set_theme!(theme_ggthemr(:fresh)) # nicer defaults - should maybe be default?
# ## Data input
include("../../../example_data.jl")
d_topo, positions = example_data("TopoPlots.jl")
uf_deconv = example_data("UnfoldLinearModelContinuousTime")
uf = example_data("UnfoldLinearModel")
results = coeftable(uf)
uf_5chan = example_data("UnfoldLinearModelMultiChannel")
data, positions = TopoPlots.example_data()
dat_e, evts, times = example_data("sort_data")
d_singletrial, _ = UnfoldSim.predef_eeg(; return_epoched = true)
nothing #hide
# # Basic complex figure
#=
By using the !-version of the plotting function and inserting a grid position instead of an entire figure, we can create complex plot combining several figures.
=#
# We will start by creating a figure with `Makie.Figure`.
# `f = Figure()`
# Now any plot can be added to `f` by placing a grid position, such as `f[1, 1]`.
f = Figure()
plot_erp!(f[1, 1], coeftable(uf_deconv))
plot_erp!(
f[1, 2],
effects(Dict(:condition => ["car", "face"]), uf_deconv),
mapping = (; color = :condition),
)
plot_butterfly!(f[2, 1:2], d_topo; positions = positions)
f
# # Very complex figure
#=
We can create a large figure with any type of plot using predefined data.
With so many plots at once, it's better to set a fixed resolution in your image to order the plots evenly.
=#
# ```@raw html
# <details>
# <summary>Click to expand</summary>
# ```
f = Figure(size = (2000, 2000))
plot_butterfly!(f[1, 1:3], d_topo; positions = positions)
pvals = DataFrame(
from = [0.1, 0.15],
to = [0.2, 0.5], # if coefname not specified, line should be black
coefname = ["(Intercept)", "category: face"],
)
plot_erp!(f[2, 1:2], results, significance = pvals, stderror = true)
plot_designmatrix!(f[2, 3], designmatrix(uf))
plot_topoplot!(f[3, 1], data[:, 150, 1]; positions = positions)
plot_topoplotseries!(
f[4, 1:3],
d_topo;
bin_width = 0.1,
positions = positions,
mapping = (; label = :channel),
)
res_effects = effects(Dict(:continuous => -5:0.5:5), uf_deconv)
plot_erp!(
f[2, 4:5],
res_effects;
mapping = (; y = :yhat, color = :continuous, group = :continuous => nonnumeric),
legend = (; nbanks = 2),
)
plot_parallelcoordinates(
f[3, 2:3],
uf_5chan;
mapping = (; color = :coefname),
)
plot_erpimage!(f[1, 4:5], times, d_singletrial)
plot_circular_topoplots!(
f[3:4, 4:5],
d_topo[in.(d_topo.time, Ref(-0.3:0.1:0.5)), :];
positions = positions,
predictor = :time,
predictor_bounds = [-0.3, 0.5],
)
# ```@raw html
# </details >
# ```
f
# # Complex figure in two columns
# ```@raw html
# <details>
# <summary>Click to expand</summary>
# ```
f = Figure(size = (1200, 1400))
ga = f[1, 1]
gc = f[2, 1]
ge = f[3, 1]
gg = f[4, 1]
gb = f[1, 2]
gd = f[2, 2]
gf = f[3, 2]
gh = f[4, 2]
d_topo, pos = example_data("TopoPlots.jl")
data, positions = TopoPlots.example_data()
df = UnfoldMakie.eeg_array_to_dataframe(data[:, :, 1], string.(1:length(positions)))
raw_ch_names = example_data("raw_ch_names")
m = example_data("UnfoldLinearModel")
results = coeftable(m)
results.coefname =
replace(results.coefname, "condition: face" => "face", "(Intercept)" => "car")
results = filter(row -> row.coefname != "continuous", results)
plot_erp!(ga, results; :stderror => true, mapping = (; color = :coefname => "Conditions"))
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
plot_butterfly!(
gb,
d_topo;
positions = pos,
topomarkersize = 10,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
plot_topoplot!(gc, data[:, 340, 1]; positions = positions, axis = (; xlabel = "[340 ms]"))
plot_topoplotseries!(
gd,
df;
bin_width = 80,
positions = positions,
visual = (label_scatter = false,),
layout = (; use_colorbar = true),
)
ax = gd[1, 1] = Axis(f)
text!(ax, 0, 0, text = "Time [ms]", align = (:center, :center), offset = (-20, -80))
hidespines!(ax) # delete unnecessary spines (lines)
hidedecorations!(ax, label = false)
plot_erpgrid!(
ge,
data[:, :, 1],
positions;
axis = (; ylabel = "µV", ylim = [-0.05, 0.6], xlim = [-0.04, 1]),
)
dat_e, evts, times = example_data("sort_data")
plot_erpimage!(gf, times, dat_e; sortvalues = evts.Δlatency)
plot_channelimage!(gg, data[1:30, :, 1], positions[1:30], raw_ch_names;)
r1, positions = example_data()
r2 = deepcopy(r1)
r2.coefname .= "B" # create a second category
r2.estimate .+= rand(length(r2.estimate)) * 0.1
results_plot = vcat(r1, r2)
plot_parallelcoordinates(
gh,
subset(results_plot, :channel => x -> x .< 8, :time => x -> x .< 0);
mapping = (; color = :coefname),
normalize = :minmax,
ax_labels = ["FP1", "F3", "F7", "FC3", "C3", "C5", "P3", "P7"],
)
for (label, layout) in
zip(["A", "B", "C", "D", "E", "F", "G", "H"], [ga, gb, gc, gd, ge, gf, gg, gh])
Label(
layout[1, 1, TopLeft()],
label,
fontsize = 26,
font = :bold,
padding = (20, 20, 22, 0),
halign = :right,
)
end
# ```@raw html
# </details >
# ```
f
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2055 | # # [Change colormap of Butterfly plot ](@id pos2color)
# You want to change the colors of the lines and markers on the inserted topoplot.
# To do that you need to change the color scheme (aka color map) of the butterfly plot.
# You can find th elist of colormaps for Makie [here](https://docs.makie.org/v0.21/explanations/colors).
# # Setup
using UnfoldMakie
using CairoMakie
using DataFramesMeta
using Colors
# By default the plot looks like this:
include("../../../example_data.jl")
results, positions = example_data("TopoPlots.jl")
plot_butterfly(results; positions = positions)
# # Color schemes
# ## MNE style
# We can change the color scale by specifying a function that maps from an `(x, y)` tuple to a color.
# `UnfoldMakie` currently provides three different color scales:
# - `pos2colorRGB` (same as MNE-Python),
# - `pos2colorHSV` (HSV color space),
# - `pos2colorRomaO`.
# While `RGB` & `HSV` have the advantage of being 2D color maps, `Roma0` has the advantage of being perceptually uniform.
# Also you can specify a uniform color.
plot_butterfly(
results;
positions = positions,
topopositions_to_color = pos -> UnfoldMakie.pos_to_color_RGB(pos),
)
# ## HSV-Space
plot_butterfly(
results;
positions = positions,
topopositions_to_color = UnfoldMakie.pos_to_color_HSV,
)
# ## Uniform Color
# You can make all lines "gray", or any other arbitrary color.
# Also you can make it a function of electrode position.
plot_butterfly(
results;
positions = positions,
topopositions_to_color = x -> Colors.RGB(0.5),
)
# ## Transparency
# Unlike RGB, RGBA has a fourth channel, alpha, which is responsible for transparency.
# Here are two examples of how to manipulate it.
f = Figure()
plot_butterfly!(
f[1, 1],
results;
positions = positions,
topopositions_to_color = x -> (RGBA(UnfoldMakie.pos_to_color_RomaO(x), 1)),
)
plot_butterfly!(
f[2, 1],
results;
positions = positions,
topopositions_to_color = x -> (GrayA(UnfoldMakie.pos_to_color_RomaO(x), 0.5)),
)
f
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 584 | # # Code principles
# Here we will write about principles which we developed through our publication.
# - Code should be clear and concise.
# - Variables inside the code should have meaningful names.
# - Every function exposed to the user should have documentation that specifies all parameters, types, input and output arguments.
# - Most people will not look at the defaults, so it is very important to nudge users to label important details of the plot.
# - Function naming should be based on some theory and naming conventions.
# - You should avoid functions longer 50 lines.
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1334 | # # Getting Julia
# You can install Julia by following the instructions from the [official website](https://julialang.org/).
# ## Setup UnfoldMakie.jl
# After installing Julia, you can execute the `julia.exe`.
# ## Generate a Project
# If you do not yet have a project you can generate one.
# First you type `]` into the Julia console to switch from `julia` to `(@VERSION) pkg`.
# Here you can generate a project by using the command:
# `generate "FOLDER_PATH"`
# Note that the specific folder in which you want to generate the project does not already exist.
# ## Activate your Project
# Before you can add the necessary modules to use UnfoldMakie you have to activate your project in the `(@VERSION) pkg` environment.
# The command is:
# `activate "FOLDER_PATH"`
# ## Install the UnfoldMakie Module
# When your project is activated you can add the module.
# The command is:
# `add UnfoldMakie`
# ## Using the Project in a Pluto Notebook
# In case you want to use this generated project in a notebook (e.g. [Pluto](https://www.juliapackages.com/p/pluto) or [Jupyter](https://ipython.org/notebook.html)), you can activate this in the notebook in the following manner:
# ```julia
# begin
# using Pkg
# Pkg.activate("FOLDER_PATH")
# Pkg.resolve()
# end
# ```
# Use slash `/` for the folder path.
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 892 | # # The Dilemma of Multidimensionality
# !!! note
# Please read the paper [The Art of Brainwaves](https://apertureneuro.org/article/116386-the-art-of-brainwaves-a-survey-on-event-related-potential-visualization-practices), if you want to know how we come up with these plot types.
#=
EEG – multidimensional data and could be presented differently.
Possible dimensions:
- Voltage (must have)
- Time
- Number of channels (1-128)
- Spatial layout of channels
- Experimental conditions
- Trials/subjects
=#
# ```@raw html
# <img src="../../../assets/slicing.jpg" align="middle"/>
# ```
#=
Each way of ERP presentation is a choice of dimensions.
Hard to show meaningfully more than 3 dimensions.
=#
# # Plot types
# Each plot type can represent several dimensions. Here we represented 8 plot types.
# ```@raw html
# <img src="../../../assets/dimensions.jpg" align="middle"/>
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3074 | # # [Butterfly Plot](@id bfp_vis)
# **Butterfly plot** is a plot type for visualisation of Event-related potentials.
# It can fully represent time and channels dimensions using lines. With addition of topoplot inset it can also represent location of channels.
# It called "butterfly" because the envelope of channels reminds butterfly wings🦋.
# The configurations of [ERP plots](@ref erp_vis) and Butterfly plots are somehow similar.
# # Setup
# Package loading
# The following modules are necessary for run this tutorial:
using UnfoldMakie
using Unfold
using CairoMakie
using DataFrames
using Colors
# Note that `DataFramesMeta` is also used here in order to be able to use `@subset` for testing (filtering).
# Data
# We filter the data to make it more clearly represented:
include("../../../example_data.jl")
df, pos = example_data("TopoPlots.jl")
first(df, 3)
# # Plot Butterfly Plots
# The default butterfly plot:
plot_butterfly(df)
# The butterfly plot with corresponding topoplot. You need to provide the channel positions.
plot_butterfly(df; positions = pos)
# You want to change size of topomarkers and size of topoplot:
plot_butterfly(
df;
positions = pos,
topomarkersize = 10,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
)
# You want to add vline and hline:
f = Figure()
plot_butterfly!(f, df; positions = pos)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
f
# You want to remove all decorations:
plot_butterfly(
df;
positions = pos,
layout = (; hidedecorations = (:label => true, :ticks => true, :ticklabels => true)),
)
# # Changing the colors of channels
# Please check [this page](@ref pos2color).
# You want to highlight a specific channel or channels.
# Specify channels first:
df.highlight1 = in.(df.channel, Ref([12])) # for single channel
df.highlight2 = in.(df.channel, Ref([10, 12])) # for multiple channels
nothing #hide
# Second, you can highlight it or them by color.
gray = Colors.RGB(128 / 255, 128 / 255, 128 / 255)
f = Figure(size = (1000, 400))
plot_butterfly!(
f[1, 1],
df;
positions = pos,
mapping = (; color = :highlight1),
visual = (; color = 1:2, colormap = [gray, :red]),
)
plot_butterfly!(
f[1, 2],
df;
positions = pos,
mapping = (; color = :highlight2),
visual = (; color = 1:2, colormap = [gray, :red]),
)
f
# Or by faceting:
df.highlight2 = replace(df.highlight2, true => "channels 10, 12", false => "all channels")
plot_butterfly(
df;
positions = pos,
mapping = (; color = :highlight2, col = :highlight2),
visual = (; color = 1:2, colormap = [gray, :red]),
)
# # Column Mappings for Butterfly Plot
# Since butterfly plots use a `DataFrame` as input, the library needs to know the names of the columns used for plotting. You can set these mapping values by calling `plot_butterfly(...; mapping=(; :x=:time))`. Just specify a `NamedTuple`. Note the `;` right after the opening parentheses.
# # Configurations of Butterfly Plot
# ```@docs
# plot_butterfly
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 905 | # # Channel image
# **Channel image** is a plot type for visualizing EEG activity for all channels.
# It can fully represent time and channel dimensions using a heatmap.
# Y-axis represents all channels, x-axis represents time, while color represents voltage.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using CairoMakie
using UnfoldSim
include("../../../example_data.jl")
# # Plot Channel image
# The following code will result in the default configuration.
data, pos = TopoPlots.example_data()
data = data[:, :, 1]
pos = pos[1:30]
raw_ch_names = ["FP1", "F3", "F7", "FC3", "C3", "C5", "P3", "P7", "P9", "PO7",
"PO3", "O1", "Oz", "Pz", "CPz", "FP2", "Fz", "F4", "F8", "FC4", "FCz", "Cz",
"C4", "C6", "P4", "P8", "P10", "PO8", "PO4", "O2"]
plot_channelimage(data[1:30, :], pos, raw_ch_names;)
# # Configurations for Channel image
# ```@docs
# plot_channelimage
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1520 | # # Circular Topoplots
# **Circular topoplot series** is a plot type for visualizing EEG activity in relation to some continous variable arranged on a circluar line.
# It can fully represent channel and channel location dimensions using contour lines. It can also partially represent the varaible dimension.
# Variable could be for instance saccadic amplitude or degrees of visual angle.
# Basically, it is a series of Topoplots arranged on a circle.
# # Setup
# Package loading
using UnfoldMakie
using CairoMakie
using TopoPlots # for example data
using Random
using DataFrames
# Data generation
# Generate a `Dataframe`. We need to specify the Topoplot positions either via `position`, or via `labels`.
data, pos = TopoPlots.example_data();
dat = data[:, 240, 1]
df = DataFrame(
:estimate => eachcol(Float64.(data[:, 100:40:300, 1])),
:circular_variable => [0, 50, 80, 120, 180, 210],
:time => 100:40:300,
)
df = flatten(df, :estimate);
# # Plot generations
# Note how the plots are located at the angles of the `circular_variable`.
plot_circular_topoplots(
df;
positions = pos,
center_label = "Relative angle [°]",
predictor = :circular_variable,
)
# If the bounding variable is not between 0 and 360, since we are using time, we must specify it.
plot_circular_topoplots(
df;
positions = pos,
center_label = "Time [sec]",
predictor = :time,
predictor_bounds = [80, 320],
)
# # Configurations of Circular Topoplots
# ```@docs
# plot_circular_topoplots
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 549 | # # Design matrix
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using DataFrames
using CairoMakie
# Data
include("../../../example_data.jl")
uf = example_data("UnfoldLinearModel");
# # Plot Designmatrices
# The following code will result in the default configuration.
plot_designmatrix(designmatrix(uf))
# To make the design matrix easier to read, you may want to sort it using `sort_data`.
plot_designmatrix(designmatrix(uf); sort_data = true)
# # Configurations for Design matrix plot
# ```@docs
# plot_designmatrix
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4015 | # # [ERP Plot](@id erp_vis)
# **ERP plot** is plot type for visualisation of [Event-related potentials](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3016705/).
# It can fully represent time and experimental condition dimensions using lines.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using DataFrames
using CairoMakie
using DataFramesMeta
using UnfoldSim
using UnfoldMakie
include("../../../example_data.jl");
# Data generation
# Let's generate some data. We'll fit a model with a 2 level categorical predictor and a continuous predictor with interaction.
data, evts = UnfoldSim.predef_eeg(; noiselevel = 12, return_epoched = true)
data = reshape(data, (1, size(data)...))
f = @formula 0 ~ 1 + condition + continuous
se_solver = (x, y) -> Unfold.solver_default(x, y, stderror = true);
m = fit(
UnfoldModel,
Dict(Any => (f, range(0, step = 1 / 100, length = size(data, 2)))),
evts,
data,
solver = se_solver,
)
results = coeftable(m)
res_effects = effects(Dict(:continuous => -5:0.5:5), m);
# ## Figure plotting
plot_erp(results)
# To change legend title use `mapping.color`:
plot_erp(results, mapping = (; color = :coefname => "Conditions"))
# # Additional features
# ## Effect plot
# Effect plot shows how ERP voltage is affected by variation of some variable (here: `:contionous`).
# - `categorical_color::Bool = true`
# Treat `:color` as continuous or categorical variable in case of numeric `:color` column.
# - `categorical_group::Bool = true`
# Treat `:group` as categorical variable by default in case of numeric `:group` column.
plot_erp(
res_effects;
mapping = (; y = :yhat, color = :continuous, group = :continuous),
layout = (; use_colorbar = false),
)
# ## Significance lines
# - `significance::Array = []` - show a significance (see below).
# Here we manually specify p-value lines. If array is not empty, plot shows colored lines under the plot representing the p-values.
# Below is an example in which p-values are given:
m = example_data("UnfoldLinearModel")
results = coeftable(m)
significancevalues = DataFrame(
from = [0.01, 0.2],
to = [0.3, 0.4],
coefname = ["(Intercept)", "condition: face"], # if coefname not specified, line should be black
)
plot_erp(results; :significance => significancevalues)
# ## Error ribbons
# - `stderror`::bool = `false` - add an error ribbon, with lower and upper limits based on the `:stderror` column.
# Display a colored band on the graph to indicate lower and higher estimates based on the standard error.
# For the generalizability of your results, it is always better to include error bands.
f = Figure()
results.coefname =
replace(results.coefname, "condition: face" => "face", "(Intercept)" => "car")
results = filter(row -> row.coefname != "continuous", results)
plot_erp!(
f[1, 1],
results;
axis = (title = "Bad example", titlegap = 12),
:stderror => false,
mapping = (; color = :coefname => "Conditions"),
)
plot_erp!(
f[2, 1],
results;
axis = (title = "Good example", titlegap = 12),
:stderror => true,
mapping = (; color = :coefname => "Conditions"),
)
ax = Axis(f[2, 1], width = Relative(1), height = Relative(1))
xlims!(ax, [-0.04, 1])
ylims!(ax, [-0.04, 1])
hidespines!(ax)
hidedecorations!(ax)
text!(0.98, 0.2, text = "* Confidence\nintervals", align = (:right, :top))
f
# There are two ways to implement it.
# First is using `:stderror = true` after `;`.
results.se_low = results.estimate .- 0.5
results.se_high = results.estimate .+ 0.15
plot_erp(select(results, Not(:stderror)); stderror = true)
# Second way is to specify manually lower and higher borders of the error bands.
# !!! note
# `:stderror` has precedence over `:se_low`/`:se_high`.
# ## Faceting
# Creation of column facets for each channel.
m7 = example_data("7channels")
results7 = coeftable(m7)
plot_erp(results7, mapping = (; col = :channel, group = :channel))
# # Configurations of ERP plot
# ```@docs
# plot_erp
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 777 | # # ERP grid
# **ERP grid** is a plot type for visualisation of Event-related potentials.
# It can fully represent time, channel, and layout (channel locations) dimensions using lines. It can also partially represent condition dimensions.
# Lines are displayed on a grid. The location of each axis represents the location of the electrode.
# This plot type is not as popular because it is too cluttered.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using CairoMakie
using UnfoldSim
include("../../../example_data.jl")
# # Plot ERP grid
data, pos = TopoPlots.example_data()
data = data[:, :, 1]
f = Figure()
plot_erpgrid!(f[1, 1], data, pos; axis = (; xlabel = "s", ylabel = "µV"))
f
# # Configurations for Channel image
# ```@docs
# plot_erpgrid
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2415 | # # ERP image
# **ERP image** is a plot type for visualizing EEG activity for all trials.
# It can fully represent time and trial dimensions using a heatmap.
# Y-axis represents all trials, x-axis represents time, while color represents voltage.
# The ERP image can also be sorted by specific experimental variables, which helps to reveal important correlations.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using CairoMakie
using UnfoldSim
using Statistics
# Data input
include("../../../example_data.jl")
data, evts = UnfoldSim.predef_eeg(; noiselevel = 10, return_epoched = true)
plot_erpimage(data)
# # Plot ERP image
# The following code will result in the default configuration.
# # Sorted ERP image
# Generate the data and specify the necessary sorting parameter.
#=
- `sortvalues::Vector{Int64} = false`
Parameter over which plot will be sorted. Using `sortperm()` of Base Julia.
`sortperm()` computes a permutation of the array's indices that puts the array in sorted order.
=#
dat_e, evts, times = example_data("sort_data")
dat_norm = dat_e[:, :] .- mean(dat_e, dims = 2) # normalisation
plot_erpimage(times, dat_norm; sortvalues = evts.Δlatency)
# To see the effect of sorting and normalization, also check this figure.
f = Figure()
plot_erpimage!(f[1, 1], times, dat_e; axis = (; ylabel = "test"))
plot_erpimage!(
f[2, 1],
times,
dat_e;
sortvalues = evts.Δlatency,
axis = (; ylabel = "test"),
)
plot_erpimage!(f[1, 2], times, dat_norm;)
plot_erpimage!(f[2, 2], times, dat_norm; sortvalues = evts.Δlatency)
f
# # Additional features
# Since ERP images use a `Matrix` as an input, the library does not need any informations about the mapping.
#=
- `erpblur::Number = 10`
Number indicating how much blur is applied to the image.
Gaussian blur of the `ImageFiltering` module is used.
- `meanplot::bool = false`
Indicating whether the plot should add a line plot below the ERP image, showing the mean of the data.
=#
# Example of mean plot
plot_erpimage(
data;
meanplot = true,
colorbar = (label = "Voltage [µV]",),
visual = (colormap = :viridis, colorrange = (-40, 40)),
)
# Example of mean plot and plot of sorted values
plot_erpimage(
times,
dat_e;
sortvalues = evts.Δlatency,
meanplot = true,
show_sortval = true,
)
# # Configurations for ERP image
# ```@docs
# plot_erpimage
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4805 | # # Parallel Coordinates
# **Parallel Coordinates Plot** (PCP) is a plot type used to visualize EEG activity for some channels.
# It can fully represent condition and channel dimensions using lines. It can also partially represent time and trials.
# Each vertical axis represents a voltage level for a channel.
# Each line represents a trial, each colour represents a condition.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using DataFrames
using CairoMakie
# Data generation
include("../../../example_data.jl")
r1, positions = example_data();
r2 = deepcopy(r1)
r2.coefname .= "B" # create a second category
r2.estimate .+= rand(length(r2.estimate)) * 0.1
results_plot = vcat(r1, r2);
nothing #hide
# # Plot PCPs
plot_parallelcoordinates(
subset(results_plot, :channel => x -> x .<= 5);
mapping = (; color = :coefname),
ax_labels = ["FP1", "F3", "F7", "FC3", "C3"],
)
# # Additional features
# ## Normalization
#=
On the first image, there is no normalization and the extremes of all axes are the same and equal to the max and min values across all chanells.
On the second image, there is a `minmax normalization`, so each axis has its own extremes based on the min and max of the data.
Typically, parallel plots are normalized per axis. Whether this makes sense for estimating channel x, we do not know.
=#
f = Figure()
plot_parallelcoordinates(
f[1, 1],
subset(results_plot, :channel => x -> x .< 10);
mapping = (; color = :coefname),
axis = (; title = "normalize = nothing"),
)
plot_parallelcoordinates(
f[2, 1],
subset(results_plot, :channel => x -> x .< 10);
mapping = (; color = :coefname),
normalize = :minmax,
axis = (; title = "normalize = :minmax"),
)
f
# ## Color schemes
# Use only categorical with high contrast between adjacent colors.
# More: [change colormap](https://docs.makie.org/stable/explanations/colors/index.html).
f = Figure()
plot_parallelcoordinates(
f[1, 1],
subset(results_plot, :channel => x -> x .<= 5);
mapping = (; color = :coefname),
visual = (; colormap = :tab10),
axis = (; title = "colormap = tab10"),
)
plot_parallelcoordinates(
f[2, 1],
subset(results_plot, :channel => x -> x .<= 5);
mapping = (; color = :coefname),
visual = (; colormap = :Accent_3),
axis = (; title = "colormap = Accent_3"),
)
f
# ## Labels
# Use `ax_labels` to specify labels for the axes.
plot_parallelcoordinates(
subset(results_plot, :channel => x -> x .< 5);
visual = (; color = :darkblue),
ax_labels = ["Fz", "Cz", "O1", "O2"],
)
# ## Tick labels
# Specify tick labels on axis. There are four different options for the tick labels.
f = Figure(size = (400, 800))
plot_parallelcoordinates(
f[1, 1],
subset(results_plot, :channel => x -> x .< 5, :time => x -> x .< 0);
ax_labels = ["Fz", "Cz", "O1", "O2"],
ax_ticklabels = :all,
normalize = :minmax,
axis = (; title = "ax_ticklabels = :all"),
) # show all ticks on all axes
plot_parallelcoordinates(
f[2, 1],
subset(results_plot, :channel => x -> x .< 5, :time => x -> x .< 0);
ax_labels = ["Fz", "Cz", "O1", "O2"],
ax_ticklabels = :left,
normalize = :minmax,
axis = (; title = "ax_ticklabels = :left"),
) # show all ticks on the left axis, but only extremities on others
plot_parallelcoordinates(
f[3, 1],
subset(results_plot, :channel => x -> x .< 5, :time => x -> x .< 0);
ax_labels = ["Fz", "Cz", "O1", "O2"],
ax_ticklabels = :outmost,
normalize = :minmax,
axis = (; title = "ax_ticklabels = :outmost"),
) # show ticks on extremities of all axes
plot_parallelcoordinates(
f[4, 1],
subset(results_plot, :channel => x -> x .< 5, :time => x -> x .< 0);
ax_labels = ["Fz", "Cz", "O1", "O2"],
ax_ticklabels = :none,
normalize = :minmax,
axis = (; title = "ax_ticklabels = :none"),
) # disable all ticks
f
# ## Bending the parallel plot
# Bending the linescan be helpful to make them more visible.
f = Figure()
plot_parallelcoordinates(
f[1, 1],
subset(results_plot, :channel => x -> x .< 10),
axis = (; title = "bend = false"),
)
plot_parallelcoordinates(
f[2, 1],
subset(results_plot, :channel => x -> x .< 10),
bend = true,
axis = (; title = "bend = true"),
)
f
# ## Transparancy
uf_5chan = example_data("UnfoldLinearModelMultiChannel")
f = Figure()
plot_parallelcoordinates(
f[1, 1],
uf_5chan;
mapping = (; color = :coefname),
visual = (; alpha = 0.1),
axis = (; title = "alpha = 0.1"),
)
plot_parallelcoordinates(
f[2, 1],
uf_5chan,
mapping = (; color = :coefname),
visual = (; alpha = 0.9),
axis = (; title = "alpha = 0.9"),
)
f
# # Configurations of Parallel coordinates plot
# ```@docs
# plot_parallelcoordinates
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 791 | # # [Spline plot](@id spline_vis)
# **Spline plot** is a plot type for visualisation of terms in an UnfoldModel.
# Two subplots are generated for each spline term: 1) the basis function of the spline; 2) the density of the underlying covariate.
# Multiple spline terms are arranged across columns.
# Dashed lines indicate spline knots.
# # Setup
# Package and data loading
using Unfold, UnfoldMakie
using BSplineKit, DataFrames
include("../../../example_data.jl")
df, pos = example_data("TopoPlots.jl")
m1 = example_data("UnfoldLinearModelwith1Spline");
m2 = example_data("UnfoldLinearModelwith2Splines");
# Spline plot with one spline term:
plot_splines(m1)
# Spline plot with two spline terms:
plot_splines(m2)
# # Configurations of Spline plot
# ```@docs
# plot_splines
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3326 | # # [Topoplot](@id topo_vis)
# **Topoplot** (aka topography plot) is a plot type for visualisation of EEG activity in a specific time stemp or time interval.
# It can fully represent channel and channel location dimensions using contour lines.
# The topoplot is a 2D projection and interpolation of the 3D distributed sensor activity. The name stems from physical geography, but instead of height, the contour lines represent voltage levels.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using DataFrames
using CairoMakie
using TopoPlots
using DataFrames
# Data loading
dat, positions = TopoPlots.example_data();
# The size of `data` is 64×400×3. This means:
# - 64 channels;
# - 400 timepoints in range from -0.3 to 0.5 mseconds;
# - Estimates of 3 averaging functions. Instead of displaying the EEG data for all subjects, here we aggregate the data using (1) mean, (2) standard deviation and (3) p-value within t-tests.
# While `position` consist of 64 x and y coordinates of each channels on a scalp.
# # Plot Topoplots
# Here we select a time point in 340 msec and the mean estimate.
plot_topoplot(dat[1:4, 340, 1]; positions = positions[1:4])
df = DataFrame(:estimate => dat[:, 340, 1])
plot_topoplot(df; positions = positions)
# ## Setting sensor positions
#=
The `plot_topoplot()` needs the sensor positions to be specified. There are several ways to do this:
- Specify positions directly: `plot_topoplot(...; positions=[...])`
- Specify the sensor labels: `plot_topoplot(...; labels=[...])`
To get the positions from the labels we use a [database](https://raw.githubusercontent.com/sappelhoff/eeg_positions/main/data/Nz-T10-Iz-T9/standard_1005_2D.tsv).
=#
# # Column Mappings for Topoplots
#=
When using topoplots with a `DataFrame` as input, the library needs to know the names of the columns used for plotting. This is specified using the `mapping=(;)` kwargs.
While there are several default values that will be checked in order if they exist in the `DataFrame`, a custom name may need to be chosen:
Note that only one of `positions` or `labels` needs to be set to draw a topoplot. If both are set, positions takes precedence, labels can be used to label electrodes in TopoPlots.jl.
=#
# The default columns of mapping could be seen usign this code:
configs_default = UnfoldMakie.PlotConfig()
configs_default.mapping.y
# # Labelling
#=
- `label_text` draws labels next to their positions.
Example: `plot_topoplot(...; visual=(; label_text = true))`
- `label_scatter (boolean)` draws the markers at the given positions.
Example: `plot_topoplot(...; visual=(; label_scatter = true))`
=#
f = Figure(size = (500, 500))
labs4 = ["O1", "F2", "F3", "P4"]
plot_topoplot!(
f[1, 1],
dat[1:4, 340, 1];
positions = positions[1:4],
visual = (; label_scatter = false),
labels = labs4,
axis = (; title = "no channel scatter"),
)
plot_topoplot!(
f[1, 2],
dat[1:4, 340, 1];
positions = positions[1:4],
visual = (; label_text = true, label_scatter = (markersize = 15, strokewidth = 2)),
labels = labs4,
axis = (; title = "channel scatter with text"),
mapping = (; labels = labs4),
)
f
# # Highlighting channels
plot_topoplot(dat[:, 50, 1]; positions, high_chan = [1, 2])
# # Configurations of Topoplot
# ```@docs
# plot_topoplot
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4913 | # # Topoplot Series
# **Topoplot series** is a plot type for visualizing EEG activity in a given time frame or time interval.
# It can fully represent channel and channel location dimensions using contour lines. It can also partially represent the time dimension.
# Basically, it is a series of Topoplots.
# # Setup
# Package loading
using Unfold
using UnfoldMakie
using DataFrames
using CairoMakie
using TopoPlots
using Statistics
# Data input
data, positions = TopoPlots.example_data()
df = UnfoldMakie.eeg_array_to_dataframe(data[:, :, 1], string.(1:length(positions)));
nothing #hide
# # Number of topoplots
# There are two ways to specify the number of topoplots in a topoplot series:
# `bin_width` - specify the interval between topoplots
bin_width = 80
plot_topoplotseries(
df;
bin_width,
positions = positions,
axis = (; xlabel = "Time windows [s]"),
)
# `bin_num` - specify the number of topoplots
plot_topoplotseries(
df;
bin_num = 5,
positions = positions,
axis = (; xlabel = "Time windows [s]"),
)
# # Categorical and contionous x-values
# By deafult x-value is `time`, but it could be any contionous (i.g. saccade amplitude) or categorical (any experimental variable) value.
f = Figure()
df_cat = UnfoldMakie.eeg_array_to_dataframe(data[:, 1:5, 1], string.(1:length(positions)))
df_cat.condition = repeat(["A", "B", "C", "D", "E"], size(df_cat, 1) ÷ 5)
plot_topoplotseries!(
f[1, 1],
df_cat;
nrows = 2,
mapping = (; col = :condition),
axis = (; xlabel = "Conditions"),
positions = positions,
)
f
#md # !!! note "Warning"
#md # Version with conditional `mapping.row` is not yet implemented.
#=
To create topoplot series with categorical values:
- Do not specify `bin_width` or `bin_num`.
- Put categorical value in `mapping.col`.
=#
# # Additional features
# ## Adjusting individual topoplots
# By using `topoplot_axes` you can flexibly change configurations of topoplots.
df_adj = UnfoldMakie.eeg_array_to_dataframe(data[:, 1:4, 1], string.(1:length(positions)))
df_adj.condition = repeat(["A", "B", "C", "D"], size(df_adj, 1) ÷ 4)
plot_topoplotseries(
df_adj;
nrows = 2,
positions = positions,
mapping = (; col = :condition),
axis = (; title = "axis title", xlabel = "Conditions"),
topoplot_axes = (;
rightspinevisible = true,
xlabelvisible = false,
title = "single topoplot title",
),
)
# ## Adjusting column gaps
# Using `colgap` in `with_theme` helps to adjust column gaps.
with_theme(colgap = 5) do
plot_topoplotseries(df, bin_num = 5; positions = positions)
end
# However it doesn't work with subsets. Here you need to use `topoplot_axes.limits`.
begin
f = Figure()
plot_topoplotseries!(
f[1, 1],
df,
bin_num = 5;
positions = positions,
topoplot_axes = (; limits = (-0.05, 1.05, -0.1, 1.05)),
)
f
end
# ## Adjusting contours
# Topographic contour is a line drawn on a topographic map to indicate an increase or decrease in voltage.
# A contour level is an area with a specific range of voltage. By default, the number of contour levels is 6, which means that the topography plot is divided into 6 areas depending on their voltage values.
plot_topoplotseries(
df;
bin_width,
positions = positions,
visual = (; enlarge = 0.9, contours = (; linewidth = 1, color = :black)),
)
# ## Aggregating functions
# In this example `combinefun` is specified by `mean`, `median` and `std`.
f = Figure(size = (500, 500))
plot_topoplotseries!(
f[1, 1],
df;
bin_width,
positions = positions,
combinefun = mean,
axis = (; xlabel = "", title = "combinefun = mean"),
)
plot_topoplotseries!(
f[2, 1],
df;
bin_width,
positions = positions,
combinefun = median,
axis = (; xlabel = "", title = "combinefun = median"),
)
plot_topoplotseries!(
f[3, 1],
df;
bin_width,
positions = positions,
combinefun = std,
axis = (; title = "combinefun = std"),
)
f
# ## Multiple rows
# Use `nrows` to specify multiple rows.
f = Figure()
df_col = UnfoldMakie.eeg_array_to_dataframe(data[:, :, 1], string.(1:length(positions)))
plot_topoplotseries!(
f[1, 1:5],
df_col;
bin_num = 14,
nrows = 4,
positions = positions,
visual = (; label_scatter = false),
)
f
# # Configurations of Topoplot series
#=
Also you can:
- Label the x-axis with `axis.xlabel`.
- Hide electrode markers with `visual.label_scatter`.
- Change the color map with `visual.colormap`. The default is `Reverse(:RdBu)`.
- Adjust the limits of the topoplot boxes with `axis.xlim_topo` and `axis.ylim_topo`. By default both are `(-0.25, 0.25)`.
- Adjust the size of the figure with `Figure(size = (x, y))`.
- Adjust the padding between topoplot labels and axis labels using `xlabelpadding` and `ylabelpadding`.
=#
# ```@docs
# plot_topoplotseries
# ```
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 559 | module UnfoldMakiePyMNEExt
using GeometryBasics
using PyMNE
using UnfoldMakie
"""
to_positions(raw::PyMNE.Py; kwargs...)
Generates EEG positions. Calls `make_eeg_layout` from MNE-Python with optional kwargs.
**Return Value:** `Vector{Point2{Float64}`.
"""
function UnfoldMakie.to_positions(raw::PyMNE.Py; kwargs...)
layout_from_raw = PyMNE.channels.make_eeg_layout(raw.info; kwargs...).pos
positions = pyconvert(Array, layout_from_raw)[:, 1:2]
points = map(GeometryBasics.Point{2,Float64}, eachrow(positions))
return points
end
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2394 | module UnfoldMakie
import Makie.get_ticks
using Makie
#using CairoMakie
using AlgebraOfGraphics
using TopoPlots
using GridLayoutBase # for relative_axis
using Unfold
using ImageFiltering
using LinearAlgebra # for PCP
using Statistics
using Colors
using ColorSchemes
using ColorTypes
using DocStringExtensions # for $SIGNATURES
using Interpolations # for parallelplot
using DataStructures
using DataFrames
using SparseArrays
using CategoricalArrays # for cut for TopoPlotSeries
using StaticArrays
using CoordinateTransformations # for 3D positions to 2D
import Makie.hidedecorations!
import Makie.hidespines!
import AlgebraOfGraphics.hidedecorations!
#import AlgebraOfGraphics.hidespines!
# Unfold Backward Compatability. AbstractDesignMatrix was introduced only in v0.7
if isdefined(Unfold, :AbstractDesignMatrix)
# nothing to do for AbstractDesignMatrix, already imprted
# backward compatible accessor
const drop_missing_epochs = Unfold.drop_missing_epochs
const modelmatrices = Unfold.modelmatrices
else
const AbstractDesignMatrix = Unfold.DesignMatrix
const drop_missing_epochs = Unfold.dropMissingEpochs
const modelmatrices = Unfold.get_Xs
end
include("plotconfig.jl")
include("docstring_template.jl")
include("supportive_defaults.jl")
include("eeg_series.jl")
include("plot_topoplotseries.jl")
include("plot_erp.jl")
include("plot_butterfly.jl")
include("plot_designmatrix.jl")
include("plot_splines.jl")
include("plot_topoplot.jl")
include("plot_erpimage.jl")
include("plot_parallelcoordinates.jl")
include("plot_circular_topoplots.jl")
include("plot_erpgrid.jl")
include("plot_channelimage.jl")
include("layout_helper.jl")
include("eeg_positions.jl")
include("topo_color.jl")
include("relative_axis.jl")
export PlotConfig
export plot_designmatrix
export plot_designmatrix!
export plot_splines
export plot_splines!
export plot_erp
export plot_erp!
export plot_erpimage
export plot_erpimage!
export plot_topoplot
export plot_topoplot!
export plot_parallelcoordinates
export plot_butterfly
export plot_butterfly!
export plot_circular_topoplots
export plot_circular_topoplots!
export plot_topoplotseries
export plot_topoplotseries!
export plot_erpgrid
export plot_erpgrid!
export plot_channelimage
export plot_channelimage!
export to_positions
export eeg_array_to_dataframe
export eeg_topoplot_series
export nonnumeric # reexport from AoG
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3074 | function _docstring(cfg_symb::Symbol)
cfg = PlotConfig(cfg_symb)
fn = fieldnames(PlotConfig)
out = ""
visuallink = Dict(
:erp => `Makie.lines`,
:butterfly => `Makie.lines`,
:paracoord => `Makie.lines`,
:erpgrid => `Makie.lines`,
:designmat => `Makie.heatmap`,
:erpimage => `Makie.heatmap`,
:channelimage => `Makie.heatmap`,
:circtopos => `Topoplot.eeg_topoplot`,
:topoplot => `Topoplot.eeg_topoplot`,
:topoplotseries => `Topoplot.eeg_topoplot`,
:splines => `Makie.series`,
)
visuallink2 = Dict(
:erp => "https://docs.makie.org/stable/reference/plots/lines/",
:butterfly => "https://docs.makie.org/stable/reference/plots/lines/",
:paracoord => "https://docs.makie.org/stable/reference/plots/lines/",
:erpgrid => "https://docs.makie.org/stable/reference/plots/lines/",
:designmat => "https://docs.makie.org/stable/reference/plots/heatmap/",
:erpimage => "https://docs.makie.org/stable/reference/plots/heatmap/",
:channelimage => "https://docs.makie.org/stable/reference/plots/heatmap/",
:circtopos => "https://makieorg.github.io/TopoPlots.jl/stable/eeg/",
:topoplot => "https://makieorg.github.io/TopoPlots.jl/stable/eeg/",
:topoplotseries => "https://makieorg.github.io/TopoPlots.jl/stable/eeg/",
:splines => "https://docs.makie.org/stable/reference/plots/series",
)
cbarstring =
(cfg_symb == :erp || cfg_symb == :butterfly) ?
"[`AlgebraOfGraphics.colorbar!`](@ref)" :
"[`Makie.Colorbar`](https://docs.makie.org/stable/reference/blocks/colorbar/)"
link = Dict(
:figure => "use `kwargs...` of [`Makie.Figure`](https://docs.makie.org/stable/explanations/figure/)",
:axis => "use `kwargs...` of [`Makie.Axis`](https://docs.makie.org/stable/reference/blocks/axis/)",
:legend => "use `kwargs...` of [`Makie.Legend`](https://docs.makie.org/stable/reference/blocks/legend/)",
:layout => "check this [page](https://unfoldtoolbox.github.io/UnfoldMakie.jl/dev/generated/how_to/hide_deco/)",
:mapping => "use any mapping from [`AlgebraOfGraphics`](https://aog.makie.org/stable/layers/mapping/)",
:visual => "use `kwargs...` of [$(visuallink[cfg_symb])]($(visuallink2[cfg_symb]))",
:colorbar => "use `kwargs...` of $cbarstring",
)
for k = 1:length(fn)
namedtpl = string(Base.getfield(cfg, fn[k]))
addlink = ""
try
addlink = "- *" * link[fn[k]] * "*"
catch
end
namedtpl = replace(namedtpl, "_" => "\\_")
out = out * "**$(fn[k]) =** $(namedtpl) $addlink \n\n"
end
return """## Shared plot configuration options
The shared plot options can be used as follows: `type = (; key = value, ...))`.\\
For example, `plot_x(...; colorbar = (; vertical = true, label = "Test"))`.\\
Multiple defaults will be cycled until match.
Placing `;` is important!
$(out)
"""
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 14551 | # taken from: https://raw.githubusercontent.com/sappelhoff/eeg_positions/main/data/Nz-T10-Iz-T9/standard_1005_2D.tsv
# license: https://github.com/sappelhoff/eeg_positions/blob/main/LICENSE
standard_1005_2D = Dict(
[
("AF1", (-0.1025, 0.5139))
("AF10", (0.5878, 0.809))
("AF10H", (0.5021, 0.691))
("AF1H", (-0.0512, 0.5105))
("AF2", (0.1025, 0.5139))
("AF2H", (0.0512, 0.5105))
("AF3", (-0.2067, 0.5274))
("AF3H", (-0.1543, 0.5194))
("AF4", (0.2067, 0.5274))
("AF4H", (0.1543, 0.5194))
("AF5", (-0.3143, 0.5513))
("AF5H", (-0.26, 0.5379))
("AF6", (0.3143, 0.5513))
("AF6H", (0.26, 0.5379))
("AF7", (-0.427, 0.5879))
("AF7H", (-0.3699, 0.5678))
("AF8", (0.427, 0.5879))
("AF8H", (0.3699, 0.5678))
("AF9", (-0.5878, 0.809))
("AF9H", (-0.5021, 0.691))
("AFF1", (-0.1207, 0.4195))
("AFF10", (0.7071, 0.7071))
("AFF10H", (0.6039, 0.6039))
("AFF1H", (-0.0602, 0.4155))
("AFF2", (0.1207, 0.4195))
("AFF2H", (0.0602, 0.4155))
("AFF3", (-0.2444, 0.4361))
("AFF3H", (-0.182, 0.4263))
("AFF4", (0.2444, 0.4361))
("AFF4H", (0.182, 0.4263))
("AFF5", (-0.3743, 0.4661))
("AFF5H", (-0.3084, 0.4493))
("AFF6", (0.3743, 0.4661))
("AFF6H", (0.3084, 0.4493))
("AFF7", (-0.5138, 0.5138))
("AFF7H", (-0.4426, 0.4874))
("AFF8", (0.5138, 0.5138))
("AFF8H", (0.4426, 0.4874))
("AFF9", (-0.7071, 0.7071))
("AFF9H", (-0.6039, 0.6039))
("AFFZ", (0, 0.4142))
("AFP1", (-0.0803, 0.6148))
("AFP10", (0.454, 0.891))
("AFP10H", (0.3878, 0.761))
("AFP1H", (-0.0401, 0.6133))
("AFP2", (0.0803, 0.6148))
("AFP2H", (0.0401, 0.6133))
("AFP3", (-0.1615, 0.621))
("AFP3H", (-0.1207, 0.6174))
("AFP4", (0.1615, 0.621))
("AFP4H", (0.1207, 0.6174))
("AFP5", (-0.2443, 0.6317))
("AFP5H", (-0.2027, 0.6258))
("AFP6", (0.2443, 0.6317))
("AFP6H", (0.2027, 0.6258))
("AFP7", (-0.3299, 0.6474))
("AFP7H", (-0.2867, 0.6388))
("AFP8", (0.3299, 0.6474))
("AFP8H", (0.2867, 0.6388))
("AFP9", (-0.454, 0.891))
("AFP9H", (-0.3878, 0.761))
("AFPZ", (0, 0.6128))
("AFZ", (0, 0.5095))
("C1", (-0.1584, 0))
("C1H", (-0.0787, 0))
("C2", (0.1584, 0))
("C2H", (0.0787, 0))
("C3", (-0.3249, 0))
("C3H", (-0.2401, 0))
("C4", (0.3249, 0))
("C4H", (0.2401, 0))
("C5", (-0.5095, 0))
("C5H", (-0.4142, 0))
("C6", (0.5095, 0))
("C6H", (0.4142, 0))
("CCP1", (-0.157, -0.0804))
("CCP1H", (-0.078, -0.0791))
("CCP2", (0.157, -0.0804))
("CCP2H", (0.078, -0.0791))
("CCP3", (-0.3219, -0.0857))
("CCP3H", (-0.2379, -0.0825))
("CCP4", (0.3219, -0.0857))
("CCP4H", (0.2379, -0.0825))
("CCP5", (-0.5042, -0.096))
("CCP5H", (-0.4102, -0.0901))
("CCP6", (0.5042, -0.096))
("CCP6H", (0.4102, -0.0901))
("CCPZ", (0, -0.0787))
("CP1", (-0.1527, -0.1616))
("CP1H", (-0.0759, -0.1591))
("CP2", (0.1527, -0.1616))
("CP2H", (0.0759, -0.1591))
("CP3", (-0.3126, -0.1718))
("CP3H", (-0.2313, -0.1657))
("CP4", (0.3126, -0.1718))
("CP4H", (0.2313, -0.1657))
("CP5", (-0.4881, -0.1912))
("CP5H", (-0.3978, -0.1802))
("CP6", (0.4881, -0.1912))
("CP6H", (0.3978, -0.1802))
("CPP1", (-0.1455, -0.2445))
("CPP1H", (-0.0724, -0.2412))
("CPP2", (0.1455, -0.2445))
("CPP2H", (0.0724, -0.2412))
("CPP3", (-0.2969, -0.2587))
("CPP3H", (-0.22, -0.2503))
("CPP4", (0.2969, -0.2587))
("CPP4H", (0.22, -0.2503))
("CPP5", (-0.4612, -0.2852))
("CPP5H", (-0.377, -0.2702))
("CPP6", (0.4612, -0.2852))
("CPP6H", (0.377, -0.2702))
("CPPZ", (0, -0.2401))
("CPZ", (0, -0.1584))
("CZ", (0, 0))
("F1", (-0.1349, 0.3302))
("F10", (0.809, 0.5878))
("F10H", (0.691, 0.5021))
("F1H", (-0.0672, 0.3262))
("F2", (0.1349, 0.3302))
("F2H", (0.0672, 0.3262))
("F3", (-0.2744, 0.3467))
("F3H", (-0.2038, 0.3369))
("F4", (0.2744, 0.3467))
("F4H", (0.2038, 0.3369))
("F5", (-0.4234, 0.3771))
("F5H", (-0.3474, 0.3599))
("F6", (0.4234, 0.3771))
("F6H", (0.3474, 0.3599))
("F7", (-0.5879, 0.427))
("F7H", (-0.5032, 0.3992))
("F8", (0.5879, 0.427))
("F8H", (0.5032, 0.3992))
("F9", (-0.809, 0.5878))
("F9H", (-0.691, 0.5021))
("FC1", (-0.1527, 0.1616))
("FC1H", (-0.0759, 0.1591))
("FC2", (0.1527, 0.1616))
("FC2H", (0.0759, 0.1591))
("FC3", (-0.3126, 0.1718))
("FC3H", (-0.2313, 0.1657))
("FC4", (0.3126, 0.1718))
("FC4H", (0.2313, 0.1657))
("FC5", (-0.4881, 0.1912))
("FC5H", (-0.3978, 0.1802))
("FC6", (0.4881, 0.1912))
("FC6H", (0.3978, 0.1802))
("FCC1", (-0.157, 0.0804))
("FCC1H", (-0.078, 0.0791))
("FCC2", (0.157, 0.0804))
("FCC2H", (0.078, 0.0791))
("FCC3", (-0.3219, 0.0857))
("FCC3H", (-0.2379, 0.0825))
("FCC4", (0.3219, 0.0857))
("FCC4H", (0.2379, 0.0825))
("FCC5", (-0.5042, 0.096))
("FCC5H", (-0.4102, 0.0901))
("FCC6", (0.5042, 0.096))
("FCC6H", (0.4102, 0.0901))
("FCCZ", (0, 0.0787))
("FCZ", (0, 0.1584))
("FFC1", (-0.1455, 0.2445))
("FFC1H", (-0.0724, 0.2412))
("FFC2", (0.1455, 0.2445))
("FFC2H", (0.0724, 0.2412))
("FFC3", (-0.2969, 0.2587))
("FFC3H", (-0.22, 0.2503))
("FFC4", (0.2969, 0.2587))
("FFC4H", (0.22, 0.2503))
("FFC5", (-0.4612, 0.2852))
("FFC5H", (-0.377, 0.2702))
("FFC6", (0.4612, 0.2852))
("FFC6H", (0.377, 0.2702))
("FFCZ", (0, 0.2401))
("FFT10", (0.891, 0.454))
("FFT10H", (0.761, 0.3878))
("FFT7", (-0.6474, 0.3299))
("FFT7H", (-0.5509, 0.3048))
("FFT8", (0.6474, 0.3299))
("FFT8H", (0.5509, 0.3048))
("FFT9", (-0.891, 0.454))
("FFT9H", (-0.761, 0.3878))
("FT10", (0.9511, 0.309))
("FT10H", (0.8123, 0.2639))
("FT7", (-0.691, 0.2245))
("FT7H", (-0.5852, 0.2057))
("FT8", (0.691, 0.2245))
("FT8H", (0.5852, 0.2057))
("FT9", (-0.9511, 0.309))
("FT9H", (-0.8123, 0.2639))
("FTT10", (0.9877, 0.1564))
("FTT10H", (0.8436, 0.1336))
("FTT7", (-0.7176, 0.1137))
("FTT7H", (-0.6059, 0.1036))
("FTT8", (0.7176, 0.1137))
("FTT8H", (0.6059, 0.1036))
("FTT9", (-0.9877, 0.1564))
("FTT9H", (-0.8436, 0.1336))
("FP1", (-0.2245, 0.691))
("FP1H", (-0.1137, 0.7176))
("FP2", (0.2245, 0.691))
("FP2H", (0.1137, 0.7176))
("FPZ", (0, 0.7266))
("FZ", (0, 0.3249))
("I1", (-0.309, -0.9511))
("I1H", (-0.1564, -0.9877))
("I2", (0.309, -0.9511))
("I2H", (0.1564, -0.9877))
("IZ", (0, -1))
("LPA", (-1, 0))
("N1", (-0.309, 0.9511))
("N1H", (-0.1564, 0.9877))
("N2", (0.309, 0.9511))
("N2H", (0.1564, 0.9877))
("NAS", (0, 1))
("NFP1", (-0.2639, 0.8123))
("NFP1H", (-0.1336, 0.8436))
("NFP2", (0.2639, 0.8123))
("NFP2H", (0.1336, 0.8436))
("NFPZ", (0, 0.8541))
("NZ", (0, 1))
("O1", (-0.2245, -0.691))
("O1H", (-0.1137, -0.7176))
("O2", (0.2245, -0.691))
("O2H", (0.1137, -0.7176))
("OI1", (-0.2639, -0.8123))
("OI1H", (-0.1336, -0.8436))
("OI2", (0.2639, -0.8123))
("OI2H", (0.1336, -0.8436))
("OIZ", (0, -0.8541))
("OZ", (0, -0.7266))
("P1", (-0.1349, -0.3302))
("P10", (0.809, -0.5878))
("P10H", (0.691, -0.5021))
("P1H", (-0.0672, -0.3262))
("P2", (0.1349, -0.3302))
("P2H", (0.0672, -0.3262))
("P3", (-0.2744, -0.3467))
("P3H", (-0.2038, -0.3369))
("P4", (0.2744, -0.3467))
("P4H", (0.2038, -0.3369))
("P5", (-0.4234, -0.3771))
("P5H", (-0.3474, -0.3599))
("P6", (0.4234, -0.3771))
("P6H", (0.3474, -0.3599))
("P7", (-0.5879, -0.427))
("P7H", (-0.5032, -0.3992))
("P8", (0.5879, -0.427))
("P8H", (0.5032, -0.3992))
("P9", (-0.809, -0.5878))
("P9H", (-0.691, -0.5021))
("PO1", (-0.1025, -0.5139))
("PO10", (0.5878, -0.809))
("PO10H", (0.5021, -0.691))
("PO1H", (-0.0512, -0.5105))
("PO2", (0.1025, -0.5139))
("PO2H", (0.0512, -0.5105))
("PO3", (-0.2067, -0.5274))
("PO3H", (-0.1543, -0.5194))
("PO4", (0.2067, -0.5274))
("PO4H", (0.1543, -0.5194))
("PO5", (-0.3143, -0.5513))
("PO5H", (-0.26, -0.5379))
("PO6", (0.3143, -0.5513))
("PO6H", (0.26, -0.5379))
("PO7", (-0.427, -0.5879))
("PO7H", (-0.3699, -0.5678))
("PO8", (0.427, -0.5879))
("PO8H", (0.3699, -0.5678))
("PO9", (-0.5878, -0.809))
("PO9H", (-0.5021, -0.691))
("POO1", (-0.0803, -0.6148))
("POO10", (0.454, -0.891))
("POO10H", (0.3878, -0.761))
("POO1H", (-0.0401, -0.6133))
("POO2", (0.0803, -0.6148))
("POO2H", (0.0401, -0.6133))
("POO3", (-0.1615, -0.621))
("POO3H", (-0.1207, -0.6174))
("POO4", (0.1615, -0.621))
("POO4H", (0.1207, -0.6174))
("POO5", (-0.2443, -0.6317))
("POO5H", (-0.2027, -0.6258))
("POO6", (0.2443, -0.6317))
("POO6H", (0.2027, -0.6258))
("POO7", (-0.3299, -0.6474))
("POO7H", (-0.2867, -0.6388))
("POO8", (0.3299, -0.6474))
("POO8H", (0.2867, -0.6388))
("POO9", (-0.454, -0.891))
("POO9H", (-0.3878, -0.761))
("POOZ", (0, -0.6128))
("POZ", (0, -0.5095))
("PPO1", (-0.1207, -0.4195))
("PPO10", (0.7071, -0.7071))
("PPO10H", (0.6039, -0.6039))
("PPO1H", (-0.0602, -0.4155))
("PPO2", (0.1207, -0.4195))
("PPO2H", (0.0602, -0.4155))
("PPO3", (-0.2444, -0.4361))
("PPO3H", (-0.182, -0.4263))
("PPO4", (0.2444, -0.4361))
("PPO4H", (0.182, -0.4263))
("PPO5", (-0.3743, -0.4661))
("PPO5H", (-0.3084, -0.4493))
("PPO6", (0.3743, -0.4661))
("PPO6H", (0.3084, -0.4493))
("PPO7", (-0.5138, -0.5138))
("PPO7H", (-0.4426, -0.4874))
("PPO8", (0.5138, -0.5138))
("PPO8H", (0.4426, -0.4874))
("PPO9", (-0.7071, -0.7071))
("PPO9H", (-0.6039, -0.6039))
("PPOZ", (0, -0.4142))
("PZ", (0, -0.3249))
("RPA", (1, 0))
("T10", (1, 0))
("T10H", (0.8541, 0))
("T7", (-0.7266, 0))
("T7H", (-0.6128, 0))
("T8", (0.7266, 0))
("T8H", (0.6128, 0))
("T9", (-1, 0))
("T9H", (-0.8541, 0))
("TP10", (0.9511, -0.309))
("TP10H", (0.8123, -0.2639))
("TP7", (-0.691, 0.2245))
("TP7H", (-0.5852, -0.2057))
("TP8", (0.691, -0.2245))
("TP8H", (0.5852, -0.2057))
("TP9", (-0.9511, -0.309))
("TP9H", (-0.8123, -0.2639))
("TPP10", (0.891, -0.454))
("TPP10H", (0.761, -0.3878))
("TPP7", (-0.6474, -0.3299))
("TPP7H", (-0.5509, -0.3048))
("TPP8", (0.6474, -0.3299))
("TPP8H", (0.5509, -0.3048))
("TPP9", (-0.891, -0.454))
("TPP9H", (-0.761, -0.3878))
("TTP10", (0.9877, -0.1564))
("TTP10H", (0.8436, -0.1336))
("TTP7", (-0.7176, -0.1137))
("TTP7H", (-0.6059, -0.1036))
("TTP8", (0.7176, -0.1137))
("TTP8H", (0.6059, -0.1036))
("TTP9", (-0.9877, -0.1564))
("TTP9H", (-0.8436, -0.1336))
],
)
function getLabelPos(label)
l = uppercase(label)
#change value range from [-1,1] to [0,1]
return (standard_1005_2D[l][1] / 2.0 + 0.5, standard_1005_2D[l][2] / 2.0 + 0.5)
end
label_in_channel_order = [
"FP1",
"F3",
"F7",
"FC3",
"C3",
"C5",
"P3",
"P7",
"P9",
"PO7",
"PO3",
"O1",
"Oz",
"Pz",
"CPz",
"FP2",
"Fz",
"F4",
"F8",
"FC4",
"FCz",
"Cz",
"C4",
"C6",
"P4",
"P8",
"P10",
"PO8",
"PO4",
"O2",
"HEOG_left",
"HEOG_right",
"VEOG_lower",
]
function channelToLabel(channel)
return label_in_channel_order[channel]
end
"""
cart3d_to_spherical(x, y, z)
Convert x, y, z electrode positions on a scalp to spherical coordinate representation.
**Return Value:** `Matrix`.
"""
function cart3d_to_spherical(x, y, z)
sph = SphericalFromCartesian().(SVector.(x, y, z))
sph = [vcat(s.r, s.θ, π / 2 - s.ϕ) for s in sph]
sph = hcat(sph...)'
return sph
end
"""
to_positions(x, y, z; sphere = [0, 0, 0.])
to_positions(pos::AbstractMatrix; sphere = [0, 0, 0.])
Projects 3D electrode positions to a 2D layout.
Reimplementation of the MNE algorithm.
Assumes `size(pos) = (3, nChannels)` when input is `AbstractMatrix`.
Tip: You can get positions directly from an MNE object after loading PyMNE and enabling the UnfoldMakie PyMNE extension.
**Return Value:** `Vector{Point2{Float64}}`.
"""
to_positions(pos::AbstractMatrix; kwargs...) =
to_positions(pos[1, :], pos[2, :], pos[3, :]; kwargs...)
function to_positions(x, y, z; sphere = [0, 0, 0.0])
#cart3d_to_spherical(x,y,z)
# translate to sphere origin
x .-= sphere[1]
y .-= sphere[2]
z .-= sphere[3]
# convert to spherical coordinates
sph = cart3d_to_spherical(x, y, z)
# get rid of of the radius for now
pol_a = sph[:, 3]
pol_b = sph[:, 2]
# use only theta & phi, convert back to cartesian coordinates
p_x = pol_a .* cos.(pol_b)
p_y = pol_a .* sin.(pol_b)
# scale by the radius
p_x .*= sph[:, 1] ./ (π / 2)
p_y .*= sph[:, 1] ./ (π / 2)
# move back by the sphere coordinates
p_x .+= sphere[1]
p_y .+= sphere[2]
return Point2f.(p_x, p_y)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 11315 | """
eeg_array_to_dataframe(data::AbstractMatrix, label_aliases::AbstractVector)
eeg_array_to_dataframe(data::AbstractVector, label_aliases::AbstractVector)
eeg_array_to_dataframe(data::Union{AbstractMatrix, AbstractVector{<:Number}})
Helper function converting an array (Matrix or Vector) to a tidy `DataFrame` with columns `:estimate`, `:time` and `:label` (with aliases `:color`, `:group`, `:channel`).
Format of Arrays:\\
- times x condition for plot\\_erp.\\
- channels x time for plot\\_butterfly, plot\\_topoplotseries.\\
- channels for plot\\_topoplot.\\
**Return Value:** `DataFrame`.
"""
eeg_array_to_dataframe(data::Union{AbstractMatrix,AbstractVector{<:Number}}) =
eeg_array_to_dataframe(data, string.(1:size(data, 1)))
eeg_array_to_dataframe(data::AbstractVector, label_aliases::AbstractVector) =
eeg_array_to_dataframe(reshape(data, 1, :), label_aliases)
function eeg_array_to_dataframe(data::AbstractMatrix, label_aliases::AbstractVector)
array_to_df(data, label_aliases) = DataFrame(data', label_aliases)
array_to_df(data::LinearAlgebra.Adjoint{<:Number,<:AbstractVector}, label_aliases) =
DataFrame(collect(data)', label_aliases)
df = array_to_df(data, label_aliases)
df[!, :time] .= 1:nrow(df)
df = stack(df, Not([:time]); variable_name = :label_aliases, value_name = "estimate")
df.color = df.label_aliases
df.group = df.label_aliases
df.channel = df.label_aliases
return df
end
"""
eeg_topoplot_series(data::DataFrame,
f,
data::DataFrame;
bin_width,
bin_num,
y = :erp,
label = :label,
col = :time,
row = nothing,
col_labels = false,
row_labels = false,
rasterize_heatmaps = true,
combinefun = mean,
xlim_topo,
ylim_topo,
topoplot_attributes...,
)
eeg_topoplot_series!(fig, data::DataFrame, bin_width; kwargs..)
Plot a series of topoplots.
The function takes the `combinefun = mean` over the `:time` column of `data` in `bin_width` steps.
- `f` \\
Figure object. \\
- `data::DataFrame`\\
Needs the columns `:time` and `y(=:erp)`, and `label(=:label)`. \\
If `data` is a matrix, it is automatically cast to a dataframe, time bins are in samples, labels are `string.(1:size(data,1))`.
- `col`, `row = :time` \\
Specify the field to be divided into columns and rows. The default is `col = :time` to split by the time field and `row = nothing`. \\
Useful to split by a condition, e.g. `...(..., col = :time, row = :condition)` would result in multiple (as many as different values in `df.condition`) rows of topoplot series.
- `row_labels`, `col_labels = false` \\
Indicate whether there should be labels in the plots in the first column to indicate the row value and in the last row to indicate the time (typically timerange).
- `combinefun::Function = mean`\\
Specify how the samples within `bin_width` are summarised.\\
Example functions: `mean`, `median`, `std`.
**Return Value:** `Tuple{Figure, Vector{Any}}`.
"""
function eeg_topoplot_series(
data::Union{<:Observable,<:DataFrame,<:AbstractMatrix};
figure = NamedTuple(),
kwargs...,
)
return eeg_topoplot_series!(Figure(; figure...), data; kwargs...)
end
#eeg_topoplot_series(data::Union{<:Observable,<:DataFrame,<:AbstractMatrix}; kwargs...) =
# eeg_topoplot_series(data; kwargs...)
# AbstractMatrix
function eeg_topoplot_series!(
fig,
data::Union{<:Observable,<:DataFrame,<:AbstractMatrix};
kwargs...,
)
return eeg_topoplot_series!(fig, data, string.(1:size(data, 1)); kwargs...)
end
# convert a 2D Matrix to the dataframe
function eeg_topoplot_series(
data::Union{<:Observable,<:DataFrame,<:AbstractMatrix},
labels;
kwargs...,
)
return eeg_topoplot_series(eeg_array_to_dataframe(data, labels); kwargs...)
end
function eeg_topoplot_series!(
fig,
data::Union{<:Observable,<:DataFrame,<:AbstractMatrix},
labels;
kwargs...,
)
return eeg_topoplot_series!(fig, eeg_array_to_dataframe(data, labels); kwargs...)
end
function eeg_topoplot_series!(
fig,
data::Union{<:Observable{<:DataFrame},<:DataFrame};
cat_or_cont_columns = "cont",
y = :erp,
label = :label,
col = :time,
row = nothing,
col_labels = false,
row_labels = false,
rasterize_heatmaps = true,
combinefun = mean,
topoplot_axes = (;),
interactive_scatter = nothing,
highlight_scatter = false,
topoplot_attributes...,
)
axis_options = create_axis_options()
axis_options = merge(axis_options, topoplot_axes)
# aggregate the data over time bins
# using same colormap + contour levels for all plots
data = _as_observable(data)
select_col = isnothing(col) ? 1 : unique(to_value(data)[:, :col_coord])
select_row = isnothing(row) ? 1 : unique(to_value(data)[:, :row_coord])
if eltype(to_value(data)[!, col]) <: Number
data_mean = @lift(
data_binning(
$data;
col_y = y,
fun = combinefun,
grouping = [label, :col_coord, :row_coord],
)
)
else
# categorical detected, no binning necessary
data_mean = data
end
(q_min, q_max) = extract_colorrange(to_value(data_mean), y)
topoplot_attributes = merge(
(
colorrange = (q_min, q_max),
interp_resolution = (128, 128),
#contours = (; levels = range(q_min, q_max; length = 7)),
),
topoplot_attributes,
)
# do the col/row plot
axlist = []
if interactive_scatter != nothing
@assert isa(interactive_scatter, Observable)
end
for r = 1:length(select_row)
for c = 1:length(select_col)
ax = Axis(fig[:, :][r, c]; axis_options...)
df_single =
topoplot_subselection(data_mean, col, row, select_col, select_row, r, c)
# select labels
labels = to_value(df_single)[:, label]
# select data
single_y = @lift($df_single[:, y])
topoplot_attributes = scatter_management(
single_y,
topoplot_attributes,
highlight_scatter,
interactive_scatter,
)
if isempty(to_value(single_y))
break
end
single_topoplot = eeg_topoplot!(ax, single_y, labels; topoplot_attributes...)
if rasterize_heatmaps
single_topoplot.plots[1].plots[1].rasterize = true
end
label_management(ax, cat_or_cont_columns, df_single, col) # to put column and row labels
interactive_toposeries(interactive_scatter, single_topoplot, r, c)
push!(axlist, ax)
end
end
if typeof(fig) != GridLayout && typeof(fig) != GridLayoutBase.GridSubposition
colgap!(fig.layout, 0)
end
return fig, axlist, topoplot_attributes[:colorrange]
end
function label_management(ax, cat_or_cont_columns, df_single, col)
if cat_or_cont_columns == "cat"
ax.xlabel = string(to_value(df_single)[1, col])
else
tmp_labels = to_value(df_single).cont_cuts[1, :][]
ax.xlabel = string(tmp_labels)
end
end
function topoplot_subselection(data_mean, col, row, select_col, select_row, r, c)
sel = 1 .== ones(size(to_value(data_mean), 1))
if !isnothing(col)
sel = sel .&& (to_value(data_mean)[:, :col_coord] .== select_col[c]) # subselect
end
if !isnothing(row)
sel = sel .&& (to_value(data_mean)[:, :row_coord] .== select_row[r]) # subselect
end
df_single = @lift($data_mean[sel, :])
return df_single
end
function scatter_management(
single_y,
topoplot_attributes,
highlight_scatter,
interactive_scatter,
)
if highlight_scatter != false || interactive_scatter != nothing
strokecolor = Observable(repeat([:black], length(to_value(single_y))))
highlight_feature = (; strokecolor = strokecolor)
if :label_scatter ∈ keys(topoplot_attributes)
topoplot_attributes = merge(
topoplot_attributes,
(;
label_scatter = if isa(topoplot_attributes[:label_scatter], NamedTuple)
merge(topoplot_attributes[:label_scatter], highlight_feature)
else
highlight_feature
end
),
)
else
topoplot_attributes =
merge(topoplot_attributes, (; label_scatter = highlight_feature))
end
end
return topoplot_attributes
end
function interactive_toposeries(interactive_scatter, single_topoplot, r, c)
if interactive_scatter != nothing
@assert isa(interactive_scatter, Observable)
end
if interactive_scatter != false
on(events(single_topoplot).mousebutton) do event
if event.button == Mouse.left && event.action == Mouse.press
plt, p = pick(single_topoplot)
if isa(plt, Makie.Scatter) && plt == single_topoplot.plots[1].plots[3]
plt.strokecolor[] .= :black
plt.strokecolor[][p] = :white
notify(plt.strokecolor) # not sure why this is necessary, but oh well..
interactive_scatter[] = (r, c, p)
end
end
end
end
end
function create_axis_options()
return (
aspect = 1,
title = "",
xgridvisible = false,
xminorgridvisible = false,
xminorticksvisible = false,
xticksvisible = false,
xticklabelsvisible = false,
xlabelvisible = true,
ygridvisible = false,
yminorgridvisible = false,
yminorticksvisible = false,
yticksvisible = false,
yticklabelsvisible = false,
ylabelvisible = false,
leftspinevisible = false,
rightspinevisible = false,
topspinevisible = false,
bottomspinevisible = false,
xpanlock = true,
ypanlock = true,
xzoomlock = true,
yzoomlock = true,
xrectzoom = false,
yrectzoom = false,
#limits = (xlim_topo, ylim_topo),
)
end
"""
data_binning(df, bin_width; col_y = :erp, fun = mean, grouping = [])
Group `DataFrame` according to topoplot coordinates and apply aggregation function.
Arguments:
- `df::AbstractTable`\\
Requires columns `:cont_cuts`, `col_y` (default `:erp`), and all columns in `grouping` (`col_coord`, `row_coord`, `label`);
- `col_y = :erp` \\
The column to combine over (with `fun`);
- `fun = mean()`\\
Function to combine.
- `grouping = []`\\
Vector of symbols or strings, columns to group by the data before aggregation. Values of `nothing` are ignored.
**Return Value:** `DataFrame`.
"""
function data_binning(df; col_y = :erp, fun = mean, grouping = [])
df = deepcopy(df) # cut seems to change stuff inplace
grouping = grouping[.!isnothing.(grouping)]
df_grouped = groupby(df, unique([:cont_cuts, grouping...]))
df_combined = combine(df_grouped, col_y => fun)
rename!(df_combined, names(df_combined)[end] => col_y) # renames estimate_fun to estimate
return df_combined
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 998 | function dropnames(namedtuple::NamedTuple, names::Tuple{Vararg{Symbol}})
keepnames = Base.diff_names(Base._nt_names(namedtuple), names)
return NamedTuple{keepnames}(namedtuple)
end
function apply_layout_settings!(
config::PlotConfig;
fig = nothing,
hm = nothing,
drawing = nothing,
ax = nothing,
plot_area = (1, 1),
)
if isnothing(ax)
ax = current_axis()
end
if :hidespines ∈ keys(config.layout) && !isnothing(config.layout.hidespines)
Makie.hidespines!(ax, config.layout.hidespines...)
end
if :hidedecorations ∈ keys(config.layout) && !isnothing(config.layout.hidedecorations)
hidedecorations!(ax; config.layout.hidedecorations...)
end
end
Makie.hidedecorations!(ax::Matrix{AxisEntries}; kwargs...) =
Makie.hidedecorations!.(ax; kwargs...)
Makie.hidespines!(ax::Matrix{AxisEntries}, args...) = Makie.hidespines!.(ax, args...)
Makie.hidespines!(ax::AxisEntries, args...) = Makie.hidespines!.(ax.axis, args...)
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 7176 | using DataFrames
using TopoPlots
using LinearAlgebra
"""
plot_butterfly(plot_data::Union{DataFrame, AbstractMatrix}; kwargs...)
plot_butterfly(times::Vector, plot_data::Union{DataFrame, AbstractMatrix}; kwargs...)
plot_butterfly!(f::Union{GridPosition, GridLayout, Figure}, plot_data::Union{DataFrame, AbstractMatrix}; kwargs...)
Plot a Butterfly plot.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{DataFrame, AbstractMatrix}`\\
Data for the ERP plot visualization.
- `kwargs...`\\
Additional styling behavior. \\
Often used as: `plot_butterfly(df; visual = (; colormap = :romaO))`.
## Keyword arguments (kwargs)
- `positions::Array = []` \\
Adds a topoplot as an inset legend to the provided channel positions. Must be the same length as `plot_data`.
To change the colors of the channel lines use the `topoposition_to_color` function.
- `topolegend::Bool = true`\\
Show an inlay topoplot with corresponding electrodes. Requires `positions`.
- `topomarkersize::Real = 10` \\
Change the size of the electrode markers in topoplot.
- `topopositions_to_color::x -> pos_to_color_RomaO(x)`\\
Change the line colors.
- `topo_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of the topoplot axis.\\
To see all options just type `?Axis` in REPL.\\
Defaults: $(supportive_defaults(:topo_default))
- `mapping = (;)`\\
For highlighting specific channels.\\
Example: `mapping = (; color = :highlight))`, where `:highlight` is variable with appopriate mapping.
**Return Value:** `Figure` displaying Butterfly plot.
$(_docstring(:butterfly))
see also [`plot_erp`](@ref erp_vis)
"""
plot_butterfly(plot_data::Union{<:AbstractDataFrame,AbstractMatrix}; kwargs...) =
plot_butterfly!(Figure(), plot_data; kwargs...)
function plot_butterfly!(
f::Union{GridPosition,GridLayout,<:Figure},
plot_data::Union{<:AbstractDataFrame,AbstractMatrix};
positions = nothing,
labels = nothing,
topolegend = true,
topomarkersize = 10,
topopositions_to_color = x -> pos_to_color_RomaO(x),
topo_axis = (;),
mapping = (;),
kwargs...,
)
config = PlotConfig(:butterfly)
config_kwargs!(config; mapping, kwargs...)
plot_data = deepcopy(plot_data) # to avoid change of data in REPL
if isa(plot_data, AbstractMatrix{<:Real})
plot_data = eeg_array_to_dataframe(plot_data)
config_kwargs!(config; axis = (; xlabel = "Time [samples]"))
end
# resolve columns with data
config.mapping = resolve_mappings(plot_data, config.mapping)
#remove mapping values with `nothing`
deleteKeys(nt::NamedTuple{names}, keys) where {names} =
NamedTuple{filter(x -> x ∉ keys, names)}(nt)
config.mapping = deleteKeys(
config.mapping,
keys(config.mapping)[findall(isnothing.(values(config.mapping)))],
)
# turn "nothing" from group columns into :fixef
if "group" ∈ names(plot_data)
plot_data.group = plot_data.group .|> a -> isnothing(a) ? :fixef : a
end
if isnothing(positions) && isnothing(labels)
topolegend = false
colors = nothing
else
all_positions = get_topo_positions(; positions = positions, labels = labels)
if (config.visual.colormap !== nothing)
colors = config.visual.colormap
un = length(unique(plot_data[:, config.mapping.color]))
colors = cgrad(config.visual.colormap, un, categorical = true)
else
colors = get_topo_color(all_positions, topopositions_to_color)
end
end
# Categorical mapping
# convert color column into string to prevent wrong grouping
if (:group ∈ keys(config.mapping))
config.mapping =
merge(config.mapping, (; group = config.mapping.group => nonnumeric))
end
if (:color ∈ keys(config.mapping))
config.mapping =
merge(config.mapping, (; color = config.mapping.color => nonnumeric))
end
if (
:col ∈ keys(config.mapping) &&
typeof(plot_data[:, config.mapping.col]) == Vector{Int64}
)
config.mapping = merge(config.mapping, (; col = config.mapping.col => nonnumeric))
end
mapp = AlgebraOfGraphics.mapping()
for i in [:color, :group]
if (i ∈ keys(config.mapping))
tmp = getindex(config.mapping, i)
mapp = mapp * AlgebraOfGraphics.mapping(; i => tmp)
end
end
# remove x / y
mapping_others = deleteKeys(config.mapping, [:x, :y, :positions, :lables])
xy_mapp =
AlgebraOfGraphics.mapping(config.mapping.x, config.mapping.y; mapping_others...)
basic = visual(Lines; config.visual...) * xy_mapp
basic = basic * data(plot_data)
plot_equation = basic * mapp
f_grid = f[1, 1]
if (topolegend)
topo_axis = update_axis(supportive_defaults(:topo_default); topo_axis...)
ix = unique(i -> plot_data[:, config.mapping.group[1]][i], 1:size(plot_data, 1))
topoplot_legend(
Axis(f_grid; topo_axis...),
topomarkersize,
plot_data[ix, config.mapping.color[1]],
colors,
all_positions,
)
end
if isnothing(colors)
drawing = draw!(f_grid, plot_equation; axis = config.axis)
else
drawing = draw!(
f_grid,
plot_equation,
scales(Color = (; palette = colors));
axis = config.axis,
)
end
apply_layout_settings!(config; fig = f, ax = drawing, drawing = drawing)
return f
end
# topopositions_to_color = colors?
function topoplot_legend(axis, topomarkersize, unique_val, colors, all_positions)
all_positions = unique(all_positions)
topo_matrix = eeg_head_matrix(all_positions, (0.5, 0.5), 0.5)
un = unique(unique_val)
special_colors =
ColorScheme(vcat(RGB(1, 1, 1.0), colors[map(x -> findfirst(x .== un), unique_val)]))
xlims!(low = -0.2, high = 1.2)
ylims!(low = -0.2, high = 1.2)
topoplot = eeg_topoplot!(
axis,
1:length(all_positions), # go from 1:npos
string.(1:length(all_positions));
positions = all_positions,
interpolation = NullInterpolator(), # inteprolator that returns only 0, which is put to white in the special_colorsmap
colorrange = (0, length(all_positions)), # add the 0 for the white-first color
colormap = special_colors,
head = (color = :black, linewidth = 1, model = topo_matrix),
label_scatter = (markersize = topomarkersize, strokewidth = 0.5),
)
hidespines!(axis)
hidedecorations!(axis)
return topoplot
end
function eeg_head_matrix(positions, center, radius)
oldCenter = mean(positions)
oldRadius, _ = findmax(x -> norm(x .- oldCenter), positions)
radF = radius / oldRadius
return Makie.Mat4f(
radF,
0,
0,
0,
0,
radF,
0,
0,
0,
0,
1,
0,
center[1] - oldCenter[1] * radF,
center[2] - oldCenter[2] * radF,
0,
1,
)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3544 | """
plot_channelimage!(f::Union{GridPosition, GridLayout, Figure}, data::Union{DataFrame,AbstractMatrix}, positions::Vector{Point{2,Float32}}, ch_names::Vector{String}; kwargs...)
plot_channelimage(data::Union{DataFrame, AbstractMatrix}, positions::Vector{Point{2,Float32}}, ch_names::Vector{String}; kwargs...)
Plot a Channel image
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{DataFrame, AbstractMatrix}`\\
DataFrame or Matrix with data.\\
Data should has a format of 1 row - 1 channel.
- `positions::Vector{Point{2,Float32}}`\\
A vector with EEG layout coordinates.
- `ch_names::Vector{String}`\\
Vector with channel names.
- `times::Vector = range(-0.3, 1.2, length = size(data, 2))`\\
Time range on x-axis.
- `sorting_variables::Vector = [:y, :x]`\\
Method to sort channels on y-axis.\\
For instance, you can sort by channel positions on the scalp (x, y) or channel name.
- `sorting_reverse::Vector = [:false, :false]`\\
Should sorting variables be reversed or not?
$(_docstring(:channelimage))
**Return Value:** `Figure` displaying the Channel image.
"""
plot_channelimage(
data::Union{DataFrame,AbstractMatrix},
position::Vector{Point{2,Float32}},
ch_names::Vector{String};
kwargs...,
) = plot_channelimage!(Figure(), data, position, ch_names; kwargs...)
function plot_channelimage!(
f::Union{GridPosition,GridLayout,Figure},
data::Union{DataFrame,AbstractMatrix},
positions::Vector{Point{2,Float32}},
ch_names::Vector{String};
times = range(-0.3, 1.2, length = size(data, 2)),
sorting_variables = [:y, :x],
sorting_reverse = [:false, :false],
kwargs...,
)
config = PlotConfig(:channelimage)
config_kwargs!(config; kwargs...)
if length(positions) != length(ch_names)
error(
"Length of positions and channel names are not equal: $(length(positions)) and $(length(ch_names))",
)
end
if size(data, 1) != length(positions)
error(
"Number of data rows and positions length are not equal: $(size(data, 1)) and $(length(positions))",
)
end
if length(sorting_variables) != length(sorting_reverse)
error(
"Length of sorting_variables and sorting_reverse are not equal: $(length(sorting_variables)) and $(length(sorting_reverse))",
)
end
x = [i[1] for i in positions]
y = [i[2] for i in positions]
sorted_data =
DataFrame(:x => x, :y => y, :ch_names => ch_names, :index => 1:length(ch_names))
sort!(sorted_data, sorting_variables, rev = sorting_reverse)
sorted_names = sorted_data[!, :ch_names]
sorted_names = [string(x) for x in sorted_names]
sorted_indecies = sorted_data[!, :index]
if typeof(data) == DataFrame
data = Matrix(data)
end
iz = mean(data, dims = 3)[sorted_indecies, :, 1]' #how it could be 3 dimensions if my data is 2D?
gl = f[1, 1] = GridLayout()
ax = Axis(
gl[1, 1],
xlabel = config.axis.xlabel,
ylabel = config.axis.ylabel,
yticks = 1:length(ch_names),
ytickformat = xc -> sorted_names,
yticklabelsize = config.axis.yticklabelsize,
)
hm = Makie.heatmap!(times, 1:length(ch_names), iz, colormap = config.visual.colormap)
Makie.Colorbar(
gl[1, 2],
hm,
label = config.colorbar.label,
labelrotation = config.colorbar.labelrotation,
)
return f
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 8675 | """
plot_circular_topoplots!(f, data::DataFrame; kwargs...)
plot_circular_topoplots(data::DataFrame; kwargs...)
Plot a circular EEG topoplot.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.\\
- `data::DataFrame`\\
DataFrame with data keys (columns `:y, :yhat, :estimate`), and :position (columns `:pos, :position, :positions`).
## Keyword arguments (kwargs)
- `predictor::Vector{Any} = :predictor`\\
The circular predictor value, defines position of topoplot across the circle.
Mapped around `predictor_bounds`.
- `predictor_bounds::Vector{Int64} = [0, 360]`\\
The bounds of the predictor. Relevant for the axis labels.
- `positions::Vector{Point{2, Float32}} = nothing`\\
Positions of the [`plot_topoplot`](@ref topo_vis).
- `center_label::String = ""`\\
The text in the center of the cricle.
- `plot_radius::String = 0.8`\\
The radius of the circular topoplot series plot calucalted by formula: `radius = (minwidth * plot_radius) / 2`.
- `labels::Vector{String} = nothing`\\
Labels for the [`plot_topoplots`](@ref topo_vis).
$(_docstring(:circtopos))
**Return Value:** `Figure` displaying the Circular topoplot series.
"""
plot_circular_topoplots(data::DataFrame; kwargs...) =
plot_circular_topoplots!(Figure(), data; kwargs...)
plot_circular_topoplots!(f, data::DataFrame; kwargs...) =
plot_circular_topoplots!(f, data; kwargs...)
function plot_circular_topoplots!(
f::Union{GridPosition,GridLayout,Figure},
data::DataFrame;
predictor = :predictor,
predictor_bounds = [0, 360],
positions = nothing,
labels = nothing,
center_label = "",
plot_radius = 0.8,
kwargs...,
)
config = PlotConfig(:circtopos)
config_kwargs!(config; kwargs...)
config.mapping = resolve_mappings(data, config.mapping)
positions = get_topo_positions(; positions = positions, labels = labels)
# moving the values of the predictor to a different array to perform boolean queries on them
predictor_values = data[:, predictor]
if (length(predictor_bounds) != 2)
error("predictor_bounds needs exactly two values")
end
if (predictor_bounds[1] >= predictor_bounds[2])
error("predictor_bounds[1] needs to be smaller than predictor_bounds[2]")
end
if (
(length(predictor_values[predictor_values.<predictor_bounds[1]]) != 0) ||
(length(predictor_values[predictor_values.>predictor_bounds[2]]) != 0)
)
error(
"all values in the data's effect column have to be within the predictor_bounds range",
)
end
if (all(predictor_values .<= 2 * pi))
@warn "insert the predictor values in degrees instead of radian, or change predictor_bounds"
end
ax = Axis(f[1, 1]; aspect = 1)
hidedecorations!(ax)
hidespines!(ax)
plot_circular_axis!(ax, predictor_bounds, center_label)
limits!(ax, -3.5, 3.5, -3.5, 3.5)
min, max = calculate_global_max_values(data[:, config.mapping.y], predictor_values)
# setting the colorbar to the bottom right of the box.
# Relative values got determined by checking what subjectively looks best
Colorbar(
f[1, 2];
colorrange = (min, max),
config.colorbar...,
height = @lift Fixed($(pixelarea(ax.scene)).widths[2])
)
plot_topo_plots!(
f[1, 1],
data[:, config.mapping.y],
positions,
predictor_values,
predictor_bounds,
min,
max,
labels,
plot_radius,
)
apply_layout_settings!(config; ax = ax)
# set the scene's background color according to config
#set_theme!(Theme(backgroundcolor = config.axisData.backgroundcolor))
return f
end
function calculate_global_max_values(data, predictor)
x = combine(
groupby(DataFrame(:e => data, :p => predictor), :p),
:e => (x -> maximum(abs.(quantile!(x, [0.01, 0.99])))) => :local_max_val,
)
global_max_val = maximum(x.local_max_val)
return (-global_max_val, global_max_val)
end
function plot_circular_axis!(ax, predictor_bounds, center_label)
# The axis position is always the middle of the screen
# It uses the GridLayout's full size
lines!(
ax,
1 * cos.(LinRange(0, 2 * pi, 500)),
1 * sin.(LinRange(0, 2 * pi, 500)),
color = (:black, 0.5),
linewidth = 3,
)
# labels and label lines for the circle
circlepoints_lines =
[(1.1 * cos(a), 1.1 * sin(a)) for a in LinRange(0, 2pi, 5)[1:end-1]]
circlepoints_labels =
[(1.3 * cos(a), 1.3 * sin(a)) for a in LinRange(0, 2pi, 5)[1:end-1]]
text!(
circlepoints_lines,
# using underscores as lines around the circular axis
text = ["_", "_", "_", "_"],
rotation = LinRange(0, 2pi, 5)[1:end-1],
align = (:right, :baseline),
#textsize = round(minsize*0.03)
)
text!(
circlepoints_labels,
text = calculate_axis_labels(predictor_bounds),
align = (:center, :center),
#textsize = round(minsize*0.03)
)
text!(ax, 0, 0, text = center_label, align = (:center, :center)) #,textsize = round(minsize*0.04))
end
# four labels around the circle, middle values are the 0.25, 0.5, and 0.75 quantiles
function calculate_axis_labels(predictor_bounds)
nonboundlabels = quantile(predictor_bounds, [0.25, 0.5, 0.75])
# third label is on the left and it tends to cover the circle
# so added some blank spaces to tackle that
if typeof(predictor_bounds[1]) == Float64
res = [
string(trunc(predictor_bounds[1], digits = 1)),
string(trunc(nonboundlabels[1], digits = 1)),
string(trunc(nonboundlabels[2], digits = 1)),
string(trunc(nonboundlabels[3], digits = 1)),
]
else
res = [
string(trunc(Int, predictor_bounds[1])),
string(trunc(Int, nonboundlabels[1])),
string(trunc(Int, nonboundlabels[2]), " "),
string(trunc(Int, nonboundlabels[3])),
]
end
return res
end
function plot_topo_plots!(
f,
data,
positions,
predictor_values,
predictor_bounds,
globalmin,
globalmax,
labels,
plot_radius,
)
df = DataFrame(:e => data, :p => predictor_values)
gp = groupby(df, :p)
i = 0
for g in gp
i += 1
bbox = calculate_BBox([0, 0], [1, 1], g.p[1], predictor_bounds, plot_radius)
eeg_axis = Axis(
f, # this creates an axis at the same grid location of the current axis
aspect = 1,
width = Relative(0.2), # size of bboxes
height = Relative(0.2), # size of bboxes
halign = bbox.origin[1] + bbox.widths[1] / 2, # coordinates
valign = bbox.origin[2] + bbox.widths[2] / 2,
#backgroundcolor = nothing,
)
if !isnothing(labels)
eeg_axis.xlabel = labels[i]
end
TopoPlots.eeg_topoplot!(
eeg_axis,
g.e;
positions = positions,
colorrange = (globalmin, globalmax),
enlarge = 1,
)
hidedecorations!(eeg_axis, label = false)
hidespines!(eeg_axis)
end
end
function calculate_BBox(origin, widths, predictor_value, bounds, plot_radius)
minwidth = minimum(widths)
predictor_ratio = (predictor_value - bounds[1]) / (bounds[2] - bounds[1])
radius = (minwidth * plot_radius) / 2 # radius of the position circle of a circular topoplot
size_of_BBox = minwidth / 5
# the middle point of the circle for the topoplot positions
# has to be moved a bit into the direction of the longer axis
# to be centered on a scene that's not shaped like a square.
res_shift = [
((origin[1] + widths[1]) - widths[1]) / 2,
((origin[2] + widths[2]) - widths[2]) / 2,
]
res_shift[res_shift.<0] .= 0
x = radius * cos(predictor_ratio * 2 * pi) + res_shift[1]
y = radius * sin(predictor_ratio * 2 * pi) + res_shift[2]
# notice that the bbox defines the bottom left and the top
# right point of the axis. This means that you have to
# move the bbox to the bottom left by size_of_bbox/2 to move
# the center of the axis to a point.
if abs(y) < 1
y = round(y, digits = 2)
end
return BBox(
(origin[1] + widths[1]) / 2 - size_of_BBox / 2 + x,
(origin[1] + widths[1]) / 2 + size_of_BBox - size_of_BBox / 2 + x,
(origin[2] + widths[2]) / 2 - size_of_BBox / 2 + y,
(origin[2] + widths[2]) / 2 + size_of_BBox - size_of_BBox / 2 + y,
)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4931 | """
plot_designmatrix!(f::Union{GridPosition, GridLayout, Figure}, data::Unfold.DesignMatrix; kwargs...)
plot_designmatrix(data::Unfold.DesignMatrix; kwargs...)
Plot a designmatrix.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Unfold.DesignMatrix`\\
Data for the plot visualization.
## Keyword arguments (kwargs)
- `standardize_data::Bool = true`\\
Indicates whether the data is standardized by pointwise division of the data with its sampled standard deviation.
- `sort_data::Bool = true`\\
Indicates whether the data is sorted. It uses `sortslices()` of Base Julia.
- `xticks::Num = nothing`\\
Returns the number of labels on the x axis.
- `xticks` = 0: no labels are placed.
- `xticks` = 1: first possible label is placed.
- `xticks` = 2: first and last possible labels are placed.
- 2 < `xticks` < `number of labels`: equally distribute the labels.
- `xticks` ≥ `number of labels`: all labels are placed.
$(_docstring(:designmat))
**Return Value:** `Figure` displaying the Design matrix.
"""
plot_designmatrix(
data::Union{<:Vector{<:AbstractDesignMatrix},<:AbstractDesignMatrix};
kwargs...,
) = plot_designmatrix!(Figure(), data; kwargs...)
function plot_designmatrix!(f, data::Vector{<:AbstractDesignMatrix}; kwargs...)
if length(data) > 1
@warn "multiple $(length(data)) designmatrices found, plotting the first one"
end
plot_designmatrix!(f, data[1]; kwargs...)
end
function plot_designmatrix!(
f::Union{GridPosition,GridLayout,Figure},
data::AbstractDesignMatrix;
xticks = nothing,
sort_data = false,
standardize_data = false,
kwargs...,
)
config = PlotConfig(:designmat)
config_kwargs!(config; kwargs...)
designmat = UnfoldMakie.modelmatrix(data)
if standardize_data
designmat = designmat ./ std(designmat, dims = 1)
designmat[isinf.(designmat)] .= 1.0
end
if isa(designmat, SparseMatrixCSC)
if sort_data
@warn "Sorting does not make sense for time-expanded designmatrices. sort_data has been set to `false`"
sort_data = false
end
designmat = Matrix(designmat[end÷2-2000:end÷2+2000, :]) # needs a size(designmat) of at least 4000 x Any
end
if sort_data
designmat = Base.sortslices(designmat, dims = 1)
end
labels0 = replace.(Unfold.get_coefnames(data), r"\s*:" => ":")
if length(split(labels0[1], ": ")) > 1
labels = map(x -> join(split(x, ": ")[3]), labels0)
labels_top1 = Unfold.extract_coef_info(Unfold.get_coefnames(data), 2)
unique_names = String[]
labels_top2 = String[""]
for el in labels_top1
if !in(el, unique_names)
push!(unique_names, el)
push!(labels_top2, el)
else
push!(labels_top2, "")
end
end
end
lLength = length(labels0)
# only change xticks if we want less then all
if (xticks !== nothing && xticks < lLength)
@assert(xticks >= 0, "xticks shouldn't be negative")
# sections between xticks
section_size = (lLength - 2) / (xticks - 1)
new_labels = []
# first tick. Empty if 0 ticks
if xticks >= 1
push!(new_labels, labels0[1])
else
push!(new_labels, "")
end
# fill in ticks in the middle
for i = 1:(lLength-2)
# checks if we're at the end of a section, but NO tick on the very last section
if i % section_size < 1 && i < ((xticks - 1) * section_size)
push!(new_labels, labels0[i+1])
else
push!(new_labels, "")
end
end
# last tick at the end
if xticks >= 2
push!(new_labels, labels0[lLength-1])
else
push!(new_labels, "")
end
labels0 = new_labels
end
if length(split(labels0[1], ": ")) > 1
ax2 = Axis(
f[1, 1],
xticklabelcolor = :red,
xaxisposition = :top;
xticks = (1:length(labels_top2), labels_top2),
)
hidespines!(ax2)
hidexdecorations!(ax2, ticklabels = false, ticks = false)
hm = heatmap!(ax2, designmat'; config.visual...)
else
labels = labels0
end
# plot Designmatrix
config.axis = merge(config.axis, (; xticks = (1:length(labels), labels)))
ax = Axis(f[1, 1]; config.axis...)
hm = heatmap!(ax, designmat'; config.visual...)
if isa(designmat, SparseMatrixCSC)
ax.yreversed = true
end
apply_layout_settings!(config; fig = f, hm = hm)
return f
end
# Unfold.extract_coef_info.(Unfold.get_coefnames.(designmatrix(td)),3)
# use it!
# vcat(Unfold.extract_coef_info.(Unfold.get_coefnames.(designmatrix(td)),3)...)
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 7148 | using DataFrames
using TopoPlots
using LinearAlgebra
"""
plot_erp!(f::Union{GridPosition, GridLayout, Figure}, plot_data::Union{DataFrame, AbstractMatrix, AbstractVector{<:Number}}; kwargs...)
plot_erp(times, plot_data::Union{DataFrame, AbstractMatrix, AbstractVector{<:Number}}; kwargs...)
Plot an ERP plot.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{Union{DataFrame, AbstractMatrix, AbstractVector{<:Number}, Vector{Float32}}`\\
Data for the ERP plot visualization.
- `kwargs...`\\
Additional styling behavior. \\
Often used as: `plot_erp(df; mapping = (; color = :coefname, col = :conditionA))`.
## Keyword arguments (kwargs)
- `stderror::Bool = false`\\
Add an error ribbon, with lower and upper limits based on the `:stderror` column.
- `significance::DataFrame = nothing`\\
Show significant time periods as horizontal bars.\\
Example: `DataFrame(from = [0.1, 0.3], to = [0.5, 0.7], coefname = ["(Intercept)", "condition: face"])`.\\
If `coefname` is not specified, the significance lines will be black.
- `layout.use_colorbar = true`\\
Enable or disable colorbar.\\
- `layout.use_legend = true`\\
Enable or disable legend.\\
- `layout.show_legend = true`\\
Enable or disable legend and colorbar.\\
$(_docstring(:erp))
**Return Value:** `Figure` displaying the ERP plot.
"""
plot_erp(plot_data::Union{DataFrame,AbstractMatrix,AbstractVector{<:Number}}; kwargs...) =
plot_erp!(Figure(), plot_data; kwargs...)
plot_erp(
times,
plot_data::Union{DataFrame,AbstractMatrix,AbstractVector{<:Number}};
kwargs...,
) = plot_erp(plot_data; axis = (; xticks = times), kwargs...)
function plot_erp!(
f::Union{GridPosition,GridLayout,Figure},
plot_data::Union{DataFrame,AbstractMatrix,AbstractVector{<:Number}};
positions = nothing,
labels = nothing,
categorical_color = nothing,
categorical_group = nothing,
stderror = false, # XXX if it exists, should be plotted
significance = nothing,
mapping = (;),
kwargs...,
)
if !(isnothing(categorical_color) && isnothing(categorical_group))
@warn "categorical_color and categorical_group have been deprecated.
To switch to categorical colors, please use `mapping(..., color = :mycolorcolum => nonnumeric)`.
`group` is now automatically cast to nonnumeric."
end
config = PlotConfig(:erp)
config_kwargs!(config; mapping, kwargs...)
plot_data = deepcopy(plot_data)
if isa(plot_data, Union{AbstractMatrix{<:Real},AbstractVector{<:Number}})
plot_data = eeg_array_to_dataframe(plot_data')
config_kwargs!(config; axis = (; xlabel = "Time [samples]"))
end
# resolve columns with data
config.mapping = resolve_mappings(plot_data, config.mapping)
#remove mapping values with `nothing`
deleteKeys(nt::NamedTuple{names}, keys) where {names} =
NamedTuple{filter(x -> x ∉ keys, names)}(nt)
config.mapping = deleteKeys(
config.mapping,
keys(config.mapping)[findall(isnothing.(values(config.mapping)))],
)
# turn "nothing" from group columns into :fixef
if "group" ∈ names(plot_data)
plot_data.group = plot_data.group .|> a -> isnothing(a) ? :fixef : a
end
# automatically convert col & group to nonnumeric
if (
:col ∈ keys(config.mapping) &&
!isa(config.mapping.col, Pair) &&
typeof(plot_data[:, config.mapping.col]) <: AbstractVector{<:Number}
)
config.mapping = merge(config.mapping, (; col = config.mapping.col => nonnumeric))
end
if (
:group ∈ keys(config.mapping) &&
!isa(config.mapping.group, Pair) &&
typeof(plot_data[:, config.mapping.group]) <: AbstractVector{<:Number}
)
config.mapping =
merge(config.mapping, (; group = config.mapping.group => nonnumeric))
end
# check if stderror values exist and create new columns with high and low band
if "stderror" ∈ names(plot_data) && stderror
plot_data.stderror = plot_data.stderror .|> a -> isnothing(a) ? 0.0 : a
plot_data[!, :se_low] = plot_data[:, config.mapping.y] .- plot_data.stderror
plot_data[!, :se_high] = plot_data[:, config.mapping.y] .+ plot_data.stderror
end
mapp = AlgebraOfGraphics.mapping()
# mapping for stderrors
for i in [:color, :group, :col, :row, :layout]
if (i ∈ keys(config.mapping))
tmp = getindex(config.mapping, i)
mapp = mapp * AlgebraOfGraphics.mapping(; i => tmp)
end
end
# remove x / y
mapping_others = deleteKeys(config.mapping, [:x, :y, :positions, :lables])
xy_mapp =
AlgebraOfGraphics.mapping(config.mapping.x, config.mapping.y; mapping_others...)
basic = visual(Lines; config.visual...) * xy_mapp
# add band of sdterrors
if stderror
m_se = AlgebraOfGraphics.mapping(config.mapping.x, :se_low, :se_high)
basic = basic + visual(Band, alpha = 0.5) * m_se
end
basic = basic * data(plot_data)
# add the p-values
if !isnothing(significance)
basic = basic + add_significance(plot_data, significance, config)
end
plot_equation = basic * mapp
f_grid = f[1, 1] = GridLayout()
drawing = draw!(f_grid, plot_equation; axis = config.axis)
if config.layout.show_legend == true
config_kwargs!(config; mapping, layout = (; show_legend = false))
if config.layout.use_legend == true
legend!(f_grid[:, end+1], drawing; config.legend...)
end
if config.layout.use_colorbar == true
colorbar!(f_grid[:, end+1], drawing; config.colorbar...)
end
end
apply_layout_settings!(config; fig = f, ax = drawing, drawing = drawing)
return f
end
function add_significance(plot_data, significance, config)
p = deepcopy(significance)
# for now, add them to the fixed effect
if "group" ∉ names(p)
# group not specified using first
if "group" ∈ names(plot_data)
p[!, :group] .= plot_data[1, :group]
if length(unique(plot_data.group)) > 1
@warn "multiple groups found, choosing first one"
end
else
p[!, :group] .= 1
end
end
if :color ∈ keys(config.mapping)
c = config.mapping.color isa Pair ? config.mapping.color[1] : config.mapping.color
un = unique(p[!, c])
p[!, :sigindex] .= [findfirst(un .== x) for x in p.coefname]
else
p[!, :signindex] .= 1
end
# define an index to dodge the lines vertically
scaleY = [minimum(plot_data.estimate), maximum(plot_data.estimate)]
stepY = scaleY[2] - scaleY[1]
posY = stepY * -0.05 + scaleY[1]
Δt = diff(plot_data.time[1:2])[1]
Δy = 0.01
p[!, :segments] = [
Makie.Rect(
Makie.Vec(x, posY + stepY * (Δy * (n - 1))),
Makie.Vec(y - x + Δt, 0.5 * Δy * stepY),
) for (x, y, n) in zip(p.from, p.to, p.sigindex)
]
res = data(p) * mapping(:segments) * visual(Poly)
return (res)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 5568 | """
plot_erpgrid(data::Union{Matrix{<:Real}, DataFrame}, positions::Vector; kwargs...)
plot_erpgrid!(f::Union{GridPosition, GridLayout, Figure}, data::Union{Matrix{<:Real}, DataFrame}, positions::Vector, ch_names::Vector{String}; kwargs...)
Plot an ERP image.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{Matrix{<:Real}, DataFrame}`\\
Data for the plot visualization.\\
Data should has a format of 1 row - 1 channel.
- `positions::Vector{Point{2,Float}}` \\
Electrode positions.
- `ch_names::Vector{String}`\\
Vector with channel names.
- `hlines_grid_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of the hlines on all subaxes.\\
To see all options just type `?hlines` in REPL.\\
Defaults: $(supportive_defaults(:hlines_grid_default))
- `vlines_grid_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of the vlines on all subaxes.\\
To see all options just type `?vlines` in REPL.\\
Defaults: $(supportive_defaults(:vlines_grid_default))
- `lines_grid_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of the lines on all subaxes.\\
To see all options just type `?lines` in REPL.\\
Defaults: $(supportive_defaults(:lines_grid_default))
- `labels_grid_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of the labels on all subaxes.\\
To see all options just type `?text` in REPL.\\
Defaults: $(supportive_defaults(:labels_grid_default))
## Keyword arguments (kwargs)
- `drawlabels::Bool = false`\\
Draw channels labels over each waveform.
- `times::Vector = 1:size(data, 2)`\\
Vector of `size()`.
$(_docstring(:erpgrid))
**Return Value:** `Figure` displaying ERP grid.
"""
plot_erpgrid(
data::Union{Matrix{<:Real},DataFrame},
positions::Vector,
ch_names::Vector{String};
kwargs...,
) = plot_erpgrid!(Figure(), data, positions, ch_names; kwargs...)
plot_erpgrid!(
f::Union{GridPosition,GridLayout,Figure},
data::Union{Matrix{<:Real},DataFrame},
positions;
kwargs...,
) = plot_erpgrid!(f, data, positions, string.(1:length(positions)); kwargs...)
plot_erpgrid(data::Union{Matrix{<:Real},DataFrame}, positions; kwargs...) =
plot_erpgrid!(Figure(), data, positions, string.(1:length(positions)); kwargs...)
function plot_erpgrid!(
f::Union{GridPosition,GridLayout,Figure},
data::Union{Matrix{<:Real},DataFrame},
positions::Vector,
ch_names::Vector{String};
drawlabels = false,
times = -1:size(data, 2)-2, #arbitrary
labels_grid_axis = (;),
hlines_grid_axis = (;),
vlines_grid_axis = (;),
lines_grid_axis = (;),
kwargs...,
)
config = PlotConfig(:erpgrid)
config_kwargs!(config; kwargs...)
if typeof(data) == DataFrame #maybe better would be put it into signature?
data = Matrix(data)
end
if length(positions) != length(ch_names)
error(
"Length of positions and channel names are not equal: $(length(positions)) and $(length(ch_names))",
)
end
if size(data, 1) != length(positions)
error(
"Number of data rows and positions length are not equal: $(size(data, 1)) and $(length(positions))",
)
end
positions = hcat([[p[1], p[2]] for p in positions]...)
minmaxrange = (maximum(positions, dims = 2) - minimum(positions, dims = 2)) #should be different for x and y
positions = (positions .- mean(positions, dims = 2)) ./ minmaxrange .+ 0.5
axlist = []
rel_zeropoint = argmin(abs.(times)) ./ length(times)
labels_grid_axis =
update_axis(supportive_defaults(:labels_grid_default); labels_grid_axis...)
for (ix, p) in enumerate(eachcol(positions))
x = p[1]
y = p[2]
ax = Axis(
f[1, 1],
width = Relative(0.2),
height = Relative(0.2),
halign = x,
valign = y,
)
if drawlabels
text!(ax, rel_zeropoint + 0.1, 1; text = ch_names[ix], labels_grid_axis...)
end
# todo: add label if not nothing
push!(axlist, ax)
end
hlines_grid_axis =
update_axis(supportive_defaults(:hlines_grid_default); hlines_grid_axis...)
vlines_grid_axis =
update_axis(supportive_defaults(:vlines_grid_default); vlines_grid_axis...)
lines_grid_axis =
update_axis(supportive_defaults(:lines_grid_default); lines_grid_axis...)
hlines!.(axlist, Ref([0.0]); hlines_grid_axis...)
vlines!.(axlist, Ref([0.0]); vlines_grid_axis...)
times = isnothing(times) ? (1:size(data, 2)) : times
# todo: add customizable kwargs
h = lines!.(axlist, Ref(times), eachrow(data); lines_grid_axis...)
linkaxes!(axlist...)
hidedecorations!.(axlist)
hidespines!.(axlist)
ax2 = Axis(f[1, 1], width = Relative(1.05), height = Relative(1.05))
hidespines!(ax2)
hidedecorations!(ax2, label = false)
xlims!(ax2, config.axis.xlim)
ylims!(ax2, config.axis.ylim)
xstart = [Point2f(0), Point2f(0)]
xdir = [Vec2f(0, 0.1), Vec2f(0.1, 0)]
arrows!(xstart, xdir, arrowsize = 10)
text!(
0.02,
0,
text = config.axis.xlabel,
fontsize = config.axis.fontsize,
align = (:left, :top),
)
text!(
-0.008,
0.01,
text = config.axis.ylabel,
fontsize = config.axis.fontsize,
align = (:left, :baseline),
rotation = π / 2,
)
f
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 7968 | """
plot_erpimage!(f::Union{GridPosition, GridLayout, Figure}, data::AbstractMatrix{Float64}; kwargs...)
plot_erpimage!(f::Union{GridPosition, GridLayout, Figure}, data::Observable{<:AbstractMatrix}; kwargs...)
plot_erpimage!(f::Union{GridPosition, GridLayout, Figure}, times::Observable{<:AbstractVector}, data::Observable{<:AbstractMatrix{<:Real}}; kwargs...)
plot_erpimage(times::AbstractVector, data::Union{<:Observable{Matrix{<:Real}}, Matrix{<:Real}}; kwargs...)
plot_erpimage(data::Matrix{Float64}; kwargs...)
Plot an ERP image.
## Arguments:
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{DataFrame, Vector{Float32}}`\\
Data for the plot visualization.
## Keyword arguments (kwargs)
- `erpblur::Number = 10`\\
Number indicating how much blur is applied to the image. \\
Gaussian blur of the `ImageFiltering` module is used.\\
Non-Positive values deactivate the blur.
- `sortvalues::Vector{Int64} = false`\\
Parameter over which plot will be sorted. Using `sortperm()` of Base Julia.\\
`sortperm()` computes a permutation of the array's indices that puts the array in sorted order.
- `sortindex::Vector{Int64} = nothing`\\
Sorting over index values.
- `meanplot::bool = false`\\
Add a line plot below the ERP image, showing the mean of the data.
- `show_sortval::bool = false`\\
Add a plot on the right from ERP image, showing the distribution of the sorting data.
- `sortval_xlabel::String = "Sorting variable"`\\
If `show_sortval = true` controls xlabel.
- `axis.ylabel::String = "Trials"`\\
If `sortvalues = true` the default text will change to "Sorted trials", but it could be changed to any values specified manually.
- `meanplot_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of meanplot.\\
To see all options just type `?Axis` in REPL.\\
Defaults: $(supportive_defaults(:meanplot_default))
- `sortplot_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of meanplot.\\
To see all options just type `?Axis` in REPL.\\
Defaults: $(supportive_defaults(:sortplot_default))
$(_docstring(:erpimage))
**Return Value:** `Figure` displaying the ERP image.
"""
plot_erpimage(data; kwargs...) = plot_erpimage!(Figure(), data; kwargs...)
plot_erpimage(
times::AbstractVector,
data::Union{<:Observable{Matrix{<:Real}},AbstractMatrix{<:Real}};
kwargs...,
) = plot_erpimage!(Figure(), times, data; kwargs...)
plot_erpimage!(f::Union{GridPosition,GridLayout,Figure}, args...; kwargs...) =
plot_erpimage!(f, map(_as_observable, args)...; kwargs...)
plot_erpimage!(
f::Union{GridPosition,GridLayout,Figure},
data::Observable{<:AbstractMatrix};
kwargs...,
) = plot_erpimage!(f, @lift(1:size($data, 1)), data; kwargs...)
_as_observable(x) = Observable(x)
_as_observable(x::Observable) = x
function plot_erpimage!(
f::Union{GridPosition,GridLayout,Figure},
times::Observable{<:AbstractVector},
data::Observable{<:AbstractMatrix{<:Real}};
sortvalues = Observable(nothing),
sortindex = Observable(nothing),
erpblur = Observable(10),
meanplot = false,
show_sortval = false,
sortval_xlabel = Observable("Sorting variable"),
meanplot_axis = (;),
sortplot_axis = (;),
kwargs..., # not observables for a while ;)
)
ga = f[1, 1:2] = GridLayout()
sortvalues = _as_observable(sortvalues)
sortindex = _as_observable(sortindex)
erpblur = _as_observable(erpblur)
config = PlotConfig(:erpimage)
if isnothing(sortindex) && !isnothing(sortvalues)
config_kwargs!(config; axis = (; ylabel = "Trials sorted"))
end
config_kwargs!(config; kwargs...)
!isnothing(to_value(sortindex)) ? @assert(to_value(sortindex) isa Vector{Int}) : ""
ax = Axis(ga[1:4, 1:4]; config.axis...)
ax.yticks = [
1,
size(to_value(data), 2) ÷ 4,
size(to_value(data), 2) ÷ 2,
size(to_value(data), 2) - (size(to_value(data), 2) ÷ 4),
size(to_value(data), 2),
]
ax.yticklabelsvisible = true
sortindex = sortindex_managment(sortindex, sortvalues, data)
filtered_data = @lift(
UnfoldMakie.imfilter(
$data[:, $sortindex],
UnfoldMakie.Kernel.gaussian((0, max($erpblur, 0))),
)
)
yvals = @lift(1:size($filtered_data, 2))
hm = heatmap!(ax, times, yvals, filtered_data; config.visual...)
if meanplot
ei_meanplot(ax, data, config, f, ga, times, meanplot_axis)
end
if show_sortval
ei_sortvalue(sortvalues, f, ax, hm, config, sortval_xlabel, sortplot_axis)
elseif config.layout.use_colorbar != false
Colorbar(
ga[1:4, 5],
hm,
label = config.colorbar.label,
labelrotation = config.colorbar.labelrotation,
)
end
hidespines!(ax, :r, :t)
apply_layout_settings!(config; fig = f, hm = hm, ax = ax, plot_area = (4, 1))
return f
end
function ei_meanplot(ax, data, config, f, ga, times, meanplot_axis)
ax.xlabelvisible = false #padding of the main plot
ax.xticklabelsvisible = false
trace = @lift(mean($data, dims = 2)[:, 1])
meanplot_axis = update_axis(supportive_defaults(:meanplot_default); meanplot_axis...)
axbottom = Axis(
ga[5, 1:4];
ylabel = config.colorbar.label === nothing ? "" : config.colorbar.label,
limits = @lift((
minimum($times),
maximum($times),
minimum($trace) - 0.5,
maximum($trace) + 0.5,
)),
meanplot_axis...,
)
rowgap!(ga, 7)
hidespines!(axbottom, :r, :t)
lines!(axbottom, times, trace)
apply_layout_settings!(config; fig = f, ax = axbottom)
end
function ei_sortvalue(sortvalues, f, ax, hm, config, sortval_xlabel, sortplot_axis)
if isnothing(to_value(sortvalues))
error("`show_sortval` needs non-empty `sortvalues` argument")
end
if all(isnan, to_value(sortvalues))
error("`show_sortval` can not take `sortvalues` with all NaN-values")
end
gb = f[1, 3] = GridLayout()
sortplot_axis = update_axis(supportive_defaults(:sortplot_default); sortplot_axis...)
axleft = Axis(
gb[1:4, 1:5];
xlabel = sortval_xlabel,
#xautolimitmargin = (-1, 1),
#yautolimitmargin = (1, 100),
xticks = @lift([
round(minimum($sortvalues), digits = 2),
round(maximum($sortvalues), digits = 2),
]),
limits = @lift((
minimum($sortvalues) - (maximum($sortvalues) / 100 * 3),
maximum($sortvalues) + (maximum($sortvalues) / 100 * 3),
0 - (length($sortvalues) / 100 * 3),
length($sortvalues) + (length($sortvalues) / 100 * 3), #they should be realtive
)),
sortplot_axis...,
)
ys = @lift(1:length($sortvalues))
xs = @lift(sort($sortvalues))
axempty = Axis(gb[5, 1])
hidedecorations!(axempty)
hidespines!(axempty)
hidespines!(axleft, :r, :t)
lines!(axleft, xs, ys)
if config.layout.use_colorbar != false
Colorbar(
gb[1:4, 6],
hm,
label = config.colorbar.label,
labelrotation = config.colorbar.labelrotation,
)
end
apply_layout_settings!(config; fig = f, ax = axleft)
end
function sortindex_managment(sortindex, sortvalues, data)
if isnothing(to_value(sortindex))
if isnothing(to_value(sortvalues))
sortindex = @lift(1:size($data, 2))
else
if length(to_value(sortvalues)) != size(to_value(data), 2)
error(
"The length of sortvalues differs from the length of data trials. This leads to incorrect sorting.",
)
else
sortindex = @lift(sortperm($sortvalues))
end
end
end
return sortindex
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 11304 |
"""
plot_parallelcoordinates(data::Union{DataFrame, AbstractMatrix}; kwargs...)
plot_parallelcoordinates!(f::Union{GridPosition, GridLayout, Figure}, data::Union{DataFrame, AbstractMatrix}; kwargs)
Plot a PCP (parallel coordinates plot).\\
Dimensions: conditions, channels, time, trials.
## Arguments:
- `f::Union{GridPosition, GridLayout, Figure}`
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{DataFrame, AbstractMatrix}`\\
Data for the plot visualization.
## Keyword arguments (kwargs)
- `normalize::Symbol = nothing`\\
If `:minmax`, normalize each axis to their respective min-max range.
- `ax_labels::Vector{String} = nothing`\\
Specify axis labels. \\
Should be a vector of labels with length equal to the number of unique `mapping.x` values.\\
Example: `ax_labels = ["Fz", "Cz", "O1", "O2"]`.
- `ax_ticklabels::Symbol = :outmost`\\
Specify tick labels on axis.
- `:all` - show all labels on all axes.
- `:left` - show all labels on the left axis, but only min and max on others.
- `:outmost` - show labels on min and max of all other axes.
- `:none` - remove all labels.
- `bend::Bool = false`\\
Change straight lines between the axes to curved ("bent") lines using spline interpolation.\\
Note: While this makes the plot look cool, it is not generally recommended to bent the lines, as interpretation
suffers, and the resulting visualizations can be potentially missleading.
- `visual.alpha::Number = 0.5`\\
Change of line transparency.
## Defining the axes
- `mapping.x = :channel, mapping.y = :estimate`.\\
Overwrite what should be on the x and the y axes.
- `mapping.color = :colorcolumn` \\
Split conditions by color. The default color is `:black`.
$(_docstring(:paracoord))
**Return Value:** `Figure` displaying the Parallel coordinates plot.
"""
plot_parallelcoordinates(data::Union{DataFrame,AbstractMatrix}; kwargs...) =
plot_parallelcoordinates(Figure(), data; kwargs...)
function plot_parallelcoordinates(
f,
data::Union{DataFrame,AbstractMatrix};
ax_ticklabels = :outmost,
ax_labels = nothing,
normalize = nothing,
bend = false,
kwargs...,
)
if isa(data, AbstractMatrix{<:Real})
data = eeg_array_to_dataframe(data)
end
config = PlotConfig(:paracoord)
UnfoldMakie.config_kwargs!(config; kwargs...)
config.mapping = UnfoldMakie.resolve_mappings(data, config.mapping)
# remove all unspecified columns
d = select(data, config.mapping...)
# stack the data to a matrix-like (still list of list of lists!)
d2 = unstack(
d,
Not(config.mapping.x, config.mapping.y),
config.mapping.x,
config.mapping.y,
combine = copy,
)
# remove the non x/y columns, we want a matrix at the end
rm_col =
filter(x -> x != config.mapping.x && x != config.mapping.y, [config.mapping...])
d3 = select(d2, Not(rm_col))
# give use list of matrix
d4 = reduce.(hcat, eachrow(Array(d3)))
# give us a single matrix
d5 = reduce(vcat, d4)'
# figure out the color vector
if :color ∈ keys(config.mapping)
c_split = map((c, n) -> repeat([c], n), d2[:, config.mapping.color], size.(d4, 1))
c = vcat(c_split...)
line_labels = string.(c)
else
c = config.visual.color
line_labels = nothing
if config.layout.show_legend
@warn "Disable legend because there was no color choice"
UnfoldMakie.config_kwargs!(config; layout = (; show_legend = false))
end
end
UnfoldMakie.config_kwargs!(config; visual = (; color = c))
f1, ax, axlist, hlines = parallelcoordinates(
f,
d5;
normalize = normalize,
color = c,
bend = bend,
line_labels = line_labels,
ax_labels = ax_labels,
ax_ticklabels = ax_ticklabels,
config.visual...,
)
Label(
f[1, 1, Top()],
text = config.axis.title,
padding = (20, 20, 22, 0),
fontsize = 20,
font = :bold,
)
if config.layout.show_legend
Legend(f[1, 2], ax, config.legend.title; config.legend...)
end
apply_layout_settings!(config; fig = f1, ax = ax)
return isa(f, Figure) ? Makie.FigureAxisPlot(f, [ax, axlist], hlines[1]) :
Makie.AxisPlot([ax, axlist], hlines[1])
end
function parallelcoordinates(
f::Union{<:Figure,<:GridPosition,<:GridLayout},
data::AbstractMatrix;
color = nothing,
line_labels = nothing,
colormap = Makie.wong_colors(),
ax_labels = nothing,
ax_ticklabels = :outmost, # :all, :left,:none
normalize = :minmax,
alpha = 0.3,
bend = false,
)
@assert size(data, 2) > 1 "Currently, for parallel plotting to work, more than one line must be plotted"
if isa(color, AbstractVector)
@assert size(data, 2) == length(color)
end
x_pos = 1:size(data, 1)
ax = Axis(f[1, 1])
scene = ax.parent.scene
ax_labels = isnothing(ax_labels) ? string.(1:size(data, 1)) : ax_labels
# normalize the data?
minlist = minimum.(eachrow((data)))
maxlist = maximum.(eachrow((data)))
if normalize == :minmax
function norm_minmax(x, min, max)
return (x .- min) ./ (max - min)
end
plotdata = deepcopy(data)
for (mi, ma, r) in zip(minlist, maxlist, eachrow(plotdata))
r .= norm_minmax(r, mi, ma)
end
else
plotdata = data
minlist = minimum(plotdata)
maxlist = maximum(plotdata)
end
# edge bending / bundling
if !bend
x_plotdata = x_pos
plotdata_int = plotdata
else
x_plotdata = range(1, x_pos[end], step = 0.05)
plotdata_int = Array{Float64}(undef, length(x_plotdata), size(plotdata, 2))
for k = 1:size(plotdata, 2)
itp = Interpolations.interpolate(
plotdata[:, k],
BSpline(Cubic(Interpolations.Line(OnGrid()))),
)
plotdata_int[:, k] = itp.(x_plotdata)
end
end
# color
crange = [1, 2] # default
if isnothing(color)
color = 1
elseif isa(color, AbstractVector)
if isa(color[1], String)
# categorical colors
un_c = unique(color)
color_ix = [findfirst(un_c .== c) for c in color]
if length(un_c) == 1
@warn "Only single unique value found in the specified color vector."
color = cgrad(colormap, 2)[color_ix] # color gradient
else
color = cgrad(colormap, length(un_c))[color_ix]
end
else
# continuous color
crange = [minimum(color), maximum(color)]
end
end
# plot the lines - this way it will be easy to curve them too
hlines = []
for (ix, r) in enumerate(eachcol(plotdata_int))
h = lines!(
ax,
x_plotdata,
r;
alpha = alpha,
color = isa(color, AbstractVector) ? color[ix] : color,
colormap = colormap,
colorrange = crange,
label = isa(line_labels, AbstractVector) ? line_labels[ix] : line_labels,
)
append!(hlines, [h])
end
# put the right limits + hide the data axes
xlims!(ax, 1, size(data, 1))
hidespines!(ax)
hidedecorations!(ax)
# get some defaults - necessary for LinkAxis
def = Makie.default_attribute_values(Axis, nothing)
axesOptions = (;
spinecolor = :black,
spinevisible = true,
labelfont = def[:ylabelfont],
labelrotation = def[:ylabelrotation],
labelvisible = false,
ticklabelfont = def[:yticklabelfont],
ticklabelsize = def[:yticklabelsize],
ticklabelalign = (:right, :center),
minorticks = def[:yminorticks],
)
# generate the overlay parallel axes
axlist = Makie.LineAxis[]
for i in eachindex(x_pos)
# link them to the parent axes size
axis_endpoints = lift(ax.scene.viewport) do area
center(x_pos[i], x_pos[end], area)
end
if isa(minlist, AbstractArray)
limits = [minlist[i], maxlist[i]]
else
limits = [minlist, maxlist]
end
tickformater = Makie.automatic # default
if ax_ticklabels == :outmost || (i != 1 && ax_ticklabels == :left)
tickformater = surpress_inner_labels
end
if ax_ticklabels == :none
tickformater = x -> repeat([""], length(x))
end
ax_pcp = Makie.LineAxis(
scene;
limits = limits,
dim_convert = Makie.NoDimConversion(),
ticks = PCPTicks(),
endpoints = axis_endpoints,
tickformat = tickformater,
axesOptions...,
)
pcp_title!(
scene,
ax_pcp.attributes.endpoints,
ax_labels[i];
titlegap = def[:titlegap],
)
append!(axlist, [ax_pcp])
end
# add some space to the left and top
pro = ax.layoutobservables.protrusions[]
ax.layoutobservables.protrusions[] = GridLayoutBase.RectSides(
(axlist[1].protrusion[]),
pro.right,
pro.bottom,
pro.top + def[:titlegap],
)
if normalize == :minmax
ylims!(ax, 0, 1)
else
ylims!(ax, minimum(minlist), maximum(maxlist))
end
return f, ax, axlist, hlines
end
function surpress_inner_labels(val)
lbl = Makie.Showoff.showoff(val)
if length(lbl) > 2
lbl[2:end-1] .= ""
end
return lbl
end
function center(x_pos, x_max, area)
r = Rect2f(area)
x = range(r.origin[1], r.origin[1] + r.widths[1], length = x_max)[x_pos]
y = r.origin[2]
Point2f[(x, y), (x, (y + r.widths[2]))]
end
function pcp_title!(
topscene,
endpoints::Observable,
title::String;
titlegap = Observable(4.0f0),
)
titlepos = lift(endpoints, titlegap) do a, titlegap
x = a[1][1]
y = a[2][2] + titlegap
Point2(x, y)
end
titlet = text!(
topscene,
title,
position = titlepos,
#visible = titlevisible,
#fontsize = config.legend.fontsize, # we need config here
align = (:center, :bottom),
#font = titlefont,
#color = titlecolor,
space = :data,
#show_axis=false,
inspectable = false,
)
end
"""
PCPTicks
Used to inject extrema ticks and round them if necessary.
"""
struct PCPTicks end
function Makie.get_ticks(ticks::PCPTicks, scale, formatter, vmin, vmax)
tickvalues = Makie.get_tickvalues(Makie.WilkinsonTicks(5), scale, vmin, vmax)
ticklabels_without = Makie.get_ticklabels(formatter, tickvalues)
if !(tickvalues[1] ≈ vmin)
tickvalues = [vmin, tickvalues...]
end
if !(tickvalues[end] ≈ vmax)
tickvalues = [tickvalues..., vmax]
end
ticklabels = Makie.get_ticklabels(formatter, tickvalues)
maxlen = length(ticklabels_without[1])
if length(ticklabels[1]) != maxlen
ticklabels = first.(ticklabels, maxlen)
ticklabels[1] = "~" * ticklabels[1]
ticklabels[end] = "~" * ticklabels[end]
end
return tickvalues, ticklabels
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4059 | using BSplineKit, Unfold
"""
plot_splines(m::UnfoldModel; kwargs...)
plot_splines!(f::Union{GridPosition, GridLayout, Figure}, m::UnfoldModel; kwargs...)
Visualization of spline terms in an UnfoldModel. Two subplots are generated for each spline term:\\
1) the basis function of the spline; 2) the density of the underlying covariate.\\
Multiple spline terms are arranged across columns.\\
Dashed lines indicate spline knots.
## Arguments:
- `f::Union{GridPosition, GridLayout, Figure}`
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `m::UnfoldModel`\\
UnfoldModel with splines.
- `spline_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of spline subplots.\\
To see all options just type `?Axis` in REPL.\\
Defaults: $(supportive_defaults(:spline_default))
- `density_axis::NamedTuple = (;)`\\
Here you can flexibly change configurations of density subplots.\\
To see all options just type `?Axis` in REPL.\\
Defaults: $(supportive_defaults(:density_default))
- `superlabel_config::NamedTuple = (;)`\\
Here you can flexibly change configurations of the Label on the top of the plot.\\
To see all options just type `?Label` in REPL.\\
Defaults: $(supportive_defaults(:superlabel_default))
$(_docstring(:splines))
**Return Value:** `Figure` with splines and their density for basis functions.
"""
plot_splines(m::UnfoldModel; kwargs...) = plot_splines(Figure(), m; kwargs...)
function plot_splines(
f::Union{GridPosition,GridLayout,Figure},
m::UnfoldModel;
spline_axis = (;),
density_axis = (;),
superlabel_config = (;),
kwargs...,
)
config = PlotConfig(:splines)
config_kwargs!(config; kwargs...)
spline_axis, density_axis, superlabel_config =
supportive_axes_management(spline_axis, density_axis, superlabel_config)
ga = f[1, 1] = GridLayout()
terms = Unfold.formulas(m)[1].rhs.terms
spl_title = join(terms, " + ")
splFunction = Base.get_extension(Unfold, :UnfoldBSplineKitExt).splFunction
spl_ix = findall(isa.(terms, Unfold.AbstractSplineTerm))
@assert !isempty(spl_ix) "No spline term is found in UnfoldModel. Does your UnfoldModel really have a `spl(...)` or other `AbstractSplineTerm`?"
spline_terms = [terms[i] for i in spl_ix]
subplot_id = 1
for spline_term in spline_terms
x_range = range(
spline_term.breakpoints[1],
stop = spline_term.breakpoints[end],
length = 100,
)
basis_set = splFunction(x_range, spline_term)
if subplot_id > 1
spline_axis = update_axis(spline_axis; ylabelvisible = false)
density_axis = update_axis(density_axis; ylabelvisible = false)
end
a1 = Axis(ga[1, subplot_id]; title = string(spline_term), spline_axis...)
series!(
x_range,
basis_set',
color = resample_cmap(config.visual.colormap, size(basis_set')[1]),
) # continuous color map used
vlines!(
spline_term.breakpoints;
ymin = extrema(basis_set')[1],
ymax = extrema(basis_set')[2],
linestyle = :dash,
)
a2 = Axis(ga[2, subplot_id]; xlabel = string(spline_term.term.sym), density_axis...)
density!(
Unfold.events(designmatrix(m))[1][:, spline_term.term.sym];
color = :transparent,
strokecolor = :black,
strokewidth = 1,
)
linkxaxes!(a1, a2)
subplot_id = subplot_id + 1
end
Label(ga[1, 1:end, Top()], spl_title; superlabel_config...)
f
end
function supportive_axes_management(spline_axis, density_axis, superlabel_config)
spline_axis = update_axis(supportive_defaults(:spline_default); spline_axis...)
density_axis = update_axis(supportive_defaults(:density_default); density_axis...)
superlabel_config =
update_axis(supportive_defaults(:superlabel_default); superlabel_config...)
return spline_axis, density_axis, superlabel_config
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3169 | """
plot_topoplot!(f::Union{GridPosition, GridLayout, Figure}, data::Union{<:AbstractDataFrame,<:AbstractVector}; positions::Vector, labels = nothing, kwargs...)
using Interpolations: positions
plot_topoplot(data::Union{<:AbstractDataFrame,<:AbstractVector}; position::Vector, labels = nothing, kwargs...)
Plot a topoplot.
## Arguments
- `f::Union{GridPosition, GridLayout, Figure}`\\
`Figure`, `GridLayout`, or `GridPosition` to draw the plot.
- `data::Union{DataFrame, Vector{Float32}}` \\
Data for the plot visualization.
- `positions::Vector{Point{2, Float32}}`\\
Positions used if `data` is not a `DataFrame`. Positions are generated from `labels` if `positions = nothing`.
- `labels::Vector{String} = nothing`\\
Labels used if `data` is not a DataFrame.
- `high_chan = nothing` - channnel(s) to highlight by color.
- `high_color = :darkgreen` - color for highlighting.
$(_docstring(:topoplot))
**Return Value:** `Figure` displaying the Topoplot.
"""
plot_topoplot(data::Union{<:AbstractDataFrame,<:AbstractVector}; kwargs...) =
plot_topoplot!(Figure(), data; kwargs...)
function plot_topoplot!(
f::Union{GridPosition,GridLayout,GridLayoutBase.GridSubposition,Figure},
data::Union{<:AbstractDataFrame,<:AbstractVector};
labels = nothing,
positions = nothing,
high_chan = nothing,
high_color = :darkgreen,
kwargs...,
)
config = PlotConfig(:topoplot)
config_kwargs!(config; kwargs...) # potentially should be combined
axis = Axis(f[1, 1]; config.axis...)
if !(data isa Vector)
config.mapping = resolve_mappings(data, config.mapping)
data = data[:, config.mapping.y]
end
if isnothing(positions) && !isnothing(labels)
positions = TopoPlots.labels2positions(labels)
end
positions = get_topo_positions(; positions = positions, labels = labels)
if isa(high_chan, Int) || isa(high_chan, Vector{Int64})
x = zeros(length(positions))
isa(high_chan, Int) ? x[high_chan] = 1 : x[high_chan] .= 1
clist = [:gray, high_color][Int.(x .+ 1)] #color for highlighting
eeg_topoplot!(
axis,
data,
labels;
positions,
config.visual...,
label_scatter = (;
color = clist,
markersize = ((x .+ 0.25) .* 40) ./ 5, # make adjustabel for users
),
)
else
eeg_topoplot!(axis, data, labels; positions, config.visual...)
end
if config.layout.use_colorbar == true
Colorbar(f[1, 2]; colormap = config.visual.colormap, config.colorbar...)
end
clims = (min(data...), max(data...))
if clims[1] ≈ clims[2]
@warn """The min and max of the value represented by the color are the same, it seems that the data values are identical.
We disable the color bar in this figure.
Note: The identical min and max may cause an interpolation error when plotting the topoplot."""
config_kwargs!(config, layout = (; use_colorbar = false))
else
config_kwargs!(config, colorbar = (; limits = clims))
end
apply_layout_settings!(config; fig = f)
return f
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 8926 | """
plot_topoplotseries(f::Union{GridPosition, GridLayout, Figure}, data::Union{<:Observable{<:DataFrame},DataFrame}; kwargs...)
plot_topoplotseries!(data::Union{<:Observable{<:DataFrame},DataFrame}; kwargs...)
Multiple miniature topoplots in regular distances.
## Arguments
- `f::Union{GridPosition, GridLayout, GridLayoutBase.GridSubposition, Figure}`\\
`Figure`, `GridLayout`, `GridPosition`, or `GridLayoutBase.GridSubposition` to draw the plot.
- `data::Union{<:Observable{<:DataFrame},DataFrame}`\\
DataFrame with data or Observable DataFrame.\\
Requires a `time` column by default, but can be overridden by specifying `mapping=(; x=:my_column)` with any continuous or categorical column.
## Keyword arguments (kwargs)
- `bin_width::Real = nothing`\\
Number specifing the width of bin of continuous x-value in its units.\\
- `bin_num::Real = nothing`\\
Number of topoplots.\\
Either `bin_width`, or `bin_num` should be specified. Error if they are both specified\\
If `mapping.col` or `mapping.row` are categorical `bin_width` and `bin_num` stay as `nothing`.
- `combinefun::Function = mean`\\
Specify how the samples within `bin_width` are summarised.\\
Example functions: `mean`, `median`, `std`.
- `rasterize_heatmaps::Bool = true`\\
Force rasterization of the plot heatmap when saving in `svg` format.\\
Except for the interpolated heatmap, all lines/points are vectors.\\
This is typically what you want, otherwise you get ~128x128 vectors per topoplot, which makes everything very slow.
- `col_labels::Bool`, `row_labels::Bool = true`\\
Shows column and row labels for categorical values.
- `labels::Vector{String} = nothing`\\
Show labels for each electrode.
- `positions::Vector{Point{2, Float32}} = nothing`\\
Specify channel positions. Requires the list of x and y positions for all unique electrode.
- `interactive_scatter = nothing`\\
Enable interactive mode.\\
If you create `obs_tuple = Observable((0, 0, 0))` and pass it into `interactive_scatter` you can update the observable tuple with the indices of the clicked topoplot markers.\\
`(0, 0, 0)` corresponds to the (row of topoplot layout, column of topoplot layout, electrode).
- `topoplot_axes::NamedTuple = (;)`\\
Here you can flexibly change configurations of topoplots.\\
To see all options just type `?Axis` in REPL.
- `mapping = (; col = :time`, row = nothing, layout = nothing)\\
`mapping.col` - specify x-value, can be any continuous or categorical variable.\\
`mapping.row` - specify y-value, can be any continuous or categorical variable (not implemented yet).\\
`mapping.layout` - arranges topoplots by rows when equals `:time`.\\
- `visual.colorrange::2-element Vector{Int64}`\\
Resposnible for colorrange in topoplots and in colorbar.
Code description:
-
$(_docstring(:topoplotseries))
**Return Value:** `Figure` displaying the Topoplot series.
"""
plot_topoplotseries(data::Union{<:Observable{<:DataFrame},DataFrame}; kwargs...) =
plot_topoplotseries!(Figure(), data; kwargs...)
function plot_topoplotseries!(
f::Union{GridPosition,GridLayout,Figure,GridLayoutBase.GridSubposition},
data::Union{<:Observable{<:DataFrame},DataFrame};
bin_width = nothing,
bin_num = nothing,
positions = nothing,
nrows = 1,
labels = nothing, # rename to channel_labels?
combinefun = mean,
col_labels = false,
row_labels = true,
rasterize_heatmaps = true,
interactive_scatter = nothing,
topoplot_axes = (;),
kwargs...,
)
data = _as_observable(data)
data_cuts = data
positions = get_topo_positions(; positions = positions, labels = labels)
chan_or_label = "label" ∉ names(to_value(data)) ? :channel : :label
config = PlotConfig(:topoplotseries)
# overwrite all defaults by user specified values
config_kwargs!(config; kwargs...)
# resolve columns with data
config.mapping = resolve_mappings(to_value(data), config.mapping)
data_copy = deepcopy(to_value(data)) # deepcopy prevents overwriting initial data
cat_or_cont_columns =
eltype(data_copy[!, config.mapping.col]) <: Number ? "cont" : "cat"
if cat_or_cont_columns == "cat"
# overwrite 'Time windows [s]' default if categorical
n_topoplots =
number_of_topoplots(data_copy; bin_width, bin_num, bins = 0, config.mapping)
ix =
findall.(
isequal.(unique(data_copy[!, config.mapping.col])),
[data_copy[!, config.mapping.col]],
)
else
bins = bins_estimation(
data_copy[!, config.mapping.col];
bin_width,
bin_num,
cat_or_cont_columns,
)
n_topoplots =
number_of_topoplots(data_copy; bin_width, bin_num, bins, config.mapping)
to_value(data_cuts).cont_cuts =
cut(to_value(data_cuts)[!, config.mapping.col], bins; extend = true)
unique_cuts = unique(to_value(data_cuts).cont_cuts)
ix = findall.(isequal.(unique_cuts), [to_value(data).cont_cuts])
end
data_row = @lift row_col_management($data_cuts, ix, n_topoplots, nrows, config)
config_kwargs!(
config;
mapping = (; row = :row_coord, col = :col_coord),
axis = (; xlabel = string(config.mapping.col)),
)
config_kwargs!(config; kwargs...) #add the user specified once more, just if someone specifies the xlabel manually
# overkll as we would only need to check the xlabel ;)
ftopo, axlist, colorrange = eeg_topoplot_series!(
f,
data_row;
cat_or_cont_columns = cat_or_cont_columns,
bin_width = bin_width,
bin_num = bin_num,
y = config.mapping.y,
label = chan_or_label,
col = config.mapping.col,
row = config.mapping.row,
col_labels = col_labels,
row_labels = row_labels,
rasterize_heatmaps = rasterize_heatmaps,
combinefun = combinefun,
topoplot_axes = topoplot_axes,
interactive_scatter = interactive_scatter,
config.visual...,
positions,
)
config_kwargs!(
config,
visual = (; colorrange = colorrange),
colorbar = (; colorrange = colorrange),
)
ax = Axis(
f[1, 1];
(p for p in pairs(config.axis) if p[1] != :xlim_topo && p[1] != :ylim_topo)...,
)
if config.layout.use_colorbar == true
Colorbar(f[1, 2]; colormap = config.visual.colormap, config.colorbar...)
end
apply_layout_settings!(config; fig = f, ax = ax)
return f
end
function row_col_management(data, ix, n_topoplots, nrows, config)
if :layout ∈ keys(config.mapping)
n_cols = Int(ceil(sqrt(n_topoplots)))
n_rows = Int(ceil(n_topoplots / n_cols))
else
n_rows = nrows
if 0 > n_topoplots / nrows
@warn "Impossible number of rows, set to 1 row"
n_rows = 1
elseif n_topoplots / nrows < 1
@warn "Impossible number of rows, set to $(n_topoplots) rows"
end
n_cols = Int(ceil(n_topoplots / n_rows))
end
col_coord = repeat(1:n_cols, outer = n_rows)[1:n_topoplots]
row_coord = repeat(1:n_rows, inner = n_cols)[1:n_topoplots]
data.col_coord .= 1
data.row_coord .= 1
for topo = 1:n_topoplots
data.col_coord[ix[topo]] .= col_coord[topo]
data.row_coord[ix[topo]] .= row_coord[topo]
end
return data
end
function bins_estimation(
continous_value;
bin_width = nothing,
bin_num = nothing,
cat_or_cont_columns = "cont",
)
c_min = minimum(continous_value)
c_max = maximum(continous_value)
if (!isnothing(bin_width) && !isnothing(bin_num))
error("Ambigious parameters: specify only `bin_width` or `bin_num`.")
elseif (isnothing(bin_width) && isnothing(bin_num) && cat_or_cont_columns == "cont")
error(
"You haven't specified `bin_width` or `bin_num`. Such option is available only with categorical `mapping.col` or `mapping.row`.",
)
end
if isnothing(bin_width)
bins = range(; start = c_min, length = bin_num + 1, stop = c_max)
else
bins = range(; start = c_min, step = bin_width, stop = c_max)
end
return bins
end
function number_of_topoplots(
df::DataFrame;
bin_width = nothing,
bin_num = nothing,
bins,
mapping = config.mapping,
)
if !isnothing(bin_width) | !isnothing(bin_num)
if typeof(df[:, mapping.col]) == Vector{String}
error(
"Parameters `bin_width` or `bin_num` are only allowed with continonus `mapping.col` or `mapping.row`, while you specifed categorical.",
)
end
cont_new = cut(df[:, mapping.col], bins; extend = true)
n = length(unique(cont_new))
else
n = length(unique(df[:, mapping.col]))
end
return n
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 9673 |
using GeometryBasics
using Makie: legend_position_to_aligns
using ColorSchemes: roma
using Makie
using Colors
using ColorSchemes
using ColorTypes
"""
PlotConfig(<plotname>)
Contains several different fields that can modify various aspects of the plot.
"""
mutable struct PlotConfig
figure::NamedTuple
axis::NamedTuple
layout::NamedTuple
mapping::NamedTuple
visual::NamedTuple
legend::NamedTuple
colorbar::NamedTuple
end
function PlotConfig()# defaults
PlotConfig(
(;), #figure
(;), # axis
(; # layout
show_legend = true,
use_colorbar = true,
),
(#maping
x = (:time,),
y = (:estimate, :yhat, :y),
),
(; # visual
colormap = :roma
),
(;#legend
orientation = :vertical,
tellwidth = true,
tellheight = false,
halign = :right,
valign = :center,
),
(;#colorbar
vertical = true,
tellwidth = true,
tellheight = false,
labelrotation = -π / 2,
),
)
end
PlotConfig(T::Symbol) = PlotConfig(Val{T}())
function PlotConfig(T::Val{:circtopos})
cfg = PlotConfig(:topoplot)
config_kwargs!(
cfg;
layout = (; show_legend = false),
colorbar = (;
labelrotation = -π / 2,
label = "Voltage [µV]",
colormap = Reverse(:RdBu),
),
mapping = (;),
axis = (;
label = ""
#backgroundcolor = RGB(0.98, 0.98, 0.98),
),
)
return cfg
end
function PlotConfig(T::Val{:topoplot})
cfg = PlotConfig()
config_kwargs!(
cfg;
layout = (
use_colorbar = true,
hidespines = (),
hidedecorations = (Dict(:label => false)),
),
visual = (;
contours = (color = :white, linewidth = 2),
enlarge = 1,
label_scatter = true,
label_text = true,
bounding_geometry = Circle,
colormap = Reverse(:RdBu),
),
mapping = (;
x = (nothing),
positions = (:pos, :positions, :position, nothing), # Point / Array / Tuple
labels = (:labels, :label, :sensor, nothing), # String
),
colorbar = (; flipaxis = true, label = "Voltage [µV]"),
axis = (; xlabel = "", aspect = DataAspect()),
)
return cfg
end
function PlotConfig(T::Val{:topoplotseries})
cfg = PlotConfig(:topoplot)
config_kwargs!(
cfg,
axis = (;
title = "",
titlesize = 16,
titlefont = :bold,
xlabel = "Time windows [s]",
ylabel = "",
ylabelpadding = 25,
xlabelpadding = 25,
xpanlock = true,
ypanlock = true,
xzoomlock = true,
yzoomlock = true,
xrectzoom = false,
yrectzoom = false,
),
layout = (; use_colorbar = true),
colorbar = (; flipaxis = true, label = "Voltage [µV]", colorrange = nothing),
visual = (;
label_text = false, # true doesnt work again
colormap = Reverse(:RdBu),
enlarge = 1,
label_scatter = false,
levels = nothing,
),
mapping = (; col = (:time,), row = (nothing,)),
)
return cfg
end
function PlotConfig(T::Val{:designmat})
cfg = PlotConfig()
config_kwargs!(
cfg;
layout = (; use_colorbar = true,),
axis = (;
xlabel = "Conditions",
ylabel = "Trials",
xticklabelrotation = round(pi / 8, digits = 2),
),
colorbar = (; flipaxis = true, label = ""),
)
return cfg
end
function PlotConfig(T::Val{:splines})
cfg = PlotConfig()
config_kwargs!(
cfg;
layout = (;),
axis = (;),
visual = (; colormap = :viridis),
legend = (; title = "Splines", framevisible = false),
)
return cfg
end
function PlotConfig(T::Val{:butterfly})
cfg = PlotConfig(:erp)
config_kwargs!(
cfg;
layout = (;
show_legend = false,
hidespines = (:r, :t),
hidedecorations = (Dict(
:label => false,
:ticks => false,
:ticklabels => false,
)),
),
mapping = (;
color = (:channel, :channels, :trial, :trials),
positions = (:pos, :positions, :position, :topo_positions, :x, nothing),
labels = (:labels, :label, :topoLabels, :sensor, nothing),
group = (:channel,),
),
axis = (xlabel = "Time [s]", ylabel = "Voltage [µV]", yticklabelsize = 14),
visual = (; color = nothing, colormap = nothing),
)
return cfg
end
function PlotConfig(T::Val{:erp})
cfg = PlotConfig()
config_kwargs!(
cfg;
mapping = (; color = (:color, :coefname, nothing)),
layout = (;
use_colorbar = true,
use_legend = true,
hidespines = (:r, :t),
hidedecorations = (Dict(
:label => false,
:grid => true,
:label => false,
:ticks => false,
:ticklabels => false,
)),
),
legend = (; framevisible = false),
axis = (
xlabel = "Time [s]",
ylabel = "Voltage [µV]",
yticklabelsize = 14,
xtickformat = "{:.1f}",
),
colorbar = (; label = "", flipaxis = true),
)
return cfg
end
function PlotConfig(T::Val{:erpgrid})
cfg = PlotConfig()
config_kwargs!(
cfg;
layout = (;),
colorbar = (;),
mapping = (;),
axis = (
xlabel = "Time [s]",
ylabel = "Voltage [µV]",
xlim = [-0.04, 1],
ylim = [-0.04, 1],
fontsize = 12,
),
)
return cfg
end
function PlotConfig(T::Val{:channelimage})
cfg = PlotConfig()
config_kwargs!(
cfg;
#layout = (; use_colorbar = true),
colorbar = (; label = "Voltage [µV]"),
axis = (xlabel = "Time [s]", ylabel = "Channels", yticklabelsize = 14),
visual = (; colormap = Reverse("RdBu")), #cork
)
return cfg
end
function PlotConfig(T::Val{:erpimage})
cfg = PlotConfig()
config_kwargs!(
cfg;
layout = (; use_colorbar = true),
colorbar = (; label = "Voltage [µV]"),
axis = (xlabel = "Time [s]", ylabel = "Trials"),
visual = (; colormap = Reverse("RdBu")),
)
return cfg
end
function PlotConfig(T::Val{:paracoord})
cfg = PlotConfig()
config_kwargs!(
cfg;
visual = (;
colormap = Makie.wong_colors(),
color = :black, # default linecolor
alpha = 0.3,
),
axis = (; xlabel = "Channels", ylabel = "Time", title = ""),
legend = (; title = "Conditions", merge = true, framevisible = false), # fontsize = 14),
mapping = (; x = :channel),
layout = (; show_legend = true),
)
return cfg
end
function resolve_mappings(plot_data, mapping_data) # check mapping_data in PlotConfig(T::Val{:erp})
function is_column(col)
string(col) ∈ names(plot_data)
end
# filter columns to only include the ones that are in plot_data, or throw an error if none are
function get_available(key, choices)
# is_column is an internally defined function mapping col ∈ names(plot_data)
available = choices[keys(choices)[is_column.(collect(choices))]]
if length(available) >= 1
return available[1]
else
return (nothing ∈ collect(choices)) ? # is it allowed to return nothing?
nothing :
@error(
"Default columns for $key = $choices not found,
user must provide one by using plot_plotname(...; mapping=(; $key=:your_column_name))"
)
end
end
# have to use Dict here because NamedTuples break when trying to map them with keys/indices
mapping_dict = Dict()
for (k, v) in pairs(mapping_data)
mapping_dict[k] = isa(v, Tuple) ? get_available(k, v) : v
end
return (; mapping_dict...)
end
"""
config_kwargs!(cfg::PlotConfig; kwargs...)
Takes NamedTuple of `Key => NamedTuple` as kwargs and merges the fields with the defaults.
"""
function config_kwargs!(cfg::PlotConfig; kwargs...)
is_namedtuple = [isa(t, NamedTuple) for t in values(kwargs)]
@assert(
all(is_namedtuple),
""" Keyword argument specification (kwargs...). Specified config groups must be from `NamedTuple`, but $(keys(kwargs)[.!is_namedtuple]) was not.
Maybe you forgot the semicolon (;) at the beginning of your specification? Compare these strings:
plot_example(...; layout = (; use_colorbar = true))
plot_example(...; layout = (use_colorbar = true))
The first is correct and creates a `NamedTuple` as needed. The second is incorrect and its call is ignored."""
)
field_list = fieldnames(PlotConfig) #[:layout, :visual, :mapping, :legend, :colorbar, :axis]
key_list = collect(keys(kwargs))
:extra ∈ key_list ?
@warn(
"Extra is deprecated in 0.4, and extra keyword arguments must be used directly as keyword arguments."
) : ""
apply_to = key_list[in.(key_list, Ref(field_list))]
for k ∈ apply_to
setfield!(cfg, k, merge(getfield(cfg, k), kwargs[k]))
end
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2756 |
struct RelativeAxis
layoutobservables::GridLayoutBase.LayoutObservables{GridLayout}
relative_bbox::NTuple
end
"""
RelativeAxis(fig, p::NTuple{4, Float64}; kwargs...)
Returns an `Axis` whose position is relative to a `GridLayout` element (via `BBox`) and not relative to the `Scene`.
Default behavior is `Axis(..., bbox = BBox())`.
- `p::NTuple{4,Float64}`: specify the position relative to the GridPosition
left:right; bottom:top, typical numbers between 0 and 1, e.g. (0.25, 0.75, 0.25, 0.75) would center an `Axis` inside this `GridPosition`.
- `kwargs...` - inserted into the axis.
f = Figure()
ax = RelativeAxis(f[1, 2], (0.25, 0.75, 0.25, 0.75)# returns Axis centered within f[1, 2]
**Return Value:** `Axis`.
"""
function RelativeAxis(
figlike::Union{GridPosition,GridSubposition,Axis},
rel::NTuple{4,Float64};
kwargs...,
)
# it's all fake!
layoutobservables = GridLayoutBase.LayoutObservables(
Observable(nothing),
Observable(nothing),
Observable(true),
Observable(true),
Observable(true),
Observable(true),
Observable(Inside()),
suggestedbbox = nothing,
)
# generate placeholder container
r = RelativeAxis(layoutobservables, rel)
# lift bbox to make it relative
bbox = lift(suggestedbbox(figlike, r), r.relative_bbox) do old, rel
return rel_to_abs_bbox(old, rel)
end
# generate axis
ax = Axis(get_figure(figlike); bbox = bbox, kwargs...)
return ax
end
function suggestedbbox(figlike::Union{GridPosition,GridSubposition}, r::RelativeAxis)
# asign it to GridLayout to get suggestedbbox
figlike[] = r
return suggestedbboxobservable(r)
end
function suggestedbbox(figlike::Axis, r::RelativeAxis)
# need to use viewport to follow the aspect ratio of an axis
return figlike.scene.viewport
end
get_figure(f::GridPosition) = f.layout.parent
get_figure(f::GridSubposition) = get_figure(f.parent)
get_figure(f::Axis) = f.parent
"""
rel_to_abs_bbox(org, rel)
Takes a rectangle `org` consiting of coordinates of origins and applies the relative transformation tuple `rel`.
**Return Value:** `Makie.BBox`.
"""
function rel_to_abs_bbox(org, rel)
# org => suggestedbbox of parent Grid
# rel => BBox input between 0 / 1
(org_left, org_right, org_bottom, org_top) = rel
org_width = org_right - org_left
org_heigth = org_top - org_bottom
new_width = org.widths[1] .* org_width
new_heigth = org.widths[2] .* org_heigth
new_left = org.origin[1] + org.widths[1] * org_left
new_bottom = org.origin[2] + org.widths[2] * org_bottom
tup = new_left, new_left + new_width, new_bottom, new_bottom + new_heigth
return BBox(tup...)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2250 |
"""
supportive_defaults(cfg_symb::Symbol)
Default configurations for the supporting axis. Similar to PlotConfig, but these configurations are not shared by all plots.\\
Such supporting axes allow users to flexibly see defaults in docstrings and manipulate them using corresponding axes.
For developers: to make them updateable in the function, use `update_axis`.
**Return value:** `NamedTuple`.
"""
function supportive_defaults(cfg_symb::Symbol)
# plot_splines
if cfg_symb == :spline_default
return (;
ylabel = "Spline value",
xlabelvisible = false,
xticklabelsvisible = false,
ylabelvisible = true,
)
elseif cfg_symb == :density_default
return (; xautolimitmargin = (0, 0), ylabel = "Density value")
elseif cfg_symb == :superlabel_default
return (; fontsize = 20, padding = (0, 0, 40, 0))
# plot_butterfly
elseif cfg_symb == :topo_default
return (;
width = Relative(0.35),
height = Relative(0.35),
halign = 0.05,
valign = 0.95,
aspect = 1,
)
# plot_erpimage
elseif cfg_symb == :meanplot_default
return (;
height = 100,
xlabel = "Time [s]",
xlabelpadding = 0,
xautolimitmargin = (0, 0),
)
elseif cfg_symb == :sortplot_default
return (; ylabelvisible = true, yticklabelsvisible = false)
# plot_erpgrid
elseif cfg_symb == :hlines_grid_default
return (; color = :gray, linewidth = 0.5)
elseif cfg_symb == :vlines_grid_default
return (; color = :gray, linewidth = 0.5, ymin = 0.2, ymax = 0.8)
elseif cfg_symb == :lines_grid_default
return (; color = :deepskyblue3)
elseif cfg_symb == :labels_grid_default
return (; color = :gray, fontsize = 12, align = (:left, :top), space = :relative)
end
end
"""
update_axis(support_axis::NamedTuple; kwargs...)
Update values of `NamedTuple{key = value}`.\\
Used for supportive axes to make users be able to flexibly change them.
"""
function update_axis(support_axis::NamedTuple; kwargs...)
support_axis = (; support_axis..., kwargs...)
return support_axis
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1746 | function get_topo_positions(; labels = nothing, positions = nothing)
# positions have priority over labels
if isnothing(positions) && !isnothing(labels)
positions = getLabelPos.(labels)
end
@assert !isnothing(positions) "No positions found, did you forget to provide them via positions=XX, or labels=YY?"
return positions .|> (p -> Point2f(p[1], p[2]))
end
function get_topo_color(positions, posToColor)
if isnothing(positions)
return nothing
end
return posToColor.(positions)
end
function pos_to_color_RGB(pos)
cx = 0.5 - pos[1]
cy = 0.5 - pos[2]
# rotate to mimick MNE
rx = cx * 0.7071068 + cy * 0.7071068
ry = cx * -0.7071068 + cy * 0.7071068
b = 1.0 - (2 * sqrt(cx^2 + cy^2))^2 # weight by distance
colorwheel = RGB(0.5 - rx * 1.414, 0.5 - ry * 1.414, b)
return colorwheel
end
function pos_to_color_HSV(pos)
rx = 0.5 - pos[1]
ry = 0.5 - pos[2]
b = 0.5
θ, r = cart2pol.(rx, ry)
colorwheel = HSV(θ * 360, b, (r ./ 0.7) ./ 2 + 0.5)
return colorwheel
end
function pos_to_color_RomaO(pos)
rx = 0.5 - pos[1]
ry = 0.5 - pos[2]
θ, r = cart2pol.(rx, ry)
# circular colormap 2D
colorwheel = get(ColorSchemes.romaO, θ)
return colorwheel
end
function cart2pol(x, y)
θ = atan(x, y) ./ (2 * π) + 0.5
r = sqrt(x^2 + y^2)
return θ, r
end
function extract_colorrange(data_mean, y)
# aggregate the data over time bins
# using same colormap + contour levels for all plots
(q_min, q_max) = Statistics.quantile(data_mean[:, y], [0.001, 0.999])
# make them symmetrical
q_min = q_max = max(abs(q_min), abs(q_max))
q_min = -q_min
colorrange = (q_min, q_max)
return colorrange
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1116 | using UnfoldMakie
include("setup.jl")
#include("../src/UnfoldMakie.jl")
@testset "Test Config" begin
include("test_config.jl")
end
@testset "ERP plot" begin
include("test_erp.jl")
end
@testset "ERP plot: effects" begin
include("test_erp_effects.jl")
end
@testset "Butterfly" begin
include("test_butterfly.jl")
end
@testset "ERP image" begin
include("test_erpimage.jl")
end
@testset "Channel image" begin
include("test_channelimage.jl")
end
@testset "Topoplot" begin
include("test_topoplot.jl")
end
@testset "Topoplot series simple" begin
include("test_toposeries1.jl")
end
@testset "Topoplot series advanced" begin
include("test_toposeries2.jl")
end
@testset "ERP grid" begin
include("test_erpgrid.jl")
end
@testset "Parallel coordinates" begin
include("test_pcp.jl")
end
@testset "Circular EEG topoplot" begin
include("test_circular_topoplots.jl")
end
@testset "Design matricies" begin
include("test_dm.jl")
end
@testset "Spline plots" begin
include("test_splines.jl")
end
@testset "Complex plots" begin
include("test_complexplots.jl")
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 245 | using CairoMakie
using UnfoldSim
using Test
using GeometryBasics
using DataFrames
using TopoPlots
using Colors
using Statistics
using AlgebraOfGraphics
using Random
include("../docs/example_data.jl")
raw_ch_names = example_data("raw_ch_names")
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 5201 |
include("../docs/example_data.jl")
df, pos = example_data("TopoPlots.jl")
tmp = DataFrame(channel = df.channel, estimate = df.estimate)
grouped = groupby(tmp, :channel)
mat = Matrix(reduce(hcat, [group.estimate for group in grouped])')
@testset "butterfly: DataFrame as data input" begin
plot_butterfly(df; positions = pos)
#save("dev/UnfoldMakie/default_butterfly.png", f)
end
@testset "butterfly: Matrix as data input" begin
plot_butterfly(mat; positions = pos)
end
@testset "butterfly: GridLayout for DataFrame" begin
f = Figure()
plot_butterfly!(f[1, 1], df; positions = pos)
end
@testset "butterfly: GridLayout for Matrix" begin
f = Figure()
plot_butterfly!(f[1, 1], mat; positions = pos)
end
@testset "butterfly: without topolegend" begin
plot_butterfly(
df;
positions = pos,
topopositions_to_color = x -> Colors.RGB(0.1),
topolegend = false,
)
#save("dev/UnfoldMakie/basic_butterfly.png", f)
end
@testset "butterfly: change of topomarkersize" begin
plot_butterfly(
df;
positions = pos,
topomarkersize = 70,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
)
end
@testset "butterfly: add h and vlines in a Figure" begin
f = Figure()
plot_butterfly!(f, df; positions = pos)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
f
end
@testset "butterfly: add h- and vlines in GridPosition" begin
f = Figure()
ax = Axis(f[1:2, 1:5], aspect = DataAspect(), title = "Just a title")
plot_butterfly!(f[1:2, 1:5], df; positions = pos)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
hidespines!(ax)
hidedecorations!(ax, label = false)
f
end
@testset "butterfly: no decorations" begin
f = Figure()
plot_butterfly!(
f[1, 1],
df;
positions = pos,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
layout = (;
hidedecorations = (:label => true, :ticks => true, :ticklabels => true)
),
)
f
end
# Color schemes
@testset "changing color from ROMA to gray" begin
plot_butterfly(df; positions = pos, topopositions_to_color = x -> Colors.RGB(0.5))
end
@testset "changing color from ROMA to HSV" begin
plot_butterfly(
df;
positions = pos,
topopositions_to_color = UnfoldMakie.pos_to_color_HSV,
)
end
@testset "changing color from ROMA to RGB" begin
plot_butterfly(
df;
positions = pos,
topopositions_to_color = UnfoldMakie.pos_to_color_RGB,
)
end
# would be nice these colors to be colowheeled
@testset "butterfly: changing color to veridis" begin
plot_butterfly(
df;
positions = pos,
visual = (; colormap = :viridis), # choose Makie colorscheme
)
end
@testset "butterfly: changing color to romaO" begin
plot_butterfly(df; positions = pos, visual = (; colormap = :romaO))
end
@testset "butterfly: changing color to gray" begin
plot_butterfly(
df;
positions = pos,
visual = (; colormap = [:gray]), # choose Makie colorscheme
)
end
@testset "butterfly: changing color to HSV" begin
plot_butterfly(
df;
positions = pos,
visual = (; colormap = HSV.(range(0, 360, 10), 50, 50)), # choose Makie colorscheme
)
end
# Channel highlighted
@testset "butterfly: with single color highlighted channel" begin
f = pos -> UnfoldMakie.pos_to_color_RGB(pos)
f =
p ->
p == pos[10] ? Colors.RGB(1, 0, 0) : Colors.RGB(128 / 255, 128 / 255, 128 / 255)
plot_butterfly(df; positions = pos, topopositions_to_color = f)
end
# colors should be black and red
@testset "butterfly: with single color highlighted channel - 2" begin
df.highlight = in.(df.channel, Ref(10))
plot_butterfly(df; positions = pos, mapping = (; color = :highlight))
end
@testset "butterfly: with two color highlighted channel" begin
df.highlight = in.(df.channel, Ref([10, 12]))
plot_butterfly(df; positions = pos, mapping = (; color = :highlight))
end
@testset "butterfly: with two color highlighted channels and specified colormap" begin
df.highlight = in.(df.channel, Ref([10, 12]))
plot_butterfly(
df;
positions = pos,
mapping = (; color = :highlight), # define channels to be highlighted by color
visual = (; colormap = :rust), # choose Makie colorscheme
)
end
@testset "butterfly: with faceting of highlighted channels" begin
df.highlight = in.(df.channel, Ref([10, 12]))
df.highlight = replace(df.highlight, true => "channels 10, 12", false => "all channels")
plot_butterfly(
df;
positions = pos,
mapping = (; color = :highlight, col = :highlight),
visual = (;
color = 1:2,
colormap = [Colors.RGB(128 / 255, 128 / 255, 128 / 255), :red],
),
)
end
#TO DO
# not working
#= @testset "butterfly: with two size highlighted channels" begin
df.highlight = in.(df.channel, Ref([10, 12]))
plot_butterfly(df; positions = pos, mapping = (; linesize = :highlight))
end =#
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1802 | dat, pos = TopoPlots.example_data()
dat = dat[:, :, 1]
pos = pos[1:30]
df, pos2 = example_data("TopoPlots.jl")
@testset "Channel image: 3 arguments, data as Matrix" begin
plot_channelimage(dat[1:30, :], pos, raw_ch_names;)
end
@testset "Channel image: 4 arguments, data as Matrix" begin
f = Figure()
plot_channelimage!(f, dat[1:30, :], pos, raw_ch_names;)
end
@testset "Channel image: 3 arguments, data as DataFrame" begin
f = Figure(size = (400, 800))
array = [string(i) for i = 1:64]
df2 = unstack(df[:, [:estimate, :time, :channel]], :channel, :time, :estimate)
select!(df2, Not(:channel))
plot_channelimage!(f, df2, pos2, array;)
end
@testset "Channel image: error of unequal length of pos and ch_names" begin
err1 = nothing
t() = error(plot_channelimage(dat[1:30, :], pos[1:10], raw_ch_names;))
try
t()
catch err1
end
end
@testset "Channel image: sorting by y" begin
plot_channelimage(
dat[1:30, :],
pos,
raw_ch_names;
sorting_variables = [:y],
sorting_reverse = [:true],
)
end
@testset "Channel image: sorting by ch_names" begin
plot_channelimage(
dat[1:30, :],
pos,
raw_ch_names;
sorting_variables = [:ch_names],
sorting_reverse = [:true],
)
end
@testset "Channel image: error of unequal sorting_variables and sorting_reverse" begin
err1 = nothing
t() =
error(plot_channelimage(dat[1:30, :], pos, raw_ch_names; sorting_variables = [:y]))
try
t()
catch err1
end
end
@testset "Channel image: error of unequal data and sorting_reverse" begin
err1 = nothing
t() = error(plot_channelimage(dat, pos, raw_ch_names; sorting_variables = [:y]))
try
t()
catch err1
end
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3415 | #include("setup.jl")
data, pos = TopoPlots.example_data()
dat = data[:, 240, 1]
df = DataFrame(
:estimate => eachcol(Float64.(data[:, 100:40:300, 1])),
:circularVariable => [0, 50, 80, 120, 180, 210],
:time => 100:40:300,
)
labels = ["s$i" for i = 1:size(dat, 1)]
df = flatten(df, :estimate)
d_topo, positions = example_data("TopoPlots.jl")
@testset "error cases and warns" begin
@testset "out of error bounds" begin
testdf = DataFrame(
estimate = [[4.0, 1.0], [4.0, 3.0], [4.0, 3.0]],
predictor = [70, 80, 400],
)
@test_throws ErrorException plot_circular_topoplots(
testdf;
positions = [Point(1.0, 2.0), Point(1.0, 2.0), Point(1.0, 2.0)],
)
end
@testset "tooManyBoundsErr" begin
testdf = DataFrame(
estimate = [[4.0, 1.0], [4.0, 3.0], [4.0, 3.0]],
predictor = [70, 80, 90],
)
@test_throws ErrorException plot_circular_topoplots(
testdf;
predictor_bounds = [0, 100, 360],
positions = [Point(1.0, 2.0), Point(1.0, 2.0), Point(1.0, 2.0)],
)
end
end
@testset "testing calculate_global_max_values" begin
# notice: this function uses the 0.01 and the 0.99 quantile
pred = repeat(1:3, inner = 5)
val = [1:5...; 6:10...; 11:15...]
a, b = UnfoldMakie.calculate_global_max_values(val, pred)
@test isapprox(a, -14.96)
@test isapprox(b, 14.96)
end
@testset "testing calculate_axis_labels" begin
# notice: this function uses the 0.01 and the 0.99 quantile
@test UnfoldMakie.calculate_axis_labels([0, 360]) == ["0", "90", "180 ", "270"]
@test UnfoldMakie.calculate_axis_labels([-180, 180]) == ["-180", "-90", "0 ", "90"]
@test UnfoldMakie.calculate_axis_labels([0, 100]) == ["0", "25", "50 ", "75"]
end
@testset "testing calculate_BBox" begin
@test UnfoldMakie.calculate_BBox([0, 0], [1000, 1000], 180, [0, 360], 0.8) ==
BBox(0.0, 200.0, 400.0, 600)
@test UnfoldMakie.calculate_BBox([0, 0], [1000, 1000], -45, [0, 360], 0.8) ==
BBox(682.842712474619, 882.842712474619, 117.15728752538104, 317.15728752538104)
@test UnfoldMakie.calculate_BBox([0, 0], [1000, 1000], -180, [-180, 180], 0.8) ==
BBox(800.0, 1000.0, 400.0, 600.0)
end
@testset "circularplot plot basic" begin
plot_circular_topoplots(
df;
positions = pos,
center_label = "Visual angle [°]",
predictor = :time,
predictor_bounds = [80, 320],
)
end
@testset "circularplot plot in GridLayout with labels" begin
f = Figure()
ga = f[1, 1] = GridLayout()
plot_circular_topoplots!(
ga,
df;
positions = pos,
center_label = "Visual angle [°]",
predictor = :time,
predictor_bounds = [80, 320],
labels = labels,
)
f
end
@testset "circularplot plot basic" begin
plot_circular_topoplots(
d_topo[in.(d_topo.time, Ref(-0.3:0.1:0.5)), :];
positions = positions,
predictor = :time,
predictor_bounds = [-0.3, 0.5],
)
end
@testset "circularplot plot in GridLayout" begin
f = Figure(size = (2000, 2000))
plot_circular_topoplots!(
f[3:4, 4:5],
d_topo[in.(d_topo.time, Ref(-0.3:0.1:0.5)), :];
positions = positions,
predictor = :time,
predictor_bounds = [-0.3, 0.5],
)
f
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 6352 | @testset "8 plots" begin
f = Figure(size = (1200, 1400))
ga = f[1, 1]
gc = f[2, 1]
ge = f[3, 1]
gg = f[4, 1]
gb = f[1, 2]
gd = f[2, 2]
gf = f[3, 2]
gh = f[4, 2]
include("../docs/example_data.jl")
d_topo, pos = example_data("TopoPlots.jl")
data, positions = TopoPlots.example_data()
df = UnfoldMakie.eeg_array_to_dataframe(data[:, :, 1], string.(1:length(positions)))
m = example_data("UnfoldLinearModel")
results = coeftable(m)
results.coefname =
replace(results.coefname, "condition: face" => "face", "(Intercept)" => "car")
results = filter(row -> row.coefname != "continuous", results)
plot_erp!(
ga,
results;
:stderror => true,
mapping = (; color = :coefname => "Conditions"),
)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
plot_butterfly!(
gb,
d_topo;
positions = pos,
topomarkersize = 10,
topo_axis = (; height = Relative(0.4), width = Relative(0.4)),
)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
plot_topoplot!(
gc,
data[:, 340, 1];
positions = positions,
axis = (; xlabel = "[340 ms]"),
)
plot_topoplotseries!(
gd,
df;
bin_width = 80,
positions = positions,
visual = (label_scatter = false,),
layout = (; use_colorbar = true),
)
ax = gd[1, 1] = Axis(f)
text!(ax, 0, 0, text = "Time [ms]", align = (:center, :center), offset = (-20, -80))
hidespines!(ax) # delete unnecessary spines (lines)
hidedecorations!(ax, label = false)
plot_erpgrid!(
ge,
data[:, :, 1],
positions;
axis = (; ylabel = "µV", ylim = [-0.05, 0.6], xlim = [-0.04, 1]),
)
dat_e, evts, times = example_data("sort_data")
plot_erpimage!(gf, times, dat_e; sortvalues = evts.Δlatency)
plot_channelimage!(gg, data[1:30, :, 1], positions[1:30], raw_ch_names;)
r1, positions = example_data()
r2 = deepcopy(r1)
r2.coefname .= "B" # create a second category
r2.estimate .+= rand(length(r2.estimate)) * 0.1
results_plot = vcat(r1, r2)
plot_parallelcoordinates(
gh,
subset(results_plot, :channel => x -> x .< 8, :time => x -> x .< 0);
mapping = (; color = :coefname),
normalize = :minmax,
ax_labels = ["FP1", "F3", "F7", "FC3", "C3", "C5", "P3", "P7"],
)
for (label, layout) in
zip(["A", "B", "C", "D", "E", "F", "G", "H"], [ga, gb, gc, gd, ge, gf, gg, gh])
Label(
layout[1, 1, TopLeft()],
label,
fontsize = 26,
font = :bold,
padding = (20, 20, 22, 0), #(20, 70, 22, 0),
halign = :right,
)
end
f
#save("dev/UnfoldMakie/docs/src/assets/complex_plot.png", f)
end
@testset "8 plots with a Figure" begin
f = Figure(size = (1200, 1400))
include("../docs/example_data.jl")
d_topo, positions = example_data("TopoPlots.jl")
data, positions = TopoPlots.example_data()
uf = example_data("UnfoldLinearModel")
results = coeftable(uf)
uf_5chan = example_data("UnfoldLinearModelMultiChannel")
d_singletrial, _ = UnfoldSim.predef_eeg(; return_epoched = true)
pvals = DataFrame(
from = [0.1, 0.15],
to = [0.2, 0.5],
# if coefname not specified, line should be black
coefname = ["(Intercept)", "category: face"],
)
plot_erp!(f[1, 1], results, significance = pvals, stderror = true)
plot_butterfly!(f[1, 2], d_topo, positions = positions)
plot_topoplot!(f[2, 1], data[:, 150, 1]; positions = positions)
plot_topoplotseries!(
f[2, 2],
d_topo;
bin_width = 0.1,
positions = positions,
visual = (label_scatter = false,),
layout = (; use_colorbar = true),
)
plot_erpgrid!(f[3, 1], data[:, :, 1], positions)
times = -0.099609375:0.001953125:1.0
plot_erpimage!(f[3, 2], times, d_singletrial)
plot_parallelcoordinates(f[4, 2], uf_5chan; mapping = (; color = :coefname))
for (label, layout) in zip(
["A", "B", "C", "D", "E", "F", "G", "H"],
[f[1, 1], f[1, 2], f[2, 1], f[2, 2], f[3, 1], f[3, 2], f[4, 1], f[4, 2]],
)
Label(
layout[1, 1, TopLeft()],
label,
fontsize = 26,
font = :bold,
padding = (0, 5, 5, 0),
halign = :right,
)
end
f
end
@testset "testing combined figure (a Figure from mult_viz_in_fig from docs)" begin
include("../docs/example_data.jl")
d_topo, positions = example_data("TopoPlots.jl")
uf_deconv = example_data("UnfoldLinearModelContinuousTime")
uf = example_data("UnfoldLinearModel")
results = coeftable(uf)
uf_5chan = example_data("UnfoldLinearModelMultiChannel")
d_singletrial, _ = UnfoldSim.predef_eeg(; return_epoched = true)
data, positions = TopoPlots.example_data()
times = -0.099609375:0.001953125:1.0
f = Figure(size = (2000, 2000))
plot_butterfly!(f[1, 1:3], d_topo; positions = positions)
pvals = DataFrame(
from = [0.1, 0.15],
to = [0.2, 0.5],
# if coefname not specified, line should be black
coefname = ["(Intercept)", "category: face"],
)
plot_erp!(f[2, 1:2], results, significance = pvals, stderror = true)
plot_designmatrix!(f[2, 3], designmatrix(uf))
plot_topoplot!(f[3, 1], data[:, 150, 1]; positions = positions)
plot_topoplotseries!(
f[4, 1:3],
d_topo;
bin_width = 0.1,
positions = positions,
mapping = (; label = :channel),
)
res_effects = effects(Dict(:continuous => -5:0.5:5), uf_deconv)
plot_erp!(
f[2, 4:5],
res_effects;
mapping = (; y = :yhat, color = :continuous, group = :continuous => nonnumeric),
)
plot_parallelcoordinates(f[3, 2:3], uf_5chan; mapping = (; color = :coefname))
plot_erpimage!(f[1, 4:5], times, d_singletrial)
plot_circular_topoplots!(
f[3:4, 4:5],
d_topo[in.(d_topo.time, Ref(-0.3:0.1:0.5)), :];
positions = positions,
predictor = :time,
predictor_bounds = [-0.3, 0.5],
)
f
#save("test.png", f)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 317 | @testset "config kwargs" begin
cfg = PlotConfig()
UnfoldMakie.config_kwargs!(cfg; visual = (; bla = :blub))
@test cfg.visual.bla == :blub
# What if you forget `;` - that is, forget to specify a `NamedTuple`.
@test_throws AssertionError UnfoldMakie.config_kwargs!(cfg; visual = (bla = :blub))
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 1122 | include("../docs/example_data.jl")
uf = example_data("UnfoldLinearModel")
td = example_data("UnfoldTimeExpanded")
@testset "basic" begin
plot_designmatrix(designmatrix(uf))
end
@testset "sort data" begin
plot_designmatrix(designmatrix(uf); sort_data = true)
end
@testset "designmatrix plot in GridLayout" begin
f = Figure(size = (1200, 1400))
ga = f[1, 1] = GridLayout()
plot_designmatrix!(ga, designmatrix(uf); sort_data = true)
f
end
@testset "ticks specified" begin
plot_designmatrix(designmatrix(uf); xticks = 10, sort_data = false)
end
@testset "hierarchical labels (bugged)" begin
df, evts = UnfoldSim.predef_eeg()
f = @formula 0 ~ 1 + condition + continuous
basisfunction = firbasis(τ = (-0.4, 0.8), sfreq = 5, name = "stimulus")
#basisfunction = firbasis(τ = (-0.4, -0.3), sfreq = 10, name = "")
bfDict = [Any => (f, basisfunction)]
td = fit(UnfoldModel, bfDict, evts, df)
plot_designmatrix(designmatrix(td))
end
#Unfold.SimpleTraits.istrait(Unfold.ContinuousTimeTrait{typeof(td)})
#Unfold.SimpleTraits.istrait(Unfold.ContinuousTimeTrait{typeof(uf)})
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 4785 | using Unfold: stderror
using AlgebraOfGraphics: group
include("../docs/example_data.jl")
m = example_data("UnfoldLinearModel")
results = coeftable(m)
res_effects = effects(Dict(:continuous => -5:0.5:5), m)
res_effects2 = effects(Dict(:condition => ["car", "face"], :continuous => -5:5), m)
dat, positions = TopoPlots.example_data()
m7 = example_data("7channels")
results7 = coeftable(m7)
@testset "ERP plot: DataFrame data" begin
plot_erp(results)
end
@testset "ERP plot: Matrix data" begin
plot_erp(dat[1, :, 1:2]')
end
@testset "ERP plot: Array data" begin
plot_erp(dat[1, :, 1])
end
@testset "ERP plot: rename xlabel" begin
plot_erp(results; axis = (; xlabel = "test"))
end
@testset "ERP plot: xlabelvisible" begin
plot_erp(results; axis = (; xlabelvisible = false, xticklabelsvisible = false))
end
@testset "ERP plot: Array data with times vector" begin
times = range(0, step = 100, length = size(dat, 2))
plot_erp(times, dat[1, :, 1], axis = (; xtickformat = "{:d}"))
end
@testset "ERP plot: stderror error" begin
plot_erp(results; stderror = true)
end
@testset "ERP plot: standart errors in GridLayout" begin
f = Figure(size = (1200, 1400))
ga = f[1, 1] = GridLayout()
plot_erp!(ga, results; stderror = true)
f
end
@testset "ERP plot: faceting by two columns" begin
results = coeftable(m)
results.group = push!(repeat(["A", "B"], inner = 67), "A")
plot_erp(results; mapping = (; col = :group))
end
@testset "ERP plot: faceting by two columns with stderror" begin
results = coeftable(m)
results.group = push!(repeat(["A", "B"], inner = 67), "A")
plot_erp(results; mapping = (; col = :group), stderror = true)
end
@testset "ERP plot: with and withour error ribbons" begin
results = coeftable(m)
results.coefname =
replace(results.coefname, "condition: face" => "face", "(Intercept)" => "car")
results = filter(row -> row.coefname != "continuous", results)
f = Figure()
plot_erp!(
f[1, 1],
results;
axis = (; title = "Bad example", titlegap = 12),
stderror = false,
mapping = (; color = :coefname => "Conditions"),
)
plot_erp!(
f[2, 1],
results;
axis = (title = "Good example", titlegap = 12),
stderror = true,
mapping = (; color = :coefname => "Conditions"),
)
ax = Axis(f[2, 1], width = Relative(1), height = Relative(1))
xlims!(ax, [-0.04, 1])
ylims!(ax, [-0.04, 1])
hidespines!(ax)
hidedecorations!(ax)
text!(0.98, 0.2, text = "* Confidence\nintervals", align = (:right, :top))
f
#save("erp.png", f)
end
@testset "ERP plot: in GridLayout" begin
f = Figure(size = (1200, 1400))
ga = f[1, 1] = GridLayout()
pvals = DataFrame(
from = [0.1, 0.15],
to = [0.2, 0.5],
# if coefname not specified, line should be black
coefname = ["(Intercept)", "category: face"],
)
plot_erp!(ga, results; significance = pvals, stderror = true)
f
end
@testset "ERP plot with significance" begin
pvals = DataFrame(
from = [0.01, 0.2],
to = [0.3, 0.4],
coefname = ["(Intercept)", "condition: face"], # if coefname not specified, line should be black
)
plot_erp(results; :significance => pvals)
end
@testset "ERP plot: 7 channels faceted" begin
plot_erp(results7, mapping = (; col = :channel, group = :channel))
end
@testset "ERP plot: rename legend" begin
f = Figure()
results = coeftable(m)
results.coefname =
replace(results.coefname, "condition: face" => "face", "(Intercept)" => "car")
results = filter(row -> row.coefname != "continuous", results)
plot_erp!(
f,
results;
axis = (title = "Bad example", titlegap = 12),
mapping = (; color = :coefname => "Conditions"),
)
f
end
@testset "ERP plot: Facet sorting" begin
data, evts = UnfoldSim.predef_eeg()
m = fit(
UnfoldModel,
[
"car" => (@formula(0 ~ 1 + continuous), firbasis((-0.1, 1), 100)),
"face" => (@formula(0 ~ 1 + continuous), firbasis((-0.1, 1), 100)),
],
evts,
data;
eventcolumn = :condition,
)
eff = effects(Dict(:continuous => 75:20:300), m)
sorting1 = ["face", "car"] # check
sorting2 = ["car", "face"]
f = Figure()
plot_erp!(
f[1, 1],
eff;
mapping = (;
col = :eventname => sorter(sorting1),
color = :continuous,
group = :continuous,
),
)
plot_erp!(
f[2, 1],
eff;
mapping = (;
col = :eventname => sorter(sorting2),
color = :continuous,
group = :continuous,
),
)
f
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 3253 | using Unfold: eventnames
using AlgebraOfGraphics: group
include("../docs/example_data.jl")
m = example_data("UnfoldLinearModel")
res_effects = effects(Dict(:continuous => -5:0.5:5), m)
res_effects2 = effects(Dict(:condition => ["car", "face"], :continuous => -5:5), m)
@testset "Effect plot" begin
plot_erp(res_effects; mapping = (; y = :yhat, color = :continuous, group = :continuous))
end
@testset "Effect plot: faceted" begin
res_effects = effects(Dict(:continuous => -5:0.5:5), m)
res_effects.channel = push!(repeat(["1", "2"], 472), "1")
plot_erp(
res_effects;
mapping = (; y = :yhat, color = :continuous => nonnumeric, col = :channel),
legend = (; nbanks = 2),
)
end
@testset "Effect plot: faceted channels" begin #bug
res_effects = effects(Dict(:continuous => -5:0.5:5), m)
res_effects.channel = push!(repeat(["1", "2"], 472), "1")
plot_erp(
res_effects;
mapping = (;
y = :yhat,
color = :continuous => nonnumeric,
group = :channel,
col = :channel => nonnumeric,
),
legend = (; nbanks = 2),
)
end
@testset "Effect plot: no colorbar and yes legend" begin
plot_erp(
res_effects2;
mapping = (; color = :continuous, linestyle = :condition, group = :continuous),
layout = (; use_legend = true, use_colorbar = false),
)
end
@testset "Effect plot: yes colorbar and no legend" begin
plot_erp(
res_effects2;
mapping = (; color = :continuous, linestyle = :condition, group = :continuous),
layout = (; use_legend = false, use_colorbar = true),
)
end
@testset "Effect plot: yes colorbar and yes legend" begin
plot_erp(
res_effects2;
mapping = (; color = :continuous, linestyle = :condition, group = :continuous),
layout = (; use_legend = true, use_colorbar = true),
)
end
@testset "Effect plot: no colorbar and no legend" begin
plot_erp(
res_effects2;
mapping = (; color = :continuous, linestyle = :condition, group = :continuous),
layout = (; use_legend = false, use_colorbar = false),
)
end
@testset "Effect plot: move legend" begin
plot_erp(
res_effects2;
mapping = (; color = :continuous, linestyle = :condition, group = :continuous),
legend = (; valign = :bottom, halign = :right),
axis = (
title = "Marginal effects",
titlegap = 12,
xlabel = "Time [s]",
ylabel = "Amplitude [μV]",
xlabelsize = 16,
ylabelsize = 16,
xgridvisible = false,
ygridvisible = false,
),
)
end
@testset "Effect plot: xlabelvisible is not working" begin
eff_same = effects(Dict(:condition => ["car", "face"], :duration => 200), m)
plot_erp(results; axis = (; xlabelvisible = false, xticklabelsvisible = false))
plot_erp(
eff_same;
mapping = (; col = :condition, color = :time),
axis = (;
xlabel = "test",
titlevisible = false,
xlabelvisible = false,
ylabelvisible = false,
yticklabelsvisible = false,
xticklabelsvisible = false,
),
)
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
|
[
"MIT"
] | 0.5.8 | a24dcd72b75b13a7d8a90c21a4a1d1a23e6db576 | code | 2695 | data, pos = TopoPlots.example_data()
data = data[:, :, 1]
df, pos2 = example_data("TopoPlots.jl")
@testset "erpgrid: one plot is out of the border" begin
plot_erpgrid(data[1:3, :], pos[1:3])
end
@testset "erpgrid: data input with Matrix" begin
plot_erpgrid(data[1:6, :], pos[1:6])
end
@testset "erpgrid: data input with DataFrame" begin
df2 = unstack(df[:, [:estimate, :time, :channel]], :channel, :time, :estimate)
select!(df2, Not(:channel))
plot_erpgrid(df2, pos)
end
@testset "erpgrid: drawlabels" begin
plot_erpgrid(data, pos; drawlabels = true)
end
@testset "erpgrid: drawlabels with user_defined channel names" begin
plot_erpgrid(data[1:6, :], pos[1:6], raw_ch_names[1:6]; drawlabels = true)
end
@testset "erpgrid: customizable labels" begin
plot_erpgrid(
data[1:6, :],
pos[1:6],
raw_ch_names[1:6];
drawlabels = true,
labels_grid_axis = (; color = :red),
)
end
@testset "erpgrid: customizable vlines and hlines" begin
plot_erpgrid(
data[1:6, :],
pos[1:6],
raw_ch_names[1:6];
hlines_grid_axis = (; color = :red),
vlines_grid_axis = (; color = :green),
)
end
@testset "erpgrid: customizable lines" begin
plot_erpgrid(
data[1:6, :],
pos[1:6],
raw_ch_names[1:6];
lines_grid_axis = (; color = :red),
)
end
@testset "erpgrid: GridPosition" begin
f = Figure()
plot_erpgrid!(f[1, 1], data, pos)
f
end
@testset "erpgrid: change x and y labels" begin
f = Figure()
plot_erpgrid!(f[1, 1], data, pos; axis = (; xlabel = "s", ylabel = "µV"))
f
end
@testset "erpgrid: GridLayout" begin
f = Figure(size = (1200, 1400))
ga = f[1, 1] = GridLayout()
gb = f[2, 1] = GridLayout()
gd = f[2, 2] = GridLayout()
gc = f[3, 1] = GridLayout()
ge = f[4, 1] = GridLayout()
plot_erpgrid!(gb, data, pos; axis = (; xlabel = "s", ylabel = "µV"))
for (label, layout) in zip(["A", "B", "C", "D", "E"], [ga, gb, gc, gd, ge])
Label(
layout[1, 1, TopLeft()],
label,
fontsize = 26,
font = :bold,
padding = (0, 20, 22, -10),
halign = :right,
)
end
f
end
@testset "erpgrid: error of unequal data and positions" begin
err1 = nothing
t() = error(plot_erpgrid(data[1:6, :], pos[1:7], raw_ch_names[1:6]; drawlabels = true))
try
t()
catch err1
end
end
@testset "erpgrid: error of unequal ch_names and positions" begin
err1 = nothing
t() = error(plot_erpgrid(data[1:6, :], pos[1:6], raw_ch_names[1:7]; drawlabels = true))
try
t()
catch err1
end
end
| UnfoldMakie | https://github.com/unfoldtoolbox/UnfoldMakie.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.