licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 14931 |
#############################################################
# Lidar Sensor
#TODO move to a separate repo (AutomotiveSensors.jl)
mutable struct LidarSensor
angles::Vector{Float64}
ranges::Vector{Float64}
range_rates::Vector{Float64}
max_range::Float64
poly::ConvexPolygon
end
function LidarSensor(nbeams::Int;
max_range::Float64=100.0,
angle_offset::Float64=0.0,
angle_spread::Float64=2*pi,
)
if nbeams > 1
angles = collect(range(angle_offset-angle_spread/2, stop=angle_offset + angle_spread/2, length=nbeams+1))[2:end]
else
angles = Float64[]
nbeams = 0
end
ranges = Array{Float64}(undef, nbeams)
range_rates = Array{Float64}(undef, nbeams)
LidarSensor(angles, ranges, range_rates, max_range, ConvexPolygon(4))
end
nbeams(lidar::LidarSensor) = length(lidar.angles)
function observe!(lidar::LidarSensor, scene::Scene{E}, roadway::Roadway, vehicle_index::Int) where {E<:Entity}
state_ego = scene[vehicle_index].state
egoid = scene[vehicle_index].id
ego_vel = polar(vel(state_ego), posg(state_ego).θ)
# precompute the set of vehicles within max_range of the vehicle
in_range_ids = Set()
for veh in scene
if veh.id != egoid
distance = norm(VecE2(posg(state_ego) - posg(veh.state)))
# account for the length and width of the vehicle by considering
# the worst case where their maximum radius is aligned
distance = distance - hypot(length(veh.def)/2.,width(veh.def)/2.)
if distance < lidar.max_range
push!(in_range_ids, veh.id)
end
end
end
# compute range and range_rate for each angle
for (i,angle) in enumerate(lidar.angles)
ray_angle = posg(state_ego).θ + angle
ray_vec = polar(1.0, ray_angle)
ray = VecSE2(posg(state_ego).x, posg(state_ego).y, ray_angle)
range = lidar.max_range
range_rate = 0.0
for veh in scene
# only consider the set of potentially in range vehicles
if in(veh.id, in_range_ids)
to_oriented_bounding_box!(lidar.poly, veh)
range2 = AutomotiveSimulator.get_collision_time(ray, lidar.poly, 1.0)
if !isnan(range2) && range2 < range
range = range2
relative_speed = polar(vel(veh.state), posg(veh.state).θ) - ego_vel
range_rate = proj(relative_speed, ray_vec, Float64)
end
end
end
lidar.ranges[i] = range
lidar.range_rates[i] = range_rate
end
lidar
end
# function render_lidar!(rendermodel::RenderModel, lidar::LidarSensor, posG::VecSE2{Float64};
# color::Colorant=colorant"white",
# line_width::Float64 = 0.05,
# )
# for (angle, range, range_rate) in zip(lidar.angles, lidar.ranges, lidar.range_rates)
# ray = VecSE2(posG.x, posG.y, posG.θ + angle)
# t = 2 / (1 + exp(-range_rate))
# ray_color = t > 1.0 ? lerp(RGBA(1.0,1.0,1.0,0.5), RGBA(0.2,0.2,1.0,0.5), t/2) :
# lerp(RGBA(1.0,0.2,0.2,0.5), RGBA(1.0,1.0,1.0,0.5), t)
# render_ray!(rendermodel::RenderModel, ray, color=ray_color, length=range, line_width=line_width)
# end
# rendermodel
# end
#############################################################
# Road Line Lidar Sensor
mutable struct RoadlineLidarSensor
angles::Vector{Float64}
ranges::Matrix{Float64} # [n_lanes by nbeams]
max_range::Float64
poly::ConvexPolygon
end
nbeams(lidar::RoadlineLidarSensor) = length(lidar.angles)
nlanes(lidar::RoadlineLidarSensor) = size(lidar.ranges, 1)
function RoadlineLidarSensor(nbeams::Int;
max_range::Float64=100.0,
max_depth::Int=2,
angle_offset::Float64=0.0,
)
if nbeams > 1
angles = collect(range(angle_offset, stop=2*pi+angle_offset, length=nbeams+1))[2:end]
else
angles = Float64[]
nbeams = 0
end
ranges = Array{Float64}(undef, max_depth, nbeams)
RoadlineLidarSensor(angles, ranges, max_range, ConvexPolygon(4))
end
function _update_lidar!(lidar::RoadlineLidarSensor, ray::VecSE2{Float64}, beam_index::Int, p_lo::VecE2, p_hi::VecE2)
test_range = get_intersection_time(Projectile(ray, 1.0),
AutomotiveSimulator.LineSegment(p_lo, p_hi))
if !isnan(test_range)
n_ranges = size(lidar.ranges, 1)
for k in 1 : n_ranges
if test_range < lidar.ranges[k,beam_index]
for l in k+1 : n_ranges
lidar.ranges[l,beam_index] = lidar.ranges[l-1,beam_index]
end
lidar.ranges[k,beam_index] = test_range
break
end
end
end
lidar
end
function _update_lidar!(lidar::RoadlineLidarSensor, ray::VecSE2{Float64}, beam_index::Int, lane::Lane, roadway::Roadway; check_right_lane::Bool=false)
halfwidth = lane.width/2
Δ = check_right_lane ? -π/2 : π/2
p_lo = convert(VecE2, lane.curve[1].pos + polar(halfwidth, lane.curve[1].pos.θ + Δ))
for j in 2:length(lane.curve)
p_hi = convert(VecE2, lane.curve[j].pos + polar(halfwidth, lane.curve[j].pos.θ + Δ))
_update_lidar!(lidar, ray, beam_index, p_lo, p_hi)
p_lo = p_hi
end
if has_next(lane)
lane2 = next_lane(lane, roadway)
pt = lane2.curve[1]
p_hi = convert(VecE2, pt.pos + polar(lane2.width/2, pt.pos.θ + Δ))
_update_lidar!(lidar, ray, beam_index, p_lo, p_hi)
end
lidar
end
function _update_lidar!(lidar::RoadlineLidarSensor, ray::VecSE2{Float64}, beam_index::Int, roadway::Roadway)
for seg in roadway.segments
for lane in seg.lanes
# always check the left lane marking
_update_lidar!(lidar, ray, beam_index, lane, roadway)
# only check the right lane marking if this is the first lane
if lane.tag.lane == 1
_update_lidar!(lidar, ray, beam_index, lane, roadway, check_right_lane=true)
end
end
end
lidar
end
function observe!(lidar::RoadlineLidarSensor, scene::Scene{E}, roadway::Roadway, vehicle_index::Int) where E<:Entity
state_ego = scene[vehicle_index].state
egoid = scene[vehicle_index].id
ego_vel = polar(vel(state_ego), posg(state_ego).θ)
fill!(lidar.ranges, lidar.max_range)
for (beam_index,angle) in enumerate(lidar.angles)
ray_angle = posg(state_ego).θ + angle
ray = VecSE2(posg(state_ego).x, posg(state_ego).y, ray_angle)
_update_lidar!(lidar, ray, beam_index, roadway)
end
lidar
end
# function render_lidar!(rendermodel::RenderModel, lidar::RoadlineLidarSensor, posG::VecSE2{Float64};
# color::Colorant=RGBA(1.0,1.0,1.0,0.5),
# line_width::Float64 = 0.05,
# depth_level::Int = 1, # if 1, render first lanes struck by beams, if 2 render 2nd ...
# )
# for (angle, range) in zip(lidar.angles, lidar.ranges[depth_level,:])
# ray = VecSE2(posG.x, posG.y, posG.θ + angle)
# render_ray!(rendermodel::RenderModel, ray, color=color, length=range, line_width=line_width)
# end
# rendermodel
# end
#############################################################
# Road Line Lidar Culling
struct LanePortion
tag::LaneTag
curveindex_lo::Int
curveindex_hi::Int
end
mutable struct RoadwayLidarCulling
is_leaf::Bool
x_lo::Float64
x_hi::Float64
y_lo::Float64
y_hi::Float64
top_left::RoadwayLidarCulling
top_right::RoadwayLidarCulling
bot_left::RoadwayLidarCulling
bot_right::RoadwayLidarCulling
lane_portions::Vector{LanePortion}
function RoadwayLidarCulling(x_lo::Float64, x_hi::Float64, y_lo::Float64, y_hi::Float64, lane_portions::Vector{LanePortion})
retval = new()
retval.is_leaf = true
retval.x_lo = x_lo
retval.x_hi = x_hi
retval.y_lo = y_lo
retval.y_hi = y_hi
retval.lane_portions = lane_portions
retval
end
function RoadwayLidarCulling(x_lo::Float64, x_hi::Float64, y_lo::Float64, y_hi::Float64,
top_left::RoadwayLidarCulling,
top_right::RoadwayLidarCulling,
bot_left::RoadwayLidarCulling,
bot_right::RoadwayLidarCulling,)
retval = new()
retval.is_leaf = false
retval.x_lo = x_lo
retval.x_hi = x_hi
retval.y_lo = y_lo
retval.y_hi = y_hi
retval.top_left = top_left
retval.top_right = top_right
retval.bot_left = bot_left
retval.bot_right = bot_right
retval
end
end
RoadwayLidarCulling() = RoadwayLidarCulling(typemax(Float64), typemin(Float64), typemax(Float64), typemin(Float64), LanePortion[])
function Base.get(rlc::RoadwayLidarCulling, x::Real, y::Real)
if rlc.is_leaf
return rlc
else
if y < (rlc.y_lo + rlc.y_hi)/2
if x < (rlc.x_lo + rlc.x_hi)/2
return get(rlc.bot_left, x, y)
else
return get(rlc.bot_right, x, y)
end
else
if x < (rlc.x_lo + rlc.x_hi)/2
return get(rlc.top_left, x, y)
else
return get(rlc.top_right, x, y)
end
end
end
end
function ensure_leaf_in_rlc!(rlc::RoadwayLidarCulling, x::Real, y::Real, fidelity_x::Real, fidelity_y::Real)
leaf = get(rlc, x, y)
@assert(leaf.is_leaf)
x_lo, x_hi = leaf.x_lo, leaf.x_hi
y_lo, y_hi = leaf.y_lo, leaf.y_hi
while (x_hi - x_lo) > fidelity_x || (y_hi - y_lo) > fidelity_y # drill down
x_mid = (x_hi + x_lo)/2
y_mid = (y_hi + y_lo)/2
leaf.top_left = RoadwayLidarCulling(x_lo, x_mid, y_mid, y_hi, LanePortion[])
leaf.top_right = RoadwayLidarCulling(x_mid, x_hi, y_mid, y_hi, LanePortion[])
leaf.bot_left = RoadwayLidarCulling(x_lo, x_mid, y_lo, y_mid, LanePortion[])
leaf.bot_right = RoadwayLidarCulling(x_mid, x_hi, y_lo, y_mid, LanePortion[])
leaf.is_leaf = false
leaf = get(leaf, x, y)
x_lo, x_hi = leaf.x_lo, leaf.x_hi
y_lo, y_hi = leaf.y_lo, leaf.y_hi
end
rlc
end
function get_lane_portions(roadway::Roadway, x::Real, y::Real, lane_portion_max_range::Float64)
P = VecE2(x, y)
Δ² = lane_portion_max_range*lane_portion_max_range
lane_portions = LanePortion[]
for seg in roadway.segments
for lane in seg.lanes
f = curvept -> normsquared(VecE2(curvept.pos - P)) ≤ Δ²
i = findfirst(f, lane.curve)
if i != nothing
j = findlast(f, lane.curve)
@assert(j != nothing)
push!(lane_portions, LanePortion(lane.tag, i, j))
end
end
end
lane_portions
end
function RoadwayLidarCulling(
roadway::Roadway,
lane_portion_max_range::Float64, # lane portions will be extracted such that points within lane_portion_max_range are in the leaves
culling_fidelity::Float64, # the culling will drill down until Δx, Δy < culling_fidelity
)
#=
1 - get area bounds
2 - ensure all points in rlc
3 - for each leaf, construct all lane portions
=#
# get area bounds
x_lo = typemax(Float64)
x_hi = typemin(Float64)
y_lo = typemax(Float64)
y_hi = typemin(Float64)
for seg in roadway.segments
for lane in seg.lanes
for curvept in lane.curve
pos = curvept.pos
x_lo = min(pos.x, x_lo)
x_hi = max(pos.x, x_hi)
y_lo = min(pos.y, y_lo)
y_hi = max(pos.y, y_hi)
end
end
end
x_lo -= lane_portion_max_range
x_hi += lane_portion_max_range
y_lo -= lane_portion_max_range
y_hi += lane_portion_max_range
root = RoadwayLidarCulling(x_lo, x_hi, y_lo, y_hi, LanePortion[])
# ensure all points are in rlc
x = x_lo - culling_fidelity
while x < x_hi
x += culling_fidelity
y = y_lo - culling_fidelity
while y < y_hi
y += culling_fidelity
ensure_leaf_in_rlc!(root, x, y, culling_fidelity, culling_fidelity)
end
end
nodes = RoadwayLidarCulling[root]
while !isempty(nodes)
node = pop!(nodes)
if node.is_leaf
x = (node.x_lo + node.x_hi)/2
y = (node.y_lo + node.y_hi)/2
append!(node.lane_portions, get_lane_portions(roadway, x, y, lane_portion_max_range))
else
push!(nodes, node.top_left)
push!(nodes, node.top_right)
push!(nodes, node.bot_left)
push!(nodes, node.bot_right)
end
end
root
end
function _update_lidar!(
lidar::RoadlineLidarSensor,
ray::VecSE2{Float64},
beam_index::Int,
roadway::Roadway,
lane_portion::LanePortion;
check_right_lane::Bool=false
)
lane = roadway[lane_portion.tag]
halfwidth = lane.width/2
Δ = check_right_lane ? -π/2 : π/2
p_lo = convert(VecE2, lane.curve[lane_portion.curveindex_lo].pos +
polar(halfwidth, lane.curve[lane_portion.curveindex_lo].pos.θ + Δ))
for j in lane_portion.curveindex_lo+1:lane_portion.curveindex_hi
p_hi = convert(VecE2, lane.curve[j].pos + polar(halfwidth, lane.curve[j].pos.θ + Δ))
_update_lidar!(lidar, ray, beam_index, p_lo, p_hi)
p_lo = p_hi
end
if lane_portion.curveindex_hi == length(lane.curve) && has_next(lane)
lane2 = next_lane(lane, roadway)
pt = lane2.curve[1]
p_hi = convert(VecE2, pt.pos + polar(lane2.width/2, pt.pos.θ + Δ))
_update_lidar!(lidar, ray, beam_index, p_lo, p_hi)
end
lidar
end
function _update_lidar!(lidar::RoadlineLidarSensor, ray::VecSE2{Float64}, beam_index::Int, roadway::Roadway, rlc::RoadwayLidarCulling)
leaf = get(rlc, ray.x, ray.y)
for lane_portion in leaf.lane_portions
# always update the left lane marking
_update_lidar!(lidar, ray, beam_index, roadway, lane_portion)
# only check the right lane marking if this is the first lane
if lane_portion.tag.lane == 1
_update_lidar!(lidar, ray, beam_index, roadway, lane_portion, check_right_lane=true)
end
end
lidar
end
function observe!(lidar::RoadlineLidarSensor, scene::Scene{E}, roadway::Roadway, vehicle_index::Int, rlc::RoadwayLidarCulling) where E<:Entity
state_ego = scene[vehicle_index].state
egoid = scene[vehicle_index].id
ego_vel = polar(vel(state_ego), posg(state_ego).θ)
fill!(lidar.ranges, lidar.max_range)
for (beam_index,angle) in enumerate(lidar.angles)
ray_angle = posg(state_ego).θ + angle
ray = VecSE2(posg(state_ego).x, posg(state_ego).y, ray_angle)
_update_lidar!(lidar, ray, beam_index, roadway, rlc)
end
lidar
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 14699 | """
NeighborLongitudinalResult
A structure to retrieve information about a neihbor in the longitudinal direction i.e. rear and front neighbors on the same lane.
If the neighbor index is equal to `nothing` it means there is no neighbor.
# Fields
- `ind::Union{Nothing, Int64}` index of the neighbor in the scene
- `Δs::Float64` positive distance along the lane between vehicles positions
"""
struct NeighborLongitudinalResult
ind::Union{Nothing, Int64} # index in scene of the neighbor
Δs::Float64 # positive distance along lane between vehicles' positions
end
"""
VehicleTargetPoint
Defines a point on an entity that is used to measure distances.
The following target points are supported and are subtypes of VehicleTargetPoint:
- `VehicleTargetPointFront`
- `VehicleTargetPointCenter`
- `VehicleTargetPointRear`
The method `targetpoint_delta(::VehicleTargetPoint, ::Entity)` can be used to
compute the delta in the longitudinal direction to add when considering a specific target point.
"""
abstract type VehicleTargetPoint end
"""
VehicleTargetPointFront <: VehicleTargetPoint
Set the target point at the front (and center) of the entity.
"""
struct VehicleTargetPointFront <: VehicleTargetPoint end
targetpoint_delta(::VehicleTargetPointFront, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition, I} = length(veh.def)/2*cos(posf(veh.state).ϕ)
"""
VehicleTargetPointCenter <: VehicleTargetPoint
Set the target point at the center of the entity.
"""
struct VehicleTargetPointCenter <: VehicleTargetPoint end
targetpoint_delta(::VehicleTargetPointCenter, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition, I} = 0.0
"""
VehicleTargetPointFront <: VehicleTargetPoint
Set the target point at the front (and center) of the entity.
"""
struct VehicleTargetPointRear <: VehicleTargetPoint end
targetpoint_delta(::VehicleTargetPointRear, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition, I} = -length(veh.def)/2*cos(posf(veh.state).ϕ)
const VEHICLE_TARGET_POINT_CENTER = VehicleTargetPointCenter()
"""
find_neighbor(scene::Scene, roadway::Roawday, ego::Entity; kwargs...)
Search through lanes and road segments to find a neighbor of `ego` in the `scene`.
Returns a `NeighborLongitudinalResult` object with the index of the neighbor in the scene and its relative distance.
# Arguments
- `scene::Scene` the scene containing all the entities
- `roadway::Roadway` the road topology on which entities are driving
- `ego::Entity` the entity that we want to compute the neighbor of.
# Keyword arguments
- `lane::Union{Nothing, Lane}` the lane on which to search the neighbor, if different from the ego vehicle current lane, it uses the projection of the ego vehicle on the given lane as a reference point. If nothing, returns nothing.
- `rear::Bool = false` set to true to search for rear neighbor, search forward neighbor by default
- `max_distance::Float64 = 250.0` stop searching after this distance is reached, if the neighbor is further than max_distance, returns nothing
- `targetpoint_ego::VehicleTargetPoint` the point on the ego vehicle used for distance calculation, see `VehicleTargetPoint` for more info
- `targetpoint_neighbor::VehicleTargetPoint` the point on the neighbor vehicle used for distance calculation, see `VehicleTargetPoint` for more info
- `ids_to_ignore::Union{Nothing, Set{I}} = nothing` a list of entity ids to ignore for the search, ego is always ignored.
"""
function find_neighbor(scene::Scene, roadway::Roadway, ego::Entity{S,D,I};
lane::Union{Nothing, Lane} = get_lane(roadway, ego),
rear::Bool=false,
max_distance::Float64=250.0,
targetpoint_ego::VehicleTargetPoint = VehicleTargetPointCenter(),
targetpoint_neighbor::VehicleTargetPoint = VehicleTargetPointCenter(),
ids_to_ignore::Union{Nothing, Set{I}} = nothing) where {S,D,I}
if lane === nothing
return NeighborLongitudinalResult(nothing, max_distance)
elseif get_lane(roadway, ego).tag == lane.tag
tag_start = lane.tag
s_start = posf(ego.state).s
else # project ego on desired lane
roadproj = proj(posg(ego.state), lane, roadway)
roadind = RoadIndex(roadproj)
tag_start = roadproj.tag
s_start = roadway[roadind].s
end
s_base = s_start + targetpoint_delta(targetpoint_ego, ego)
tag_target = tag_start
best_ind = nothing
best_dist = max_distance
dist_searched = 0.0
while dist_searched < max_distance
curr_lane = roadway[tag_target]
for (i, veh) in enumerate(scene)
if veh.id == ego.id
continue
end
if ids_to_ignore !== nothing && veh.id ∈ ids_to_ignore
continue
end
# check if veh is on thislane
s_adjust = NaN
if get_lane(roadway, veh).tag == curr_lane.tag
s_adjust = 0.0
elseif is_between_segments_hi(posf(veh.state).roadind.ind, curr_lane.curve) &&
is_in_entrances(roadway[tag_target], posf(veh.state).roadind.tag)
distance_between_lanes = norm(VecE2(roadway[tag_target].curve[1].pos - roadway[posf(veh.state).roadind.tag].curve[end].pos))
s_adjust = -(roadway[posf(veh.state).roadind.tag].curve[end].s + distance_between_lanes)
elseif is_between_segments_lo(posf(veh.state).roadind.ind) &&
is_in_exits(roadway[tag_target], posf(veh.state).roadind.tag)
distance_between_lanes = norm(VecE2(roadway[tag_target].curve[end].pos - roadway[posf(veh.state).roadind.tag].curve[1].pos))
s_adjust = roadway[tag_target].curve[end].s + distance_between_lanes
end
if !isnan(s_adjust)
s_valid = posf(veh.state).s + targetpoint_delta(targetpoint_neighbor, veh) + s_adjust
if rear
dist_valid = s_base - s_valid + dist_searched
else
dist_valid = s_valid - s_base + dist_searched
end
if dist_valid ≥ 0.0
s_primary = posf(veh.state).s + targetpoint_delta(targetpoint_neighbor, veh) + s_adjust
if rear
dist= s_base - s_primary + dist_searched
else
dist = s_primary - s_base + dist_searched
end
if dist < best_dist
best_dist = dist
best_ind = i
end
end
end
end
# neighbor has been found exit
if best_ind != nothing
break
end
# no next lane and no neighbor found exit
if !has_next(curr_lane) ||
(tag_target == tag_start && dist_searched != 0.0) # exit after visiting this lane a 2nd time
break
end
# go to the connected lane.
if rear
dist_searched += s_base
s_base = curr_lane.curve[end].s + norm(VecE2(lane.curve[end].pos - prev_lane_point(curr_lane, roadway).pos))
tag_target = prev_lane(lane, roadway).tag
else
dist_searched += (curr_lane.curve[end].s - s_base)
s_base = -norm(VecE2(curr_lane.curve[end].pos - next_lane_point(curr_lane, roadway).pos)) # negative distance between lanes
tag_target = next_lane(curr_lane, roadway).tag
end
end
return NeighborLongitudinalResult(best_ind, best_dist)
end
"""
FrenetRelativePosition
Contains information about the projection of a point on a lane. See `get_frenet_relative_position`.
# Fields
- `origin::RoadIndex` original roadindex used for the projection, contains the target lane ID.
- `target::RoadIndex` roadindex reached after projection
- `Δs::Float64` longitudinal distance to the original roadindex
- `t::Float64` lateral distance to the original roadindex in the frame of the target lane
- `ϕ::Float64` angle with the original roadindex in the frame of the target lane
"""
struct FrenetRelativePosition
origin::RoadIndex
target::RoadIndex
Δs::Float64
t::Float64
ϕ::Float64
end
"""
get_frenet_relative_position(veh_fore::Entity, veh_rear::Entity, roadway::Roadway)
return the Frenet relative position between the two vehicles. It projects the position of the first vehicle onto the lane of the second vehicle.
The result is stored as a `FrenetRelativePosition`.
Lower level:
get_frenet_relative_position(posG::VecSE2{Float64}, roadind::RoadIndex, roadway::Roadway;
max_distance_fore::Float64 = 250.0, # max distance to search forward [m]
max_distance_rear::Float64 = 250.0, # max distance to search backward [m]
improvement_threshold::Float64 = 1e-4,
)
Project the given point to the same lane as the given RoadIndex.
This will return the projection of the point, along with the Δs along the lane from the RoadIndex.
The returned type is a `FrenetRelativePosition` object.
"""
function get_frenet_relative_position(posG::VecSE2{Float64}, roadind::RoadIndex, roadway::Roadway;
max_distance_fore::Float64 = 250.0, # max distance to search forward [m]
max_distance_rear::Float64 = 250.0, # max distance to search backward [m]
improvement_threshold::Float64 = 1e-4,
)
# project to current lane first
tag_start = roadind.tag
lane_start = roadway[tag_start]
curveproj_start = proj(posG, lane_start, roadway, move_along_curves=false).curveproj
curvept_start = lane_start[curveproj_start.ind, roadway]
s_base = lane_start[roadind.ind, roadway].s
s_proj = curvept_start.s
Δs = s_proj - s_base
sq_dist_to_curve = normsquared(VecE2(posG - curvept_start.pos))
retval = FrenetRelativePosition(roadind,
RoadIndex(curveproj_start.ind, tag_start), Δs, curveproj_start.t, curveproj_start.ϕ)
# search downstream
if has_next(lane_start)
dist_searched = lane_start.curve[end].s - s_base
s_base = -norm(VecE2(lane_start.curve[end].pos - next_lane_point(lane_start, roadway).pos)) # negative distance between lanes
tag_target = next_lane(lane_start, roadway).tag
while dist_searched < max_distance_fore
lane = roadway[tag_target]
curveproj = proj(posG, lane, roadway, move_along_curves=false).curveproj
sq_dist_to_curve2 = normsquared(VecE2(posG - lane[curveproj.ind, roadway].pos))
if sq_dist_to_curve2 < sq_dist_to_curve - improvement_threshold
sq_dist_to_curve = sq_dist_to_curve2
s_proj = lane[curveproj.ind, roadway].s
Δs = s_proj - s_base + dist_searched
retval = FrenetRelativePosition(
roadind, RoadIndex(curveproj.ind, tag_target),
Δs, curveproj.t, curveproj.ϕ)
end
if !has_next(lane)
break
end
dist_searched += (lane.curve[end].s - s_base)
s_base = -norm(VecE2(lane.curve[end].pos - next_lane_point(lane, roadway).pos)) # negative distance between lanes
tag_target = next_lane(lane, roadway).tag
if tag_target == tag_start
break
end
end
end
# search upstream
if has_prev(lane_start)
dist_searched = s_base
tag_target = prev_lane(lane_start, roadway).tag
s_base = roadway[tag_target].curve[end].s + norm(VecE2(lane_start.curve[1].pos - prev_lane_point(lane_start, roadway).pos)) # end of the lane
while dist_searched < max_distance_fore
lane = roadway[tag_target]
curveproj = proj(posG, lane, roadway, move_along_curves=false).curveproj
sq_dist_to_curve2 = normsquared(VecE2(posG - lane[curveproj.ind, roadway].pos))
if sq_dist_to_curve2 < sq_dist_to_curve - improvement_threshold
sq_dist_to_curve = sq_dist_to_curve2
s_proj = lane[curveproj.ind, roadway].s
dist = s_base - s_proj + dist_searched
Δs = -dist
retval = FrenetRelativePosition(
roadind, RoadIndex(curveproj.ind, tag_target),
Δs, curveproj.t, curveproj.ϕ)
end
if !has_prev(lane)
break
end
dist_searched += s_base
s_base = lane.curve[end].s + norm(VecE2(lane.curve[1].pos - prev_lane_point(lane, roadway).pos)) # length of this lane plus crossover
tag_target = prev_lane(lane, roadway).tag
if tag_target == tag_start
break
end
end
end
retval
end
get_frenet_relative_position(veh_fore::Entity{S, D, I}, veh_rear::Entity{S, D, I}, roadway::Roadway) where {S,D, I} = get_frenet_relative_position(posg(veh_fore.state), posf(veh_rear.state).roadind, roadway)
"""
dist_to_front_neighbor(roadway::Roadway, scene::Scene, veh::Entity)
Feature function to extract the longitudinal distance to the front neighbor (in the Frenet frame).
Returns `missing` if there are no front neighbor.
"""
function dist_to_front_neighbor(roadway::Roadway, scene::Scene, veh::Entity)
neighbor = find_neighbor(scene, roadway, veh)
if neighbor.ind === nothing
return missing
else
return neighbor.Δs
end
end
"""
front_neighbor_speed(roadway::Roadway, scene::Scene, veh::Entity)
Feature function to extract the velocity of the front neighbor.
Returns `missing` if there are no front neighbor.
"""
function front_neighbor_speed(roadway::Roadway, scene::Scene, veh::Entity)
neighbor = find_neighbor(scene, roadway, veh)
if neighbor.ind === nothing
return missing
else
return vel(scene[neighbor.ind])
end
end
"""
time_to_collision(roadway::Roadway, scene::Scene, veh::Entity)
Feature function to extract the time to collision with the front neighbor.
Returns `missing` if there are no front neighbor.
"""
function time_to_collision(roadway::Roadway, scene::Scene, veh::Entity)
neighbor = find_neighbor(scene, roadway, veh)
if neighbor.ind === nothing
return missing
else
len_ego = length(veh.def)
len_oth = length(scene[neighbor.ind].def)
Δs = neighbor.Δs - len_ego/2 - len_oth/2
Δv = vel(scene[neighbor.ind]) - vel(veh)
return -Δs / Δv
end
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 8399 | """
CurvePt{T}
describes a point on a curve, associated with a curvature and the derivative of the curvature
- `pos::VecSE2{T}` # global position and orientation
- `s::T` # distance along the curve
- `k::T` # curvature
- `kd::T` # derivative of curvature
"""
struct CurvePt{T}
pos::VecSE2{T} # global position and orientation
s::T # distance along the curve
k::T # curvature
kd::T# derivative of curvature
end
function CurvePt(pos::VecSE2{T}, s::T, k::T = convert(T, NaN)) where T
return CurvePt{T}(pos, s, k, convert(T, NaN))
end
Base.show(io::IO, pt::CurvePt) = @printf(io, "CurvePt({%.3f, %.3f, %.3f}, %.3f, %.3f, %.3f)", pt.pos.x, pt.pos.y, pt.pos.θ, pt.s, pt.k, pt.kd)
Vec.lerp(a::CurvePt, b::CurvePt, t::T) where T <: Real = CurvePt(lerp(a.pos, b.pos, t), a.s + (b.s - a.s)*t, a.k + (b.k - a.k)*t, a.kd + (b.kd - a.kd)*t)
############
"""
Curve{T}
is a vector of curve points
"""
const Curve{T} = Vector{CurvePt{T}} where T
"""
get_lerp_time_unclamped(A::VecE2, B::VecE2, Q::VecE2)
Get the interpolation scalar t for the point on the line AB closest to Q
This point is P = A + (B-A)*t
"""
function get_lerp_time_unclamped(A::VecE2, B::VecE2, Q::VecE2)
a = Q - A
b = B - A
c = proj(a, b, VecE2)
if b.x != 0.0
t = c.x / b.x
elseif b.y != 0.0
t = c.y / b.y
else
t = 0.0 # no lerping to be done
end
t
end
get_lerp_time_unclamped(A::VecSE2, B::VecSE2, Q::VecSE2) = get_lerp_time_unclamped(convert(VecE2, A), convert(VecE2, B), convert(VecE2, Q))
get_lerp_time_unclamped(A::CurvePt, B::CurvePt, Q::VecSE2) = get_lerp_time_unclamped(convert(VecE2, A.pos), convert(VecE2, B.pos), convert(VecE2, Q))
"""
get_lerp_time(A::VecE2, B::VecE2, Q::VecE2)
Get lerp time t∈[0,1] such that lerp(A, B) is as close as possible to Q
"""
get_lerp_time(A::VecE2, B::VecE2, Q::VecE2) = clamp(get_lerp_time_unclamped(A, B, Q), 0.0, 1.0)
get_lerp_time(A::CurvePt, B::CurvePt, Q::VecSE2) = get_lerp_time(convert(VecE2, A.pos), convert(VecE2, B.pos), convert(VecE2, Q))
"""
CurveIndex{I <: Integer, T <: Real}
Given a `Curve` object `curve` one can call `curve[ind]`
where `ind` is a `CurveIndex`. The field `t` can be used to interpolate between two
points in the curve.
# Fields
- `i`::I` index in the curve , ∈ [1:length(curve)-1]
- `t::T` ∈ [0,1] for linear interpolation
"""
struct CurveIndex{I <: Integer, T <: Real}
i::I # index in curve, ∈ [1:length(curve)-1]
t::T # ∈ [0,1] for linear interpolation
end
const CURVEINDEX_START = CurveIndex(1,0.0)
Base.show(io::IO, ind::CurveIndex) = @printf(io, "CurveIndex(%d, %.3f)", ind.i, ind.t)
curveindex_end(curve::Curve) = CurveIndex(length(curve)-1,1.0)
Base.getindex(curve::Curve, ind::CurveIndex) = lerp(curve[ind.i], curve[ind.i+1], ind.t)
"""
is_at_curve_end(ind::CurveIndex, curve::Curve)
returns true if the curve index is at the end of the curve
"""
function is_at_curve_end(ind::CurveIndex, curve::Curve)
(ind.i == 1 && ind.t == 0.0) ||
(ind.i == length(curve)-1 && ind.t == 1.0)
end
"""
index_closest_to_point(curve::Curve, target::AbstractVec)
returns the curve index closest to the point described by `target`.
`target` must be [x, y].
"""
function index_closest_to_point(curve::Curve, target::AbstractVec)
a = 1
b = length(curve)
c = div(a+b, 2)
@assert(length(curve) ≥ b)
sqdist_a = normsquared(VecE2(curve[a].pos - target))
sqdist_b = normsquared(VecE2(curve[b].pos - target))
sqdist_c = normsquared(VecE2(curve[c].pos - target))
while true
if b == a
return a
elseif b == a + 1
return sqdist_b < sqdist_a ? b : a
elseif c == a + 1 && c == b - 1
if sqdist_a < sqdist_b && sqdist_a < sqdist_c
return a
elseif sqdist_b < sqdist_a && sqdist_b < sqdist_c
return b
else
return c
end
end
left = div(a+c, 2)
sqdist_l = normsquared(VecE2(curve[left].pos - target))
right = div(c+b, 2)
sqdist_r = normsquared(VecE2(curve[right].pos - target))
if sqdist_l < sqdist_r
b = c
sqdist_b = sqdist_c
c = left
sqdist_c = sqdist_l
else
a = c
sqdist_a = sqdist_c
c = right
sqdist_c = sqdist_r
end
end
error("index_closest_to_point reached unreachable statement")
end
"""
get_curve_index(curve::Curve{T}, s::T) where T <: Real
Return the CurveIndex for the closest s-location on the curve
"""
function get_curve_index(curve::Curve{T}, s::T) where T <: Real
if s ≤ 0.0
return CURVEINDEX_START
elseif s ≥ curve[end].s
return curveindex_end(curve)
end
a = 1
b = length(curve)
fa = curve[a].s - s
fb = curve[b].s - s
n = 1
while true
if b == a+1
extind = a + -fa/(fb-fa)
ind = floor(Int, extind)
t = rem(extind, 1.0)
return CurveIndex(ind, t)
end
c = div(a+b, 2)
fc = curve[c].s - s
n += 1
if sign(fc) == sign(fa)
a, fa = c, fc
else
b, fb = c, fc
end
end
error("get_curve_index failed for s=$s")
end
"""
get_curve_index(ind::CurveIndex, curve::Curve, Δs::T) where T <: Real
Return the CurveIndex at ind's s position + Δs
"""
function get_curve_index(ind::CurveIndex, curve::Curve, Δs::T) where T <: Real
L = length(curve)
ind_lo, ind_hi = ind.i, ind.i+1
s_lo = curve[ind_lo].s
s_hi = curve[ind_hi].s
s = lerp(s_lo, s_hi, ind.t)
if Δs ≥ 0.0
if s + Δs ≥ s_hi && ind_hi < L
while s + Δs ≥ s_hi && ind_hi < L
Δs -= (s_hi - s)
s = s_hi
ind_lo += 1
ind_hi += 1
s_lo = curve[ind_lo].s
s_hi = curve[ind_hi].s
end
else
Δs = s + Δs - s_lo
end
t = Δs/(s_hi - s_lo)
CurveIndex(ind_lo, t)
else
while s + Δs < s_lo && ind_lo > 1
Δs += (s - s_lo)
s = s_lo
ind_lo -= 1
ind_hi -= 1
s_lo = curve[ind_lo].s
s_hi = curve[ind_hi].s
end
Δs = s + Δs - s_lo
t = Δs/(s_hi - s_lo)
CurveIndex(ind_lo, t)
end
end
"""
CurveProjection{I <: Integer, T <: Real}
The result of a point projected to a Curve
# Fields
- `ind::CurveIndex{I, T}`
- `t::T` lane offset
- `ϕ::T` lane-relative heading [rad]
"""
struct CurveProjection{I <: Integer, T <: Real}
ind::CurveIndex{I, T}
t::T # lane offset
ϕ::T # lane-relative heading [rad]
end
Base.show(io::IO, curveproj::CurveProjection) = @printf(io, "CurveProjection({%d, %.3f}, %.3f, %.3f)", curveproj.ind.i, curveproj.ind.t, curveproj.t, curveproj.ϕ)
function get_curve_projection(posG::VecSE2, footpoint::VecSE2, ind::CurveIndex)
F = inertial2body(posG, footpoint)
CurveProjection(ind, F.y, F.θ)
end
"""
Vec.proj(posG::VecSE2, curve::Curve)
Return a CurveProjection obtained by projecting posG onto the curve
"""
function Vec.proj(posG::VecSE2{T}, curve::Curve{T}) where T
ind = index_closest_to_point(curve, posG)
curveind = CurveIndex{Int64, T}(0,NaN)
footpoint = VecSE2{T}(NaN, NaN, NaN)
if ind > 1 && ind < length(curve)
t_lo = get_lerp_time(curve[ind-1], curve[ind], posG)
t_hi = get_lerp_time(curve[ind], curve[ind+1], posG)
p_lo = lerp(curve[ind-1].pos, curve[ind].pos, t_lo)
p_hi = lerp(curve[ind].pos, curve[ind+1].pos, t_hi)
d_lo = norm(VecE2(p_lo - posG))
d_hi = norm(VecE2(p_hi - posG))
if d_lo < d_hi
footpoint = p_lo
curveind = CurveIndex(ind-1, t_lo)
else
footpoint = p_hi
curveind = CurveIndex(ind, t_hi)
end
elseif ind == 1
t = get_lerp_time( curve[1], curve[2], posG )
footpoint = lerp( curve[1].pos, curve[2].pos, t)
curveind = CurveIndex(ind, t)
else # ind == length(curve)
t = get_lerp_time( curve[end-1], curve[end], posG )
footpoint = lerp( curve[end-1].pos, curve[end].pos, t)
curveind = CurveIndex(ind-1, t)
end
get_curve_projection(posG, footpoint, curveind)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 2573 | """
Frenet
Represents a vehicle position and heading in a lane relative frame.
# Constructors
- `Frenet(roadind::RoadIndex, roadway::Roadway; t::Float64=0.0, ϕ::Float64=0.0)`
- `Frenet(roadproj::RoadProjection, roadway::Roadway)`
- `Frenet(lane::Lane, s::Float64, t::Float64=0.0, ϕ::Float64=0.0)`
- `Frenet(posG::VecSE2, roadway::Roadway)`
- `Frenet(posG::VecSE2, lane::Lane, roadway::Roadway)`
# Fields
- `roadind`: road index
- `s`: distance along lane
- `t`: lane offset, positive is to left. zero point is the centerline of the lane.
- `ϕ`: lane relative heading
"""
struct Frenet
roadind::RoadIndex{Int64, Float64}
s::Float64 # distance along lane
t::Float64 # lane offset, positive is to left. zero point is the centerline of the lane.
ϕ::Float64 # lane relative heading
end
function Frenet(roadind::RoadIndex, roadway::Roadway; t::Float64=0.0, ϕ::Float64=0.0)
s = roadway[roadind].s
ϕ = _mod2pi2(ϕ)
Frenet(roadind, s, t, ϕ)
end
function Frenet(roadproj::RoadProjection, roadway::Roadway)
roadind = RoadIndex(roadproj.curveproj.ind, roadproj.tag)
s = roadway[roadind].s
t = roadproj.curveproj.t
ϕ = _mod2pi2(roadproj.curveproj.ϕ)
Frenet(roadind, s, t, ϕ)
end
function Frenet(lane::Lane, s::Float64, t::Float64=0.0, ϕ::Float64=0.0)
roadind = RoadIndex(get_curve_index(lane.curve, s), lane.tag)
return Frenet(roadind, s, t, ϕ)
end
Frenet(posG::VecSE2, roadway::Roadway) = Frenet(proj(posG, roadway), roadway)
Frenet(posG::VecSE2, lane::Lane, roadway::Roadway) = Frenet(proj(posG, lane, roadway), roadway)
# helper
function _mod2pi2(x::Float64)
val = mod2pi(x)
if val > pi
val -= 2pi
end
return val
end
"""
posg(frenet::Frenet, roadway::Roadway)
projects the Frenet position into the global frame
"""
function posg(frenet::Frenet, roadway::Roadway)
curvept = roadway[frenet.roadind]
pos = curvept.pos + polar(frenet.t, curvept.pos.θ + π/2)
VecSE2(pos.x, pos.y, frenet.ϕ + curvept.pos.θ)
end
const NULL_FRENET = Frenet(NULL_ROADINDEX, NaN, NaN, NaN)
Base.show(io::IO, frenet::Frenet) = print(io, "Frenet(", frenet.roadind, @sprintf(", %.3f, %.3f, %.3f)", frenet.s, frenet.t, frenet.ϕ))
function Base.isapprox(a::Frenet, b::Frenet;
rtol::Real=cbrt(eps(Float64)),
atol::Real=sqrt(eps(Float64))
)
a.roadind.tag == b.roadind.tag &&
isapprox(a.roadind.ind.t, b.roadind.ind.t, atol=atol, rtol=rtol) &&
isapprox(a.s, b.s, atol=atol, rtol=rtol) &&
isapprox(a.t, b.t, atol=atol, rtol=rtol) &&
isapprox(a.ϕ, b.ϕ, atol=atol, rtol=rtol)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 10268 | """
gen_straight_curve(A::VecE2{T}, B::VecE2{T}, nsamples::Integer) where T<:Real
Returns a `Curve` corresponding to a straight line between A and B. `nsamples` indicates the
number of points to place between A and B, if set to two, the curve will only contains A and B.
"""
function gen_straight_curve(A::VecE2{T}, B::VecE2{T}, nsamples::Integer) where T<:Real
θ = atan(B-A)
δ = norm(B-A)/(nsamples-1)
s = 0.0
curve = Array{CurvePt{T}}(undef, nsamples)
for i in 1 : nsamples
t = (i-1)/(nsamples-1)
P = lerp(A,B,t)
curve[i] = CurvePt(VecSE2(P.x,P.y,θ), s, 0.0)
s += δ
end
return curve
end
"""
gen_straight_segment(seg_id::Integer, nlanes::Integer, length::Float64=1000.0;
Generate a straight `RoadSegment` with `nlanes` number of lanes of length `length`.
"""
function gen_straight_segment(seg_id::Integer, nlanes::Integer, length::Float64=1000.0;
origin::VecSE2{Float64} = VecSE2(0.0,0.0,0.0),
lane_width::Float64=DEFAULT_LANE_WIDTH, # [m]
lane_widths::Vector{Float64} = fill(lane_width, nlanes),
boundary_leftmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_rightmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_middle::LaneBoundary=LaneBoundary(:broken, :white),
)
seg = RoadSegment(seg_id, Array{Lane{Float64}}(undef, nlanes))
y = -lane_widths[1]/2
for i in 1 : nlanes
y += lane_widths[i]/2
seg.lanes[i] = Lane(LaneTag(seg_id,i), [CurvePt(body2inertial(VecSE2( 0.0,y,0.0), origin), 0.0),
CurvePt(body2inertial(VecSE2(length,y,0.0), origin), length)],
width=lane_widths[i],
boundary_left=(i == nlanes ? boundary_leftmost : boundary_middle),
boundary_right=(i == 1 ? boundary_rightmost : boundary_middle)
)
y += lane_widths[i]/2
end
return seg
end
"""
quadratic bezier lerp
"""
Vec.lerp(A::VecE2{T}, B::VecE2{T}, C::VecE2{T}, t::T) where T<:Real = (1-t)^2*A + 2*(1-t)*t*B + t^2*B
"""
cubic bezier lerp
"""
Vec.lerp(A::VecE2{T}, B::VecE2{T}, C::VecE2{T}, D::VecE2{T}, t::T) where T<:Real = (1-t)^3*A + 3*(1-t)^2*t*B + 3*(1-t)*t^2*C + t^3*D
"""
gen_bezier_curve(A::VecSE2{T}, B::VecSE2{T}, rA::T, rB::T, nsamples::Int) where T <: Real
Generate a Bezier curve going from A to B with radii specified by rA and rB. It uses cubic
interpolation. `nsamples` specifies the number of point along the curve between A and B. The more
points, the more accurate the approximation is.
This is useful to generate arcs.
"""
function gen_bezier_curve(A::VecSE2{T}, B::VecSE2{T}, rA::T, rB::T, nsamples::Int) where T <: Real
a = convert(VecE2, A)
d = convert(VecE2, B)
b = a + polar( rA, A.θ)
c = d + polar(-rB, B.θ)
s = 0.0
curve = Array{CurvePt{T}}(undef, nsamples)
for i in 1 : nsamples
t = (i-1)/(nsamples-1)
P = lerp(a,b,c,d,t)
P′ = 3*(1-t)^2*(b-a) + 6*(1-t)*t*(c-b) + 3*t^2*(d-c)
P′′ = 6*(1-t)*(c-2b+a) + 6t*(d-2*c+b)
θ = atan(P′)
κ = (P′.x*P′′.y - P′.y*P′′.x)/(P′.x^2 + P′.y^2)^1.5 # signed curvature
if i > 1
s += norm(P - convert(VecE2, curve[i-1].pos)) # approximation, but should be good for many samples
end
curve[i] = CurvePt(VecSE2(P.x,P.y,θ), s, κ)
end
return curve
end
"""
gen_straight_roadway(nlanes::Int, length::Float64)
Generate a roadway with a single straight segment whose rightmost lane center starts at starts at (0,0),
and proceeds in the positive x direction.
"""
function gen_straight_roadway(nlanes::Int, length::Float64=1000.0;
origin::VecSE2{Float64} = VecSE2(0.0,0.0,0.0),
lane_width::Float64=DEFAULT_LANE_WIDTH, # [m]
lane_widths::Vector{Float64} = fill(lane_width, nlanes),
boundary_leftmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_rightmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_middle::LaneBoundary=LaneBoundary(:broken, :white),
)
retval = Roadway()
push!(retval.segments, gen_straight_segment(1, nlanes, length,
origin=origin, lane_widths=lane_widths,
boundary_leftmost=boundary_leftmost,
boundary_rightmost=boundary_rightmost,
boundary_middle=boundary_middle))
retval
end
"""
gen_stadium_roadway(nlanes::Int; length::Float64=100.0; width::Float64=10.0; radius::Float64=25.0)
Generate a roadway that is a rectangular racetrack with rounded corners.
length = length of the x-dim straight section for the innermost (leftmost) lane [m]
width = length of the y-dim straight section for the innermost (leftmost) lane [m]
radius = turn radius [m]
______________________
/ \\
| |
| |
\\______________________/
"""
function gen_stadium_roadway(nlanes::Int;
length::Float64=100.0,
width::Float64=10.0,
radius::Float64=25.0,
ncurvepts_per_turn::Int=25, # includes start and end
lane_width::Float64=DEFAULT_LANE_WIDTH, # [m]
boundary_leftmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_rightmost::LaneBoundary=LaneBoundary(:solid, :white),
boundary_middle::LaneBoundary=LaneBoundary(:broken, :white),
)
ncurvepts_per_turn ≥ 2 || error("must have at least 2 pts per turn")
A = VecE2(length, radius)
B = VecE2(length, width + radius)
C = VecE2(0.0, width + radius)
D = VecE2(0.0, radius)
seg1 = RoadSegment(1, Array{Lane{Float64}}(undef, nlanes))
seg2 = RoadSegment(2, Array{Lane{Float64}}(undef, nlanes))
seg3 = RoadSegment(3, Array{Lane{Float64}}(undef, nlanes))
seg4 = RoadSegment(4, Array{Lane{Float64}}(undef, nlanes))
seg5 = RoadSegment(5, Array{Lane{Float64}}(undef, nlanes))
seg6 = RoadSegment(6, Array{Lane{Float64}}(undef, nlanes))
for i in 1 : nlanes
curvepts1 = Array{CurvePt{Float64}}(undef, ncurvepts_per_turn)
curvepts2 = Array{CurvePt{Float64}}(undef, ncurvepts_per_turn)
curvepts3 = Array{CurvePt{Float64}}(undef, 2)
curvepts4 = Array{CurvePt{Float64}}(undef, ncurvepts_per_turn)
curvepts5 = Array{CurvePt{Float64}}(undef, ncurvepts_per_turn)
curvepts6 = Array{CurvePt{Float64}}(undef, 2)
r = radius + lane_width*(i-1)
for j in 1:ncurvepts_per_turn
t = (j-1)/(ncurvepts_per_turn-1) # ∈ [0,1]
s = r*π/2*t
curvepts1[j] = CurvePt(VecSE2(A + polar(r, lerp(-π/2, 0.0, t)), lerp(0.0,π/2,t)), s)
curvepts2[j] = CurvePt(VecSE2(B + polar(r, lerp( 0.0, π/2, t)), lerp(π/2,π, t)), s)
curvepts4[j] = CurvePt(VecSE2(C + polar(r, lerp( π/2, π, t)), lerp(π, 3π/2,t)), s)
curvepts5[j] = CurvePt(VecSE2(D + polar(r, lerp( π, 3π/2, t)), lerp(3π/2,2π,t)), s)
end
# fill in straight segments
curvepts3[1] = CurvePt(curvepts2[end].pos, 0.0)
curvepts3[2] = CurvePt(curvepts4[1].pos, length)
curvepts6[1] = CurvePt(curvepts5[end].pos, 0.0)
curvepts6[2] = CurvePt(curvepts1[1].pos, length)
laneindex = nlanes-i+1
tag1 = LaneTag(1,laneindex)
tag2 = LaneTag(2,laneindex)
tag3 = LaneTag(3,laneindex)
tag4 = LaneTag(4,laneindex)
tag5 = LaneTag(5,laneindex)
tag6 = LaneTag(6,laneindex)
boundary_left = (laneindex == nlanes ? boundary_leftmost : boundary_middle)
boundary_right = (laneindex == 1 ? boundary_rightmost : boundary_middle)
curveind_lo = CurveIndex(1,0.0)
curveind_hi = CurveIndex(ncurvepts_per_turn,1.0)
seg1.lanes[laneindex] = Lane(tag1, curvepts1, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag2),
prev = RoadIndex(curveind_hi, tag6),
)
seg2.lanes[laneindex] = Lane(tag2, curvepts2, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag3),
prev = RoadIndex(CurveIndex(ncurvepts_per_turn - 1,1.0), tag1),
)
seg3.lanes[laneindex] = Lane(tag3, curvepts3, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag4),
prev = RoadIndex(curveind_hi, tag2),
)
seg4.lanes[laneindex] = Lane(tag4, curvepts4, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag5),
prev = RoadIndex(curveind_hi, tag3),
)
seg5.lanes[laneindex] = Lane(tag5, curvepts5, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag6),
prev = RoadIndex(CurveIndex(ncurvepts_per_turn - 1,1.0), tag4),
)
seg6.lanes[laneindex] = Lane(tag6, curvepts6, width=lane_width,
boundary_left=boundary_left, boundary_right=boundary_right,
next = RoadIndex(curveind_lo, tag1),
prev = RoadIndex(curveind_hi, tag5),
)
end
retval = Roadway()
push!(retval.segments, seg1)
push!(retval.segments, seg2)
push!(retval.segments, seg3)
push!(retval.segments, seg4)
push!(retval.segments, seg5)
push!(retval.segments, seg6)
retval
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 26225 | """
LaneBoundary
Data structure to represent lanes boundaries such as double yellow lines.
# Fields
- `style::Symbol` ∈ :solid, :broken, :double
- `color::Symbol` ∈ :yellow, white
"""
struct LaneBoundary
style::Symbol # ∈ :solid, :broken, :double
color::Symbol # ∈ :yellow, white
end
const NULL_BOUNDARY = LaneBoundary(:unknown, :unknown)
#######################
"""
SpeedLimit
Datastructure to represent a speed limit
# Fields
- `lo::Float64` [m/s] lower speed limit
- `hi::Float64` [m/s] higher speed limit
"""
struct SpeedLimit
lo::Float64 # [m/s]
hi::Float64 # [m/s]
end
const DEFAULT_SPEED_LIMIT = SpeedLimit(-Inf, Inf)
#######################
"""
LaneTag
An identifier for a lane. The lane object can be retrieved by indexing the roadway by the lane tag:
```julia
tag = LaneTag(1, 2) # second lane segment 1
lane = roadway[tag] # returns a Lane object
```
# Fields
- `segment::Int64` segment id
- `lane::Int64` index in segment.lanes of this lane
"""
struct LaneTag
segment::Int64 # segment id
lane::Int64 # index in segment.lanes of this lane
end
Base.show(io::IO, tag::LaneTag) = @printf(io, "LaneTag(%d, %d)", tag.segment, tag.lane)
const NULL_LANETAG = LaneTag(0,0)
#######################################
"""
RoadIndex{I <: Integer, T <: Real}
A data structure to index points in a roadway. Calling `roadway[roadind]` will return the point
associated to the road index.
# Fields
- `ind::CurveIndex{I,T}` the index of the point in the curve
- `tag::LaneTag` the lane tag of the point
"""
struct RoadIndex{I <: Integer, T <: Real}
ind::CurveIndex{I, T}
tag::LaneTag
end
const NULL_ROADINDEX = RoadIndex(CurveIndex(-1,NaN), LaneTag(-1,-1))
Base.show(io::IO, r::RoadIndex) = @printf(io, "RoadIndex({%d, %3.f}, {%d, %d})", r.ind.i, r.ind.t, r.tag.segment, r.tag.lane)
Base.write(io::IO, r::RoadIndex) = @printf(io, "%d %.6f %d %d", r.ind.i, r.ind.t, r.tag.segment, r.tag.lane)
#######################################
"""
LaneConnection{I <: Integer, T <: Real}
Data structure to specify the connection of a lane. It connects `mylane` to the point `target`.
`target` would typically be the starting point of a new lane.
- `downstream::Bool`
- `mylane::CurveIndex{I,T}`
- `target::RoadIndex{I,T}`
"""
struct LaneConnection{I <: Integer, T <: Real}
downstream::Bool # if true, mylane → target, else target → mylane
mylane::CurveIndex{I, T}
target::RoadIndex{I, T}
end
Base.show(io::IO, c::LaneConnection) = print(io, "LaneConnection(", c.downstream ? "D" : "U", ", ", c.mylane, ", ", c.target)
function Base.write(io::IO, c::LaneConnection)
@printf(io, "%s (%d %.6f) ", c.downstream ? "D" : "U", c.mylane.i, c.mylane.t)
write(io, c.target)
end
function Base.parse(::Type{LaneConnection}, line::AbstractString)
cleanedline = replace(line, r"(\(|\))" => "")
tokens = split(cleanedline, ' ')
@assert(tokens[1] == "D" || tokens[1] == "U")
downstream = tokens[1] == "D"
mylane = CurveIndex(parse(Int, tokens[2]), parse(Float64, tokens[3]))
target = RoadIndex(
CurveIndex(parse(Int, tokens[4]), parse(Float64, tokens[5])),
LaneTag(parse(Int, tokens[6]), parse(Int, tokens[7]))
)
LaneConnection{Int64, Float64}(downstream, mylane, target)
end
#######################################
const DEFAULT_LANE_WIDTH = 3.0 # [m]
"""
Lane
A driving lane on a roadway. It identified by a `LaneTag`. A lane is defined by a curve which
represents a center line and a width. In addition it has attributed like speed limit.
A lane can be connected to other lane in the roadway, the connection are specified in the exits
and entrances fields.
# Fields
- `tag::LaneTag`
- `curve::Curve`
- `width::Float64` [m]
- `speed_limit::SpeedLimit`
- `boundary_left::LaneBoundary`
- `boundary_right::LaneBoundary`
- `exits::Vector{LaneConnection} # list of exits; put the primary exit (at end of lane) first`
- `entrances::Vector{LaneConnection} # list of entrances; put the primary entrance (at start of lane) first`
"""
mutable struct Lane{T <: Real}
tag :: LaneTag
curve :: Curve{T}
width :: Float64 # [m]
speed_limit :: SpeedLimit
boundary_left :: LaneBoundary
boundary_right :: LaneBoundary
exits :: Vector{LaneConnection{Int64, T}} # list of exits; put the primary exit (at end of lane) first
entrances :: Vector{LaneConnection{Int64, T}} # list of entrances; put the primary entrance (at start of lane) first
end
function Lane(
tag::LaneTag,
curve::Curve{T};
width::Float64 = DEFAULT_LANE_WIDTH,
speed_limit::SpeedLimit = DEFAULT_SPEED_LIMIT,
boundary_left::LaneBoundary = NULL_BOUNDARY,
boundary_right::LaneBoundary = NULL_BOUNDARY,
exits::Vector{LaneConnection{Int64, T}} = LaneConnection{Int64,T}[],
entrances::Vector{LaneConnection{Int64, T}} = LaneConnection{Int64,T}[],
next::RoadIndex=NULL_ROADINDEX,
prev::RoadIndex=NULL_ROADINDEX,
) where T
lane = Lane{T}(tag,
curve,
width,
speed_limit,
boundary_left,
boundary_right,
exits,
entrances)
if next != NULL_ROADINDEX
pushfirst!(lane.exits, LaneConnection(true, curveindex_end(lane.curve), next))
end
if prev != NULL_ROADINDEX
pushfirst!(lane.entrances, LaneConnection(false, CURVEINDEX_START, prev))
end
return lane
end
"""
has_next(lane::Lane)
returns true if the end of the lane is connected to another lane (i.e. if it has an exit lane)
"""
has_next(lane::Lane) = !isempty(lane.exits) && lane.exits[1].mylane == curveindex_end(lane.curve)
"""
has_prev(lane::Lane)
returns true if another lane is connected to the beginning of that lane. (i.e. if it has an entrance lane)
"""
has_prev(lane::Lane) = !isempty(lane.entrances) && lane.entrances[1].mylane == CURVEINDEX_START
"""
is_in_exits(lane::Lane, target::LaneTag)
returns true if `target` is in the exit lanes of `lane`.
"""
is_in_exits(lane::Lane, target::LaneTag) = findfirst(lc->lc.target.tag == target, lane.exits) != nothing
"""
is_in_entrances(lane::Lane, target::LaneTag)
returns true if `target` is in the entrances lanes of `lane`.
"""
is_in_entrances(lane::Lane, target::LaneTag) = findfirst(lc->lc.target.tag == target, lane.entrances) != nothing
"""
connect!(source::Lane, dest::Lane)
connect two lanes to each other. Useful for roadway construction.
"""
function connect!(source::Lane, dest::Lane)
# place these at the front
cindS = curveindex_end(source.curve)
cindD = CURVEINDEX_START
pushfirst!(source.exits, LaneConnection(true, cindS, RoadIndex(cindD, dest.tag)))
pushfirst!(dest.entrances, LaneConnection(false, cindD, RoadIndex(cindS, source.tag)))
(source, dest)
end
function connect!(source::Lane, cindS::CurveIndex, dest::Lane, cindD::CurveIndex)
push!(source.exits, LaneConnection(true, cindS, RoadIndex(cindD, dest.tag)))
push!(dest.entrances, LaneConnection(false, cindD, RoadIndex(cindS, source.tag)))
(source, dest)
end
#######################################
"""
RoadSegment{T}
a list of lanes forming a single road with a common direction
# Fields
- `id::Int64`
- `lanes::Vector{Lane{T}}` lanes are stored right to left
"""
mutable struct RoadSegment{T<:Real}
id::Int64
lanes::Vector{Lane{T}}
end
RoadSegment{T}(id::Int64) where T = RoadSegment{T}(id, Lane{T}[])
#######################################
"""
Roadway
The main datastructure to represent road network, it consists of a list of `RoadSegment`
# Fields
- `segments::Vector{RoadSegment}`
"""
mutable struct Roadway{T<:Real}
segments::Vector{RoadSegment{T}}
end
Roadway{T}() where T = Roadway{T}(RoadSegment{T}[])
Roadway() = Roadway{Float64}()
Base.show(io::IO, roadway::Roadway) = @printf(io, "Roadway")
"""
Base.write(io::IO, roadway::Roadway)
write all the roadway information to a text file
"""
function Base.write(io::IO, roadway::Roadway)
# writes to a text file
println(io, "ROADWAY")
println(io, length(roadway.segments)) # number of segments
for seg in roadway.segments
println(io, seg.id)
println(io, "\t", length(seg.lanes)) # number of lanes
for (i,lane) in enumerate(seg.lanes)
@assert(lane.tag.lane == i)
@printf(io, "\t%d\n", i)
@printf(io, "\t\t%.3f\n", lane.width)
@printf(io, "\t\t%.3f %.3f\n", lane.speed_limit.lo, lane.speed_limit.hi)
println(io, "\t\t", lane.boundary_left.style, " ", lane.boundary_left.color)
println(io, "\t\t", lane.boundary_right.style, " ", lane.boundary_right.color)
println(io, "\t\t", length(lane.exits) + length(lane.entrances))
for conn in lane.exits
print(io, "\t\t\t"); write(io, conn); print(io, "\n")
end
for conn in lane.entrances
print(io, "\t\t\t"); write(io, conn); print(io, "\n")
end
println(io, "\t\t", length(lane.curve))
for pt in lane.curve
@printf(io, "\t\t\t(%.4f %.4f %.6f) %.4f %.8f %.8f\n", pt.pos.x, pt.pos.y, pt.pos.θ, pt.s, pt.k, pt.kd)
end
end
end
end
"""
Base.read(io::IO, ::Type{Roadway})
extract roadway information from a text file and returns a roadway object.
"""
function Base.read(io::IO, ::Type{Roadway})
lines = readlines(io)
line_index = 1
if occursin("ROADWAY", lines[line_index])
line_index += 1
end
function advance!()
line = strip(lines[line_index])
line_index += 1
line
end
nsegs = parse(Int, advance!())
roadway = Roadway{Float64}(Array{RoadSegment{Float64}}(undef, nsegs))
for i_seg in 1:nsegs
segid = parse(Int, advance!())
nlanes = parse(Int, advance!())
seg = RoadSegment(segid, Array{Lane{Float64}}(undef, nlanes))
for i_lane in 1:nlanes
@assert(i_lane == parse(Int, advance!()))
tag = LaneTag(segid, i_lane)
width = parse(Float64, advance!())
tokens = split(advance!(), ' ')
speed_limit = SpeedLimit(parse(Float64, tokens[1]), parse(Float64, tokens[2]))
tokens = split(advance!(), ' ')
boundary_left = LaneBoundary(Symbol(tokens[1]), Symbol(tokens[2]))
tokens = split(advance!(), ' ')
boundary_right = LaneBoundary(Symbol(tokens[1]), Symbol(tokens[2]))
exits = LaneConnection{Int64, Float64}[]
entrances = LaneConnection{Int64, Float64}[]
n_conns = parse(Int, advance!())
for i_conn in 1:n_conns
conn = parse(LaneConnection, advance!())
conn.downstream ? push!(exits, conn) : push!(entrances, conn)
end
npts = parse(Int, advance!())
curve = Array{CurvePt{Float64}}(undef, npts)
for i_pt in 1:npts
line = advance!()
cleanedline = replace(line, r"(\(|\))" => "")
tokens = split(cleanedline, ' ')
x = parse(Float64, tokens[1])
y = parse(Float64, tokens[2])
θ = parse(Float64, tokens[3])
s = parse(Float64, tokens[4])
k = parse(Float64, tokens[5])
kd = parse(Float64, tokens[6])
curve[i_pt] = CurvePt(VecSE2(x,y,θ), s, k, kd)
end
seg.lanes[i_lane] = Lane(tag, curve, width=width, speed_limit=speed_limit,
boundary_left=boundary_left,
boundary_right=boundary_right,
entrances=entrances, exits=exits)
end
roadway.segments[i_seg] = seg
end
roadway
end
"""
lane[ind::CurveIndex, roadway::Roadway]
Accessor for lanes based on a CurveIndex.
Note that we extend the definition of a CurveIndex,
previously ind.i ∈ [1, length(curve)-1], to:
ind.i ∈ [0, length(curve)]
where 1 ≤ ind.i ≤ length(curve)-1 is as before, but if the index
is on the section between two lanes, we use:
ind.i = length(curve), ind.t ∈ [0,1] for the region between curve[end] → next
ind.i = 0, ind.t ∈ [0,1] for the region between prev → curve[1]
"""
function Base.getindex(lane::Lane{T}, ind::CurveIndex{I, T}, roadway::Roadway{T}) where {I<:Integer,T<:Real}
if ind.i == 0
pt_lo = prev_lane_point(lane, roadway)
pt_hi = lane.curve[1]
s_gap = norm(VecE2(pt_hi.pos - pt_lo.pos))
pt_lo = CurvePt{T}(pt_lo.pos, -s_gap, pt_lo.k, pt_lo.kd)
return lerp(pt_lo, pt_hi, ind.t)
elseif ind.i < length(lane.curve)
return lane.curve[ind]
else
pt_hi = next_lane_point(lane, roadway)
pt_lo = lane.curve[end]
s_gap = norm(VecE2(pt_hi.pos - pt_lo.pos))
pt_hi = CurvePt{T}(pt_hi.pos, pt_lo.s + s_gap, pt_hi.k, pt_hi.kd)
return lerp( pt_lo, pt_hi, ind.t)
end
end
"""
Base.getindex(roadway::Roadway, segid::Int)
returns the segment associated with id `segid`
"""
function Base.getindex(roadway::Roadway, segid::Int)
for seg in roadway.segments
if seg.id == segid
return seg
end
end
error("Could not find segid $segid in roadway")
end
"""
Base.getindex(roadway::Roadway, tag::LaneTag)
returns the lane identified by the tag `LaneTag`
"""
function Base.getindex(roadway::Roadway, tag::LaneTag)
seg = roadway[tag.segment]
seg.lanes[tag.lane]
end
"""
is_between_segments_lo(ind::CurveIndex)
"""
is_between_segments_lo(ind::CurveIndex) = ind.i == 0
"""
is_between_segments_hi(ind::CurveIndex, curve::Curve)
"""
is_between_segments_hi(ind::CurveIndex, curve::Curve) = ind.i == length(curve)
"""
is_between_segments(ind::CurveIndex, curve::Curve)
"""
is_between_segments(ind::CurveIndex, curve::Curve) = is_between_segments_lo(ind) || is_between_segments_hi(ind, curve)
"""
next_lane(lane::Lane, roadway::Roadway)
returns the lane connected to the end `lane`. If `lane` has several exits, it returns the first one
"""
next_lane(lane::Lane, roadway::Roadway) = roadway[lane.exits[1].target.tag]
"""
prev_lane(lane::Lane, roadway::Roadway)
returns the lane connected to the beginning `lane`. If `lane` has several entrances, it returns the first one
"""
prev_lane(lane::Lane, roadway::Roadway) = roadway[lane.entrances[1].target.tag]
"""
next_lane_point(lane::Lane, roadway::Roadway)
returns the point of connection between `lane` and its first exit
"""
next_lane_point(lane::Lane, roadway::Roadway) = roadway[lane.exits[1].target]
"""
prev_lane_point(lane::Lane, roadway::Roadway)
returns the point of connection between `lane` and its first entrance
"""
prev_lane_point(lane::Lane, roadway::Roadway) = roadway[lane.entrances[1].target]
"""
has_segment(roadway::Roadway, segid::Int)
returns true if `segid` is in `roadway`.
"""
function has_segment(roadway::Roadway, segid::Int)
for seg in roadway.segments
if seg.id == segid
return true
end
end
false
end
"""
has_lanetag(roadway::Roadway, tag::LaneTag)
returns true if `roadway` contains a lane identified by `tag`
"""
function has_lanetag(roadway::Roadway, tag::LaneTag)
if !has_segment(roadway, tag.segment)
return false
end
seg = roadway[tag.segment]
1 ≤ tag.lane ≤ length(seg.lanes)
end
"""
RoadProjection{I <: Integer, T <: Real}
represents the projection of a point on the roadway
# Fields
- `curveproj::CurveProjection{I, T}`
- `tag::LaneTag`
"""
struct RoadProjection{I <: Integer, T <: Real}
curveproj::CurveProjection{I, T}
tag::LaneTag
end
function get_closest_perpendicular_point_between_points(A::VecSE2{T}, B::VecSE2{T}, Q::VecSE2{T};
tolerance::T = 0.01, # acceptable error in perpendicular component
max_iter::Int = 50, # maximum number of iterations
) where T
# CONDITIONS: a < b, either f(a) < 0 and f(b) > 0 or f(a) > 0 and f(b) < 0
# OUTPUT: value which differs from a root of f(x)=0 by less than TOL
a = convert(T, 0.0)
b = convert(T, 1.0)
f_a = inertial2body(Q, A).x
f_b = inertial2body(Q, B).x
if sign(f_a) == sign(f_b) # both are wrong - use the old way
t = get_lerp_time_unclamped(A, B, Q)
t = clamp(t, 0.0, 1.0)
return (t, lerp(A,B,t))
end
iter = 1
while iter ≤ max_iter
c = (a+b)/2 # new midpoint
footpoint = lerp(A, B, c)
f_c = inertial2body(Q, footpoint).x
if abs(f_c) < tolerance # solution found
return (c, footpoint)
end
if sign(f_c) == sign(f_a)
a, f_a = c, f_c
else
b = c
end
iter += 1
end
# Maximum number of iterations passed
# This will occur when we project with a point that is not actually in the range,
# and we converge towards one edge
if a == 0.0
return (a, A)
elseif b == 1.0
return (b, B)
else
@warn("get_closest_perpendicular_point_between_points - should not happen")
c = (a+b)/2 # should not happen
return (c, lerp(A,B,c))
end
end
"""
proj(posG::VecSE2{T}, lane::Lane, roadway::Roadway; move_along_curves::Bool=true) where T <: Real
Return the RoadProjection for projecting posG onto the lane.
This will automatically project to the next or prev curve as appropriate.
if `move_along_curves` is false, will only project to lane.curve
"""
function Vec.proj(posG::VecSE2{T}, lane::Lane{T}, roadway::Roadway{T};
move_along_curves::Bool = true, # if false, will only project to lane.curve
) where T <: Real
curveproj = proj(posG, lane.curve)
rettag = lane.tag
if curveproj.ind == CurveIndex(1,zero(T)) && has_prev(lane)
pt_lo = prev_lane_point(lane, roadway)
pt_hi = lane.curve[1]
t = get_lerp_time_unclamped(pt_lo, pt_hi, posG)
if t ≤ 0.0 && move_along_curves
return proj(posG, prev_lane(lane, roadway), roadway)
elseif t < 1.0 # for t == 1.0 we use the actual end of the lane
@assert(!move_along_curves || 0.0 ≤ t < 1.0)
# t was computed assuming a constant angle
# this is not valid for the large distances and angle disparities between lanes
# thus we now use a bisection search to find the appropriate location
t, footpoint = get_closest_perpendicular_point_between_points(pt_lo.pos, pt_hi.pos, posG)
ind = CurveIndex(0, t)
curveproj = get_curve_projection(posG, footpoint, ind)
end
elseif curveproj.ind == curveindex_end(lane.curve) && has_next(lane)
pt_lo = lane.curve[end]
pt_hi = next_lane_point(lane, roadway)
t = get_lerp_time_unclamped(pt_lo, pt_hi, posG)
if t ≥ 1.0 && move_along_curves
# for t == 1.0 we use the actual start of the lane
return proj(posG, next_lane(lane, roadway), roadway)
elseif t ≥ 0.0
@assert(!move_along_curves || 0.0 ≤ t ≤ 1.0)
# t was computed assuming a constant angle
# this is not valid for the large distances and angle disparities between lanes
# thus we now use a bisection search to find the appropriate location
t, footpoint = get_closest_perpendicular_point_between_points(pt_lo.pos, pt_hi.pos, posG)
ind = CurveIndex(length(lane.curve), t)
curveproj = get_curve_projection(posG, footpoint, ind)
end
end
RoadProjection(curveproj, rettag)
end
"""
proj(posG::VecSE2{T}, seg::RoadSegment, roadway::Roadway) where T <: Real
Return the RoadProjection for projecting posG onto the segment.
Tries all of the lanes and gets the closest one
"""
function Vec.proj(posG::VecSE2{T}, seg::RoadSegment, roadway::Roadway) where T <: Real
best_dist2 = Inf
best_proj = RoadProjection{Int64, T}(CurveProjection(CurveIndex(-1,convert(T, -1)), convert(T, NaN), convert(T, NaN)),
NULL_LANETAG)
for lane in seg.lanes
roadproj = proj(posG, lane, roadway)
footpoint = roadway[roadproj.tag][roadproj.curveproj.ind, roadway]
dist2 = norm(VecE2(posG - footpoint.pos))
if dist2 < best_dist2
best_dist2 = dist2
best_proj = roadproj
end
end
best_proj
end
"""
proj(posG::VecSE2{T}, seg::RoadSegment, roadway::Roadway) where T <: Real
Return the RoadProjection for projecting posG onto the roadway.
Tries all of the lanes and gets the closest one
"""
function Vec.proj(posG::VecSE2{T}, roadway::Roadway) where T <: Real
best_dist2 = Inf
best_proj = RoadProjection(CurveProjection(CurveIndex(-1,convert(T,-1.0)),
convert(T, NaN),
convert(T, NaN)),
NULL_LANETAG)
for seg in roadway.segments
for lane in seg.lanes
roadproj = proj(posG, lane, roadway, move_along_curves=false)
targetlane = roadway[roadproj.tag]
footpoint = targetlane[roadproj.curveproj.ind, roadway]
dist2 = normsquared(VecE2(posG - footpoint.pos))
if dist2 < best_dist2
best_dist2 = dist2
best_proj = roadproj
end
end
end
best_proj
end
############################################
RoadIndex(roadproj::RoadProjection) = RoadIndex(roadproj.curveproj.ind, roadproj.tag)
"""
Base.getindex(roadway::Roadway, roadind::RoadIndex)
returns the CurvePt on the roadway associated to `roadind`
"""
function Base.getindex(roadway::Roadway, roadind::RoadIndex)
lane = roadway[roadind.tag]
lane[roadind.ind, roadway]
end
"""
move_along(roadind::RoadIndex, road::Roadway, Δs::Float64)
Return the RoadIndex at ind's s position + Δs
"""
function move_along(roadind::RoadIndex{I, T},
roadway::Roadway,
Δs::Float64,
depth::Int=0) where {I <: Integer, T <: Real}
lane = roadway[roadind.tag]
curvept = lane[roadind.ind, roadway]
if curvept.s + Δs < 0.0
if has_prev(lane)
pt_lo = prev_lane_point(lane, roadway)
pt_hi = lane.curve[1]
s_gap = norm(VecE2(pt_hi.pos - pt_lo.pos))
if curvept.s + Δs < -s_gap
lane_prev = prev_lane(lane, roadway)
curveind = curveindex_end(lane_prev.curve)
roadind = RoadIndex{I,T}(curveind, lane_prev.tag)
return move_along(roadind, roadway, Δs + curvept.s + s_gap, depth+1)
else # in the gap between lanes
t = (s_gap + curvept.s + Δs) / s_gap
curveind = CurveIndex(0, t)
RoadIndex{I,T}(curveind, lane.tag)
end
else # no prev lane, return the beginning of this one
curveind = CurveIndex(1, 0.0)
return RoadIndex{I,T}(curveind, roadind.tag)
end
elseif curvept.s + Δs > lane.curve[end].s
if has_next(lane)
pt_lo = lane.curve[end]
pt_hi = next_lane_point(lane, roadway)
s_gap = norm(VecE2(pt_hi.pos - pt_lo.pos))
if curvept.s + Δs ≥ pt_lo.s + s_gap # extends beyond the gap
curveind = lane.exits[1].target.ind
roadind = RoadIndex{I,T}(curveind, lane.exits[1].target.tag)
return move_along(roadind, roadway, Δs - (lane.curve[end].s + s_gap - curvept.s))
else # in the gap between lanes
t = (Δs - (lane.curve[end].s - curvept.s)) / s_gap
curveind = CurveIndex(0, t)
RoadIndex{I,T}(curveind, lane.exits[1].target.tag)
end
else # no next lane, return the end of this lane
curveind = curveindex_end(lane.curve)
return RoadIndex{I,T}(curveind, roadind.tag)
end
else
if roadind.ind.i == 0
ind = get_curve_index(CurveIndex(1,0.0), lane.curve, curvept.s+Δs)
elseif roadind.ind.i == length(lane.curve)
ind = get_curve_index(curveindex_end(lane.curve), lane.curve, curvept.s+Δs)
else
ind = get_curve_index(roadind.ind, lane.curve, Δs)
end
RoadIndex{I,T}(ind, roadind.tag)
end
end
"""
n_lanes_right(roadway::Roadway, lane::Lane)
returns the number of lanes to the right of `lane`
"""
n_lanes_right(roadway::Roadway, lane::Lane) = lane.tag.lane - 1
"""
rightlane(roadway::Roadway, lane::Lane)
returns the lane to the right of lane if it exists, returns nothing otherwise
"""
function rightlane(roadway::Roadway, lane::Lane)
if n_lanes_right(roadway, lane) > 0.0
return roadway[LaneTag(lane.tag.segment, lane.tag.lane - 1)]
else
return nothing
end
end
"""
n_lanes_left(roadway::Roadway, lane::Lane)
returns the number of lanes to the left of `lane`
"""
function n_lanes_left(roadway::Roadway, lane::Lane)
seg = roadway[lane.tag.segment]
length(seg.lanes) - lane.tag.lane
end
"""
leftlane(roadway::Roadway, lane::Lane)
returns the lane to the left of lane if it exists, returns nothing otherwise
"""
function leftlane(roadway::Roadway, lane::Lane)
if n_lanes_left(roadway, lane) > 0.0
return roadway[LaneTag(lane.tag.segment, lane.tag.lane + 1)]
else
return nothing
end
end
"""
lanes(roadway::Roadway{T}) where T
return a list of all the lanes present in roadway.
"""
function lanes(roadway::Roadway{T}) where T
lanes = Lane{T}[]
for i=1:length(roadway.segments)
for lane in roadway.segments[i].lanes
push!(lanes, lane)
end
end
return lanes
end
"""
lanetags(roadway::Roadway)
return a list of all the lane tags present in roadway.
"""
function lanetags(roadway::Roadway)
lanetags = LaneTag[]
for i=1:length(roadway.segments)
for lane in roadway.segments[i].lanes
push!(lanetags, lane.tag)
end
end
return lanetags
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 1862 | """
Internals, run all callbacks
"""
function _run_callbacks(callbacks::C, scenes::Vector{Scene{Entity{S,D,I}}}, actions::Union{Nothing, Vector{Scene{A}}}, roadway::R, models::Dict{I,M}, tick::Int) where {S,D,I,A<:EntityAction,R,M<:DriverModel,C<:Tuple{Vararg{Any}}}
isdone = false
for callback in callbacks
isdone |= run_callback(callback, scenes, actions, roadway, models, tick)
end
return isdone
end
"""
run_callback(callback, scenes::Vector{EntityScene}, actions::Union{Nothing, Vector{A}}, roadway::Roadway, models::Dict{I, DriverModel}, tick::Int64)
Given a callback type, `run_callback` will be run at every step of a simulation run using `simulate`.
By overloading the `run_callback` method for a custom callback type one can log information or interrupt a simulation.
The `run_callback` function is expected to return a boolean. If `true` the simulation is stopped.
# Inputs:
- `callback` the custom callback type used for dispatch
- `scenes` where the simulation data is stored, note that it is only filled up to the current time step (`scenes[1:tick+1]`)
- `actions` where the actions are stored, it is only filled up to `actions[tick]`
- `roadway` the roadway where entities are moving
- `models` a dictionary mapping entity IDs to driver models
- `tick` the index of the current time step
"""
function run_callback end
## Implementations of useful callbacks
"""
CollisionCallback
Terminates the simulation once a collision occurs
"""
@with_kw struct CollisionCallback
mem::CPAMemory=CPAMemory()
end
function run_callback(
callback::CollisionCallback,
scenes::Vector{Scene{E}},
actions::Union{Nothing, Vector{Scene{A}}},
roadway::R,
models::Dict{I,M},
tick::Int
) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel}
return !is_collision_free(scenes[tick], callback.mem)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3313 | """
simulate(
scene::Scene{E}, roadway::R, models::Dict{I,M}, nticks::Int64, timestep::Float64;
rng::AbstractRNG = Random.GLOBAL_RNG, callbacks = nothing
) where {E<:Entity,A,R,I,M<:DriverModel}
Simulate a `scene`. For detailed information, consult the documentation of `simulate!`.
By default, returns a vector containing one scene per time step.
"""
function simulate(
scene::Scene{E},
roadway::R,
models::Dict{I,M},
nticks::Int64,
timestep::Float64;
rng::AbstractRNG = Random.GLOBAL_RNG,
callbacks = nothing,
) where {E<:Entity,A,R,I,M<:DriverModel}
scenes = [Scene(E, length(scene)) for i=1:nticks+1]
n = simulate!(
scene, roadway, models, nticks, timestep, scenes, nothing,
rng=rng, callbacks=callbacks
)
return scenes[1:(n+1)]
end
"""
simulate!(
scene::Scene{E}, roadway::R, models::Dict{I,M},
nticks::Int64, timestep::Float64,
scenes::Vector{Scene{E}}, actions::Union{Nothing, Vector{Scene{A}}} = nothing;
rng::AbstractRNG = Random.GLOBAL_RNG, callbacks = nothing
) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel}
Simulate the entities in `scene` along a `roadway` for a maximum of
`nticks` time steps of size `timestep`.
Returns the number of successfully performed timesteps.
At each time step, `models` is used to determine the action for each agent.
`scenes` and `actions` are pre-allocated vectors of `Scene`s containing either
`Entity`s (for scenes) or `EntityAction`s (for actions).
If `actions` is equal to `nothing` (default), the action history is not tracked.
`scenes` must always be provided.
`callbacks` is an array of callback functions which are invoked before
the simulation starts and after every simulation step.
Any callback function can cause an early termination by returning `true`
(the default return value for callback functions should be `false`).
The random number generator for the simulation can be provided using the `rng`
keyword argument, it defaults to `Random.GLOBAL_RNG`.
"""
function simulate!(
scene::Scene{E},
roadway::R,
models::Dict{I,M},
nticks::Int64,
timestep::Float64,
scenes::Vector{Scene{E}},
actions::Union{Nothing, Vector{Scene{A}}} = nothing;
rng::AbstractRNG = Random.GLOBAL_RNG,
callbacks = nothing
) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel}
copyto!(scenes[1], scene)
# potential early out right off the bat
if (callbacks !== nothing) && _run_callbacks(callbacks, scenes, actions, roadway, models, 1)
return 0
end
for tick in 1:nticks
empty!(scenes[tick + 1])
if (actions !== nothing) empty!(actions[tick]) end
for (i, veh) in enumerate(scenes[tick])
observe!(models[veh.id], scenes[tick], roadway, veh.id)
a = rand(rng, models[veh.id])
veh_state_p = propagate(veh, a, roadway, timestep)
push!(scenes[tick + 1], Entity(veh_state_p, veh.def, veh.id))
if (actions !== nothing) push!(actions[tick], EntityAction(a, veh.id)) end
end
if !(callbacks === nothing) && _run_callbacks(callbacks, scenes, actions, roadway, models, tick+1)
return tick
end
end
return nticks
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3696 | """
observe_from_history!(model::DriverModel, roadway::Roadway, trajdata::Vector{<:EntityScene}, egoid, start::Int, stop::Int)
Given a prerecorded trajectory `trajdata`, run the observe function of a driver model for the scenes between `start` and `stop` for the vehicle of id `egoid`.
The ego vehicle does not take any actions, it just observe the scenes,
"""
function observe_from_history!(
model::DriverModel,
roadway::Roadway,
trajdata::Vector{<:EntityScene},
egoid,
start::Int = 1,
stop::Int = length(trajdata))
reset_hidden_state!(model)
for i=start:stop
observe!(model, trajdata[i], roadway, egoid)
end
return model
end
"""
maximum_entities(trajdata::Vector{<:EntityScene})
return the maximum number of entities present in a given scene of the trajectory.
"""
function maximum_entities(trajdata::Vector{<:EntityScene})
return maximum(capacity, trajdata)
end
"""
simulate_from_history(model::DriverModel, roadway::Roadway, trajdata::Vector{Scene{E}}, egoid, timestep::Float64,
start::Int = 1, stop::Int = length(trajdata);
rng::AbstractRNG = Random.GLOBAL_RNG) where {E<:Entity}
Replay the given trajectory except for the entity `egoid` which follows the given driver model.
See `simulate_from_history!` if you want to provide a container for the results or log actions.
"""
function simulate_from_history(
model::DriverModel,
roadway::Roadway,
trajdata::Vector{Scene{E}},
egoid,
timestep::Float64,
start::Int = 1,
stop::Int = length(trajdata);
rng::AbstractRNG = Random.GLOBAL_RNG
) where {E<:Entity}
scenes = [Scene(E, maximum_entities(trajdata)) for i=1:(stop - start + 1)]
n = simulate_from_history!(model, roadway, trajdata, egoid, timestep,
start, stop, scenes,
rng=rng)
return scenes[1:(n+1)]
end
"""
simulate_from_history!(model::DriverModel, roadway::Roadway, trajdata::Vector{Scene{E}}, egoid, timestep::Float64,
start::Int, stop::Int, scenes::Vector{Scene{E}};
actions::Union{Nothing, Vector{Scene{A}}} = nothing, rng::AbstractRNG = Random.GLOBAL_RNG) where {E<:Entity}
Replay the given trajectory except for the entity `egoid` which follows the given driver model.
The resulting trajectory is stored in `scenes`, the actions of the ego vehicle are stored in `actions`.
"""
function simulate_from_history!(
model::DriverModel,
roadway::Roadway,
trajdata::Vector{Scene{E}},
egoid,
timestep::Float64,
start::Int,
stop::Int,
scenes::Vector{Scene{E}};
actions::Union{Nothing, Vector{Scene{A}}} = nothing,
rng::AbstractRNG = Random.GLOBAL_RNG
) where {E<:Entity, A<:EntityAction}
# run model (unsure why it is needed, it was in the old code )
observe_from_history!(model, roadway, trajdata, egoid, start, stop)
copyto!(scenes[1], trajdata[start])
for tick=1:(stop - start)
empty!(scenes[tick + 1])
if (actions !== nothing) empty!(actions[tick]) end
ego = get_by_id(scenes[tick], egoid)
observe!(model, scenes[tick], roadway, egoid)
a = rand(rng, model)
ego_state_p = propagate(ego, a, roadway, timestep)
copyto!(scenes[tick+1], trajdata[start+tick])
egoind = findfirst(egoid, scenes[tick+1])
scenes[tick+1][egoind] = Entity(ego_state_p, ego.def, egoid)
if (actions !== nothing) push!(actions[tick], EntityAction(a, egoid)) end
end
return (stop - start)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 687 | """
Entity{S,D,I}
Immutable data structure to represent entities (vehicle, pedestrian, ...).
Entities are defined by a state, a definition, and an id.
The state of an entity usually models changing values while the definition and the id should not change.
# Constructor
`Entity(state, definition, id)`
Copy constructor that keeps the definition and id but changes the state (a new object is still created):
`Entity(entity::Entity{S,D,I}, s::S)`
# Fields
- `state::S`
- `def::D`
- `id::I`
"""
struct Entity{S,D,I} # state, definition, identification
state::S
def::D
id::I
end
Entity(entity::Entity{S,D,I}, s::S) where {S,D,I} = Entity(s, entity.def, entity.id)
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 634 | # Interface to define custom state types
"""
posf(state)
returns the coordinates of the state in the Frenet frame.
The return type is expected to be `Frenet`.
"""
function posf end
"""
posg(state)
returns the coordinates of the state in the global (world) frame.
The return type is expected to be a VecSE2.
"""
function posg end
"""
vel(state)
returns the norm of the longitudinal velocity.
"""
function vel end
"""
velf(state)
returns the velocity of the state in the Frenet frame.
"""
function velf end
"""
velg(state)
returns the velocity of the state in the global (world) frame.
"""
function velg end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 5821 | """
Scene{E}
Container to store a list of entities.
The main difference from a regular array is that its size is defined at construction and is fixed.
(`push!` is O(1))
# Constructors
- `Scene(arr::AbstractVector; capacity::Int=length(arr))`
- `Scene(::Type{E}, capacity::Int=100) where {E}`
# Fields
To interact with `Scene` object it is preferable to use functions rather than accessing the fields directly.
- `entities::Vector{E}`
- `n::Int` current number of entities in the scene
"""
mutable struct Scene{E}
entities::Vector{E} # NOTE: I tried StaticArrays; was not faster
n::Int
end
function Scene(arr::AbstractVector{E}; capacity::Int=length(arr)) where {E}
capacity ≥ length(arr) || error("capacity cannot be less than entitiy count! (N ≥ length(arr))")
entities = Array{E}(undef, capacity)
copyto!(entities, arr)
return Scene{E}(entities, length(arr))
end
function Scene(::Type{E}, capacity::Int=100) where {E}
entities = Array{E}(undef, capacity)
return Scene{E}(entities, 0)
end
Base.show(io::IO, scene::Scene{E}) where {E}= @printf(io, "Scene{%s}(%d entities)", string(E), length(scene))
"""
capacity(scene::Scene)
returns the maximum number of entities that can be put in the scene.
To get the current number of entities use `length` instead.
"""
capacity(scene::Scene) = length(scene.entities)
Base.length(scene::Scene) = scene.n
Base.getindex(scene::Scene, i::Int) = scene.entities[i]
Base.eltype(scene::Scene{E}) where {E} = E
Base.lastindex(scene::Scene) = scene.n
function Base.setindex!(scene::Scene{E}, entity::E, i::Int) where {E}
scene.entities[i] = entity
return scene
end
function Base.empty!(scene::Scene)
scene.n = 0
return scene
end
function Base.deleteat!(scene::Scene, entity_index::Int)
for i in entity_index : scene.n - 1
scene.entities[i] = scene.entities[i+1]
end
scene.n -= 1
scene
end
function Base.iterate(scene::Scene{E}, i::Int=1) where {E}
if i > length(scene)
return nothing
end
return (scene.entities[i], i+1)
end
function Base.copyto!(dest::Scene{E}, src::Scene{E}) where {E}
for i in 1 : src.n
dest.entities[i] = src.entities[i]
end
dest.n = src.n
return dest
end
Base.copy(scene::Scene{E}) where {E} = copyto!(Scene(E, capacity(scene)), scene)
function Base.push!(scene::Scene{E}, entity::E) where {E}
scene.n += 1
scene.entities[scene.n] = entity
return scene
end
####
"""
EntityScene{S,D,I} = Scene{Entity{S,D,I}}
Alias for `Scene` when the entities in the scene are of type `Entity`
# Constructors
- `EntityScene(::Type{S},::Type{D},::Type{I}) where {S,D,I}`
- `EntityScene(::Type{S},::Type{D},::Type{I},capacity::Int)`
"""
const EntityScene{S,D,I} = Scene{Entity{S,D,I}}
EntityScene(::Type{S},::Type{D},::Type{I}) where {S,D,I} = Scene(Entity{S,D,I})
EntityScene(::Type{S},::Type{D},::Type{I},capacity::Int) where {S,D,I} = Scene(Entity{S,D,I}, capacity)
Base.in(id::I, scene::EntityScene{S,D,I}) where {S,D,I} = findfirst(id, scene) !== nothing
function Base.findfirst(id::I, scene::EntityScene{S,D,I}) where {S,D,I}
for entity_index in 1 : scene.n
entity = scene.entities[entity_index]
if entity.id == id
return entity_index
end
end
return nothing
end
function id2index(scene::EntityScene{S,D,I}, id::I) where {S,D,I}
entity_index = findfirst(id, scene)
if entity_index === nothing
throw(BoundsError(scene, [id]))
end
return entity_index
end
"""
get_by_id(scene::EntityScene{S,D,I}, id::I) where {S,D,I}
Retrieve the entity by its `id`. This function uses `findfirst` which is O(n).
"""
get_by_id(scene::EntityScene{S,D,I}, id::I) where {S,D,I} = scene[id2index(scene, id)]
function get_first_available_id(scene::EntityScene{S,D,I}) where {S,D,I}
ids = Set{I}(entity.id for entity in scene)
id_one = one(I)
id = id_one
while id ∈ ids
id += id_one
end
return id
end
function Base.push!(scene::EntityScene{S,D,I}, s::S) where {S,D,I}
id = get_first_available_id(scene)
entity = Entity{S,D,I}(s, D(), id)
push!(scene, entity)
end
Base.delete!(scene::EntityScene{S,D,I}, entity::Entity{S,D,I}) where {S,D,I} = deleteat!(scene, findfirst(entity.id, scene))
function Base.delete!(scene::EntityScene{S,D,I}, id::I) where {S,D,I}
entity_index = findfirst(id, scene)
if entity_index != nothing
deleteat!(scene, entity_index)
end
return scene
end
###
function Base.write(io::IO, frames::Vector{EntityScene{S,D,I}}) where {S,D,I}
println(io, length(frames))
for scene in frames
println(io, length(scene))
for entity in scene
write(io, entity.state)
print(io, "\n")
write(io, entity.def)
print(io, "\n")
write(io, string(entity.id))
print(io, "\n")
end
end
end
function Base.read(io::IO, ::Type{Vector{EntityScene{S,D,I}}}) where {S,D,I}
n = parse(Int, readline(io))
frames = Array{EntityScene{S,D,I}}(undef, n)
for i in 1 : n
m = parse(Int, readline(io))
scene = Scene(Entity{S,D,I}, m)
for j in 1 : m
state = read(io, S)
def = read(io, D)
strid = readline(io)
id = try
parse(I, strid)
catch e
if e isa MethodError
id = try
convert(I, strid)
catch e
error("Cannot parse $strid as $I")
end
else
error("Cannot parse $strid as $I")
end
end
push!(scene, Entity(state,def,id))
end
frames[i] = scene
end
return frames
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 5582 | """
VehicleState
A default type to represent an agent physical state (position, velocity).
It contains the position in the global frame, Frenet frame and the longitudinal velocity
# constructors
VehicleState(posG::VecSE2{Float64}, v::Float64)
VehicleState(posG::VecSE2{Float64}, roadway::Roadway, v::Float64)
VehicleState(posG::VecSE2{Float64}, lane::Lane, roadway::Roadway, v::Float64)
VehicleState(posF::Frenet, roadway::Roadway, v::Float64)
# fields
- `posG::VecSE2{Float64}` global position
- `posF::Frenet` lane relative position
- `v::Float64` longitudinal velocity
"""
struct VehicleState
posG::VecSE2{Float64} # global
posF::Frenet # lane-relative frame
v::Float64
end
VehicleState() = VehicleState(VecSE2(), NULL_FRENET, NaN)
VehicleState(posG::VecSE2{Float64}, v::Float64) = VehicleState(posG, NULL_FRENET, v)
VehicleState(posG::VecSE2{Float64}, roadway::Roadway, v::Float64) = VehicleState(posG, Frenet(posG, roadway), v)
VehicleState(posG::VecSE2{Float64}, lane::Lane, roadway::Roadway, v::Float64) = VehicleState(posG, Frenet(posG, lane, roadway), v)
VehicleState(posF::Frenet, roadway::Roadway, v::Float64) = VehicleState(posg(posF, roadway), posF, v)
posf(veh::VehicleState) = veh.posF
posg(veh::VehicleState) = veh.posG
vel(veh::VehicleState) = veh.v
velf(veh::VehicleState) = (s=veh.v*cos(veh.posF.ϕ), t=veh.v*sin(veh.posF.ϕ))
velg(veh::VehicleState) = (x=veh.v*cos(veh.posG.θ), y=veh.v*sin(veh.posG.θ))
posf(veh::Entity) = posf(veh.state)
posg(veh::Entity) = posg(veh.state)
vel(veh::Entity) = vel(veh.state)
velf(veh::Entity) = velf(veh.state)
velg(veh::Entity) = velg(veh.state)
Base.show(io::IO, s::VehicleState) = print(io, "VehicleState(", s.posG, ", ", s.posF, ", ", @sprintf("%.3f", s.v), ")")
function Base.write(io::IO, s::VehicleState)
@printf(io, "%.16e %.16e %.16e", s.posG.x, s.posG.y, s.posG.θ)
@printf(io, " %d %.16e %d %d", s.posF.roadind.ind.i, s.posF.roadind.ind.t, s.posF.roadind.tag.segment, s.posF.roadind.tag.lane)
@printf(io, " %.16e %.16e %.16e", s.posF.s, s.posF.t, s.posF.ϕ)
@printf(io, " %.16e", s.v)
end
function Base.read(io::IO, ::Type{VehicleState})
tokens = split(strip(readline(io)), ' ')
i = 0
posG = VecSE2(parse(Float64, tokens[i+=1]), parse(Float64, tokens[i+=1]), parse(Float64, tokens[i+=1]))
roadind = RoadIndex(CurveIndex(parse(Int, tokens[i+=1]), parse(Float64, tokens[i+=1])),
LaneTag(parse(Int, tokens[i+=1]), parse(Int, tokens[i+=1])))
posF = Frenet(roadind, parse(Float64, tokens[i+=1]), parse(Float64, tokens[i+=1]), parse(Float64, tokens[i+=1]))
v = parse(Float64, tokens[i+=1])
return VehicleState(posG, posF, v)
end
"""
Vec.lerp(a::VehicleState, b::VehicleState, t::Float64, roadway::Roadway)
Perform linear interpolation of the two vehicle states. Returns a VehicleState.
"""
function Vec.lerp(a::VehicleState, b::VehicleState, t::Float64, roadway::Roadway)
posG = lerp(a.posG, b.posG, t)
v = lerp(a.v, b.v, t)
VehicleState(posG, roadway, v)
end
"""
move_along(vehstate::VehicleState, roadway::Roadway, Δs::Float64;
ϕ₂::Float64=vehstate.posF.ϕ, t₂::Float64=vehstate.posF.t, v₂::Float64=vehstate.v)
returns a vehicle state after moving vehstate of a length Δs along its lane.
"""
function move_along(vehstate::VehicleState, roadway::Roadway, Δs::Float64;
ϕ₂::Float64=posf(vehstate).ϕ, t₂::Float64=posf(vehstate).t, v₂::Float64=vel(vehstate)
)
roadind = move_along(posf(vehstate).roadind, roadway, Δs)
try
footpoint = roadway[roadind]
catch
println(roadind)
end
footpoint = roadway[roadind]
posG = convert(VecE2, footpoint.pos) + polar(t₂, footpoint.pos.θ + π/2)
posG = VecSE2(posG.x, posG.y, footpoint.pos.θ + ϕ₂)
VehicleState(posG, roadway, v₂)
end
# XXX Should this go in features
"""
get_center(veh::Entity{VehicleState, D, I})
returns the position of the center of the vehicle
"""
get_center(veh::Entity{VehicleState, D, I}) where {D, I} = veh.state.posG
"""
get_footpoint(veh::Entity{VehicleState, D, I})
returns the position of the footpoint of the vehicle
"""
get_footpoint(veh::Entity{VehicleState, D, I}) where {D, I} = veh.state.posG + polar(veh.state.posF.t, veh.state.posG.θ-veh.state.posF.ϕ-π/2)
"""
get_front(veh::Entity{VehicleState, VehicleDef, I})
returns the position of the front of the vehicle
"""
get_front(veh::Entity{VehicleState, D, I}) where {D<:AbstractAgentDefinition, I} = veh.state.posG + polar(length(veh.def)/2, veh.state.posG.θ)
"""
get_rear(veh::Entity{VehicleState, VehicleDef, I})
returns the position of the rear of the vehicle
"""
get_rear(veh::Entity{VehicleState, D, I}) where {D<:AbstractAgentDefinition, I} = veh.state.posG - polar(length(veh.def)/2, veh.state.posG.θ)
"""
get_lane(roadway::Roadway, vehicle::Entity)
get_lane(roadway::Roadway, vehicle::VehicleState)
return the lane where `vehicle` is in.
"""
function get_lane(roadway::Roadway, vehicle::Entity)
get_lane(roadway, vehicle.state)
end
function get_lane(roadway::Roadway, vehicle::VehicleState)
lane_tag = vehicle.posF.roadind.tag
return roadway[lane_tag]
end
"""
Base.convert(::Type{Entity{S, VehicleDef, I}}, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition,I}
Converts the definition of an entity
"""
function Base.convert(::Type{Entity{S, VehicleDef, I}}, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition,I}
vehdef = VehicleDef(class(veh.def), length(veh.def), width(veh.def))
return Entity{S, VehicleDef, I}(veh.state, vehdef, veh.id)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3769 | #=
Benchmark two collision checkers:
collision_checker(veh1::Vehicle, veh2::Vehicle) from AutomotivePOMDPs using parallel axis theorem
is_colliding(veh1::Vehicle, veh2::Vehicle) from AutomotiveSimulator using Minkowski sums
=#
using AutomotiveSimulator
using BenchmarkTools
## Helpers
const ROADWAY = gen_straight_roadway(1, 20.0)
function create_vehicle(x::Float64, y::Float64, θ::Float64 = 0.0; id::Int64=1)
s = VehicleState(VecSE2(x, y, θ), ROADWAY, 0.0)
return Entity(s, VehicleDef(), id)
end
const VEH_REF = create_vehicle(0.0, 0.0, 0.0, id=1)
function no_collisions_PA(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert !collision_checker(VEH_REF, veh2) "Error for veh ", veh2
end
end
function collisions_PA(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert collision_checker(VEH_REF, veh2) "Error for veh ", veh2
end
end
function no_collisions_MI(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert !is_colliding(VEH_REF, veh2) "Error for veh ", veh2
end
end
function collisions_MI(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert is_colliding(VEH_REF, veh2) "Error for veh ", veh2
end
end
function consistency(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert is_colliding(VEH_REF, veh2) == collision_checker(VEH_REF, veh2) "Error for veh ", veh2
end
end
## Series of test 1: Far field
thetaspace = LinRange(0.0, 2*float(pi), 10)
xspace = LinRange(15.0, 300.0, 10)
yspace = LinRange(10.0, 300.0, 10)
no_collisions_PA(xspace, yspace, thetaspace)
no_collisions_MI(xspace, yspace, thetaspace)
consistency(xspace, yspace, thetaspace)
println(" -- TEST 1 : Far Range Collision Detection -- ")
println(" ")
println("Parallel Axis performance on far range negative collisions: ")
@btime no_collisions_PA($xspace, $yspace, $thetaspace)
println(" ")
println("Minkowski Sum performance on far range negative collisions: ")
@btime no_collisions_MI($xspace, $yspace, $thetaspace)
println(" ")
println(" ------------------------------------------")
println(" ")
## Series of test 2: Superposition
thetaspace = LinRange(0.0, 2*float(pi), 10)
xspace = LinRange(-2.0, 2.0, 10)
yspace = LinRange(1.5, 1.5, 10)
collisions_PA(xspace, yspace, thetaspace)
collisions_MI(xspace, yspace, thetaspace)
consistency(xspace, yspace, thetaspace)
println(" -- TEST 2 : Superposition Collision Detection -- ")
println(" ")
println("Parallel Axis performance on positive collisions: ")
@btime collisions_PA($xspace, $yspace, $thetaspace)
println(" ")
println("Minkowski Sum performance on positive collisions: ")
@btime collisions_MI($xspace, $yspace, $thetaspace)
println(" ")
println(" ------------------------------------------")
println(" ")
## Series of test 3: Close field
thetaspace = [0.0]
yspace = [2.5]
xspace = LinRange(-2.0, 2.0, 10)
no_collisions_PA(xspace, yspace, thetaspace)
no_collisions_MI(xspace, yspace, thetaspace)
consistency(xspace, yspace, thetaspace)
println(" -- TEST 3 : Close Range Collision Detection -- ")
println(" ")
println("Parallel Axis performance on close range negative collisions: ")
@btime no_collisions_PA($xspace, $yspace, $thetaspace)
println(" ")
println("Minkowski Sum performance on close range negative collisions: ")
@btime no_collisions_MI($xspace, $yspace, $thetaspace)
println(" ")
println(" ------------------------------------------")
println(" ")
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 1041 | using Test
using AutomotiveSimulator
using DataFrames
using Distributions
@testset "Vec" begin
include("vec-tests/vec_runtests.jl")
end
@testset "AutomotiveSimulator" begin
include("test_roadways.jl")
include("test_agent_definitions.jl")
include("test_scenes.jl")
include("test_states.jl")
include("test_collision_checkers.jl")
include("test_actions.jl")
include("test_features.jl")
include("test_behaviors.jl")
include("test_simulation.jl")
end
# Restore after AutomotiveVisualization v0.9 is tagged
@testset "doc tutorials" begin
@testset "basics" begin
include("../docs/lit/tutorials/straight_roadway.jl")
end
@testset "cameras" begin
include("../docs/lit/tutorials/stadium.jl")
end
@testset "overlays" begin
include("../docs/lit/tutorials/intersection.jl")
end
@testset "basics" begin
include("../docs/lit/tutorials/crosswalk.jl")
end
@testset "basics" begin
include("../docs/lit/tutorials/sidewalk.jl")
end
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3980 | @testset "action interface" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
s = VehicleState()
@test VehicleState() == propagate(veh, s, roadway, NaN)
end
@testset "AccelTurnrate" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
a = AccelTurnrate(0.1,0.2)
io = IOBuffer()
show(io, a)
close(io)
@test a == convert(AccelTurnrate, [0.1,0.2])
@test copyto!([NaN, NaN], AccelTurnrate(0.1,0.2)) == [0.1,0.2]
@test length(AccelTurnrate) == 2
s = propagate(veh, AccelTurnrate(0.0,0.0), roadway, 1.0)
@test isapprox(s.posG.x, veh.state.v)
@test isapprox(s.posG.y, 0.0)
@test isapprox(s.posG.θ, 0.0)
# TODO Test the get method
end
@testset "AccelDesang" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
a = AccelDesang(0.1,0.2)
@test a == convert(AccelDesang, [0.1,0.2])
@test copyto!([NaN, NaN], AccelDesang(0.1,0.2)) == [0.1,0.2]
@test length(AccelDesang) == 2
io = IOBuffer()
show(io, a)
s = propagate(veh, AccelDesang(0.0,0.0), roadway, 1.0)
@test isapprox(s.posG.x, veh.state.v*1.0)
@test isapprox(s.posG.y, 0.0)
@test isapprox(s.posG.θ, 0.0)
@test isapprox(s.v, veh.state.v)
end
@testset "AccelSteeringAngle" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
a = AccelSteeringAngle(0.1,0.2)
io = IOBuffer()
show(io, a)
close(io)
@test a == convert(AccelSteeringAngle, [0.1,0.2])
@test copyto!([NaN, NaN], AccelSteeringAngle(0.1,0.2)) == [0.1,0.2]
@test length(AccelSteeringAngle) == 2
# Check that propagate
# won't work with the veh type loaded from test_tra
@test_throws ErrorException propagate(veh, AccelSteeringAngle(0.0,0.0), roadway, 1.0)
veh = Entity(veh.state, BicycleModel(veh.def), veh.id)
s = propagate(veh, AccelSteeringAngle(0.0,0.0), roadway, 1.0)
@test isapprox(s.posG.x, veh.state.v*1.0)
@test isapprox(s.posG.y, 0.0)
@test isapprox(s.posG.θ, 0.0)
@test isapprox(s.v, veh.state.v)
# Test the branch condition within propagate
s = propagate(veh, AccelSteeringAngle(0.0,1.0), roadway, 1.0)
@test isapprox(s.v, veh.state.v)
end
@testset "LaneFollowingAccel" begin
a = LaneFollowingAccel(1.0)
roadway = gen_straight_roadway(3, 100.0)
s = VehicleState(VecSE2(0.0, 0.0, 0.0), roadway, 0.0)
veh = Entity(s, VehicleDef(), 1)
vehp = propagate(veh, a, roadway, 1.0)
@test posf(vehp).s == 0.5
end
@testset "LatLonAccel" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
a = LatLonAccel(0.1,0.2)
io = IOBuffer()
show(io, a)
close(io)
@test a == convert(LatLonAccel, [0.1,0.2])
@test copyto!([NaN, NaN], LatLonAccel(0.1,0.2)) == [0.1,0.2]
@test length(LatLonAccel) == 2
Δt = 0.1
s = propagate(veh, LatLonAccel(0.0,0.0), roadway, Δt)
@test isapprox(s.posG.x, veh.state.v*Δt)
@test isapprox(s.posG.y, 0.0)
@test isapprox(s.posG.θ, 0.0)
@test isapprox(s.v, veh.state.v)
end
@testset "Pedestrian LatLon" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = trajdata[1][1]
a = PedestrianLatLonAccel(0.5,1.0, roadway[LaneTag(2,1)])
Δt = 1.0
s = propagate(veh, a, roadway, Δt)
@test s.posF.roadind.tag == LaneTag(2,1)
@test isapprox(s.posG.x, 4.0)
@test isapprox(s.posG.y, 0.25)
end
@testset "Action Mapping" begin
a1 = LaneFollowingAccel(1.2)
a2 = LaneFollowingAccel(.4)
a3 = LaneFollowingAccel(0.)
actions = [a1, a2, a3]
ids = [:vehA, :vehB, :vehC]
action_mappings = Scene([EntityAction(a, id) for (a,id) in zip(actions, ids)])
for (action,id) in zip(actions, ids)
@test get_by_id(action_mappings, id).action.a == action.a
end
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 489 | struct DummyDefinition <: AbstractAgentDefinition end
@testset "agent definition" begin
d = DummyDefinition()
@test_throws ErrorException length(d)
@test_throws ErrorException width(d)
@test_throws ErrorException class(d)
d = VehicleDef()
@test class(d) == AgentClass.CAR
@test length(d) == 4.0
@test width(d) == 1.8
d2 = BicycleModel(VehicleDef())
@test class(d2) == class(d)
@test length(d2) == length(d)
@test width(d2) == width(d)
end | AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 10618 | struct FakeDriveAction end
struct FakeDriverModel <: DriverModel{FakeDriveAction} end
@testset "driver model interface" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = get(trajdata, 1, 1)
model = FakeDriverModel()
@test_throws MethodError reset_hidden_state!(model)
@test_throws MethodError observe!(model, Scene(Entity{VehicleState, VehicleDef, Int64}), roadway, 1)
@test_throws MethodError observe_from_history!(model, roadway, trajdata, 1, 2, 1)
@test action_type(model) <: FakeDriveAction
@test_throws MethodError set_desired_speed!(model, 0.0)
@test_throws ErrorException rand(model)
@test_throws MethodError pdf(model, FakeDriveAction())
@test_throws MethodError logpdf(model, FakeDriveAction())
end
@testset "IDM test" begin
roadway = gen_straight_roadway(1, 500.0)
models = Dict{Int, DriverModel}()
models[1] = IntelligentDriverModel(k_spd = 1.0, v_des = 10.0)
models[2] = IntelligentDriverModel(k_spd = 1.0)
set_desired_speed!(models[2], 5.0)
@test models[2].v_des == 5.0
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 5.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 70.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
scene = Scene([veh1, veh2])
n_steps = 40
dt = 0.1
simulate(scene, roadway, models, n_steps, dt)
@test isapprox(get_by_id(scene, 2).state.v, models[2].v_des)
# same with noise
models = Dict{Int, DriverModel}()
models[1] = IntelligentDriverModel(a = 0.0, k_spd = 1.0, v_des = 10.0, σ=1.0)
models[2] = IntelligentDriverModel(a = 0.0, k_spd = 1.0, v_des = 5.0, σ=1.0)
@test pdf(models[1], LaneFollowingAccel(0.0)) > 0.0
@test logpdf(models[1], LaneFollowingAccel(0.0)) < 0.0
n_steps = 40
dt = 0.1
scenes = simulate(scene, roadway, models, n_steps, dt)
observe_from_history!(IntelligentDriverModel(), roadway, scenes, 2)
# initializing vehicles too close
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 5.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 3.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
scene = Scene([veh1, veh2])
simulate(scene, roadway, models, 1, dt)
end
struct FakeLaneChanger <: LaneChangeModel{LaneChangeChoice} end
@testset "lane change interface" begin
l = LaneChangeChoice(DIR_RIGHT)
io = IOBuffer()
show(io, l)
close(io)
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh = get(trajdata, 1, 1)
model = FakeLaneChanger()
@test_throws MethodError reset_hidden_state!(model)
@test_throws MethodError observe!(model, Scene(), roadway, 1)
@test_throws MethodError set_desired_speed!(model, 0.0)
@test_throws ErrorException rand(model)
end
@testset "MOBIL" begin
timestep = 0.1
lanemodel = MOBIL()
set_desired_speed!(lanemodel,20.0)
@test lanemodel.mlon.v_des == 20.0
roadway = gen_straight_roadway(3, 1000.0)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,2)], 0.0), roadway, 10.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,2)], 20.0), roadway, 2.)
veh2 = Entity(veh_state, VehicleDef(), 2)
dt = 0.5
n_steps = 10
models = Dict{Int, DriverModel}()
models[1] = Tim2DDriver(mlane=MOBIL())
set_desired_speed!(models[1], 10.0)
models[2] = Tim2DDriver(mlane=MOBIL())
set_desired_speed!(models[2], 2.0)
scene = Scene([veh1, veh2])
scenes = simulate(scene, roadway, models, n_steps, dt)
@test posf(last(scenes)[1]).roadind.tag == LaneTag(1, 3)
@test posf(last(scenes)[2]).roadind.tag == LaneTag(1, 1)
end
@testset "Tim2DDriver" begin
timestep = 0.1
drivermodel = Tim2DDriver()
set_desired_speed!(drivermodel,20.0)
@test drivermodel.mlon.v_des == 20.0
@test drivermodel.mlane.v_des == 20.0
roadway = gen_straight_roadway(3, 1000.0)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,2)], 0.0), roadway, 10.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,2)], 10.0), roadway, 2.)
veh2 = Entity(veh_state, VehicleDef(), 2)
dt = 0.5
n_steps = 10
models = Dict{Int, DriverModel}()
models[1] = Tim2DDriver()
set_desired_speed!(models[1], 10.0)
models[2] = Tim2DDriver()
set_desired_speed!(models[2], 2.0)
scene = Scene([veh1, veh2])
scenes = simulate(scene, roadway, models, n_steps, dt)
@test scenes[end][1].state.posF.roadind.tag == LaneTag(1, 3)
@test scenes[end][2].state.posF.roadind.tag == LaneTag(1, 2)
end
@testset "lane following" begin
roadway = gen_straight_roadway(1, 500.0)
models = Dict{Int, DriverModel}()
models[1] = StaticLaneFollowingDriver()
@test pdf(models[1], LaneFollowingAccel(-1.0)) ≈ 0.0
@test logpdf(models[1], LaneFollowingAccel(-1.0)) ≈ -Inf
models[2] = PrincetonDriver(k = 1.0)
@test pdf(models[2], LaneFollowingAccel(-1.0)) == Inf
@test logpdf(models[2], LaneFollowingAccel(-1.0)) == Inf
set_desired_speed!(models[2], 5.0)
@test models[2].v_des == 5.0
models[3] = ProportionalSpeedTracker(k = 1.0)
@test pdf(models[3], LaneFollowingAccel(-1.0)) == Inf
@test logpdf(models[3], LaneFollowingAccel(-1.0)) == Inf
set_desired_speed!(models[3], 5.0)
@test models[3].v_des == 5.0
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 5.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 70.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 130.0), roadway, 5.)
veh3 = Entity(veh_state, VehicleDef(), 3)
scene = Scene([veh1, veh2, veh3])
n_steps = 40
dt = 0.1
scenes = simulate(scene, roadway, models, n_steps, dt)
@test isapprox(get_by_id(scenes[end], 2).state.v, models[2].v_des, atol=1e-3)
@test isapprox(get_by_id(scenes[end], 3).state.v, models[3].v_des)
# same wth noise
models = Dict{Int, DriverModel}()
models[1] = StaticLaneFollowingDriver()
models[2] = PrincetonDriver(k = 1.0, v_des=5.0, σ=1.0, a=0.0)
models[3] = ProportionalSpeedTracker(k = 1.0, v_des=5.0, σ=1.0, a=0.0)
@test pdf(models[3], LaneFollowingAccel(0.0)) > 0.0
@test logpdf(models[3], LaneFollowingAccel(0.0)) < 0.0
@test pdf(models[2], LaneFollowingAccel(0.0)) > 0.0
@test logpdf(models[2], LaneFollowingAccel(0.0)) < 0.0
n_steps = 40
dt = 0.1
scenes = simulate(scene, roadway, models, n_steps, dt)
@test isapprox(get_by_id(scenes[end], 2).state.v, models[2].v_des, atol=1.0)
@test isapprox(get_by_id(scenes[end], 3).state.v, models[3].v_des, atol=1.0)
end
function generate_sidewalk_env()
roadway_length = 100.
crosswalk_length = 15.
crosswalk_width = 6.0
crosswalk_pos = roadway_length/2
sidewalk_width = 3.0
sidewalk_pos = crosswalk_length/2 - sidewalk_width / 2
# Generate straight roadway of length roadway_length with 2 lanes.
# Returns a Roadway type (Array of segments).
# There is already a method to generate a simple straight roadway, which we use here.
roadway = gen_straight_roadway(2, roadway_length)
# Generate the crosswalk.
# Our crosswalk does not have a predefined method for generation, so we define it with a LaneTag and a curve.
n_samples = 2 # for curve generation
crosswalk = Lane(LaneTag(2,1), gen_straight_curve(VecE2(crosswalk_pos, -crosswalk_length/2),
VecE2(crosswalk_pos, crosswalk_length/2),
n_samples), width = crosswalk_width)
cw_segment = RoadSegment(2, [crosswalk])
push!(roadway.segments, cw_segment) # Append the crosswalk to the roadway
# Generate the sidewalk.
top_sidewalk = Lane(LaneTag(3, 1), gen_straight_curve(VecE2(0., sidewalk_pos),
VecE2(roadway_length, sidewalk_pos),
n_samples), width = sidewalk_width)
bottom_sidewalk = Lane(LaneTag(3, 2), gen_straight_curve(VecE2(0., -(sidewalk_pos - sidewalk_width)),
VecE2(roadway_length, -(sidewalk_pos - sidewalk_width)),
n_samples), width = sidewalk_width)
# Note: we subtract the sidewalk_width from the sidewalk position so that the edge is flush with the road.
sw_segment = RoadSegment(3, [top_sidewalk, bottom_sidewalk])
push!(roadway.segments, sw_segment)
sidewalk = [top_sidewalk, bottom_sidewalk]
return roadway, crosswalk, sidewalk
end
@testset "sidewalk pedestrian" begin
roadway, crosswalk, sidewalk = generate_sidewalk_env()
# dummy test for the constructor
ped=SidewalkPedestrianModel(timestep=0.1,
crosswalk= roadway[LaneTag(1,1)],
sw_origin = roadway[LaneTag(1,1)],
sw_dest = roadway[LaneTag(1,1)]
)
@test ped.ttc_threshold >= 1.0
timestep = 0.1
# Crossing pedestrian definition
ped_init_state = VehicleState(VecSE2(49.0,-3.0,0.), sidewalk[2], roadway, 1.3)
ped = Entity(ped_init_state, VehicleDef(AgentClass.PEDESTRIAN, 1.0, 1.0), 1)
# Car definition
car_initial_state = VehicleState(VecSE2(0.0, 0., 0.), roadway.segments[1].lanes[1],roadway, 8.0)
car = Entity(car_initial_state, VehicleDef(), 2)
scene = Scene([ped, car])
# Define a model for each entity present in the scene
models = Dict{Int, DriverModel}()
ped_id = 1
car_id = 2
models[ped_id] = SidewalkPedestrianModel(timestep=timestep,
crosswalk= crosswalk,
sw_origin = sidewalk[2],
sw_dest = sidewalk[1]
)
models[car_id] =
LatLonSeparableDriver( # produces LatLonAccels
ProportionalLaneTracker(), # lateral model
IntelligentDriverModel(), # longitudinal model
)
nticks = 300
scenes = simulate(scene, roadway, models, nticks, timestep)
ped = get_by_id(scenes[end], ped_id)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 2899 | const ROADWAY = gen_straight_roadway(1, 20.0)
function create_vehicle(x::Float64, y::Float64, θ::Float64 = 0.0; id::Int64=1)
s = VehicleState(VecSE2(x, y, θ), ROADWAY, 0.0)
return Entity(s, VehicleDef(), id)
end
const VEH_REF = create_vehicle(0.0, 0.0, 0.0, id=1)
function no_collisions(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert !collision_checker(VEH_REF, veh2) "Error for veh ", veh2
end
return true
end
function collisions(xspace, yspace, thetaspace)
for (x,y,th) in zip(xspace, yspace, thetaspace)
veh2 = create_vehicle(x,y,th,id=2)
@assert collision_checker(VEH_REF, veh2) "Error for veh ", veh2
end
return true
end
@testset "Minkowski" begin
@test AutomotiveSimulator.cyclic_shift_left!([1,2,3,4], 1, 4) == [2,3,4,1]
@test AutomotiveSimulator.cyclic_shift_left!([1,2,3,4], 2, 4) == [3,4,1,2]
@test AutomotiveSimulator.cyclic_shift_left!([1,2,3,4,5,6,7], 1, 4) == [2,3,4,1,5,6,7]
@test AutomotiveSimulator.cyclic_shift_left!([1,2,3,4,5,6,7], 2, 4) == [3,4,1,2,5,6,7]
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
scene = Scene(Entity{VehicleState, VehicleDef, Int64})
col = get_first_collision(trajdata[1])
@test col.is_colliding
@test col.A == 1
@test col.B == 2
@test get_first_collision(trajdata[1], CPAMemory()).is_colliding == true
scene = trajdata[1]
@test is_collision_free(scene) == false
@test is_collision_free(scene, [1]) == false
@test is_colliding(scene[1], scene[2])
@test get_distance(scene[1], scene[2]) == 0
@test is_collision_free(trajdata[2])
get_distance(scene[1], scene[2])
roadway = gen_straight_roadway(2, 100.0)
veh1 = Entity(VehicleState(VecSE2(0.0, 0.0, 0.0), roadway, 10.0), VehicleDef(), 1)
veh2 = Entity(VehicleState(VecSE2(10.0, 0.0, 0.0), roadway, 5.0), VehicleDef(), 2)
scene = Scene([veh1, veh2])
@test is_collision_free(scene)
@test get_distance(veh1, veh2) ≈ 6.0
end
@testset "parallel axis" begin
## Series of test 1: Far field
thetaspace = LinRange(0.0, 2*float(pi), 10)
xspace = LinRange(15.0, 300.0, 10)
yspace = LinRange(10.0, 300.0, 10)
@test no_collisions(xspace, yspace, thetaspace)
## Series of test 2: Superposition
thetaspace = LinRange(0.0, 2*float(pi), 10)
xspace = LinRange(-2.0, 2.0, 10)
yspace = LinRange(1.5, 1.5, 10)
@test collisions(xspace,yspace,thetaspace)
## Close but no collisions
veh2 = create_vehicle(0.0, 2.2, 0.0, id=2)
@test !collision_checker(VEH_REF, veh2)
veh2 = create_vehicle(3.1, 2.2, 1.0pi, id=2)
@test !collision_checker(VEH_REF, veh2)
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
scene = trajdata[1]
@test collision_checker(scene, 1)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 12661 | @testset "neighbor features" begin
scene=Scene(Entity{VehicleState, BicycleModel, Int}, 100)
roadway=gen_straight_roadway(3, 200.0, lane_width=3.0)
push!(scene,Entity(VehicleState(VecSE2(30.0,3.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),1))
push!(scene,Entity(VehicleState(VecSE2(20.0,3.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),2))
push!(scene,Entity(VehicleState(VecSE2(40.0,3.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),3))
push!(scene,Entity(VehicleState(VecSE2(20.0,0.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),4))
push!(scene,Entity(VehicleState(VecSE2(40.0,0.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),5))
push!(scene,Entity(VehicleState(VecSE2(20.0,6.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),6))
push!(scene,Entity(VehicleState(VecSE2(40.0,6.0,0.0), roadway, 0.0),
BicycleModel(VehicleDef(AgentClass.CAR, 4.826, 1.81)),7))
@test find_neighbor(scene, roadway, scene[1]) == NeighborLongitudinalResult(3,10.0)
@test find_neighbor(scene, roadway, scene[1], rear=true) == NeighborLongitudinalResult(2,10.0)
@test find_neighbor(scene, roadway, scene[1], lane=leftlane(roadway, scene[1])) == NeighborLongitudinalResult(7,10.0)
@test find_neighbor(scene, roadway, scene[1], lane=leftlane(roadway, scene[1]), rear=true) == NeighborLongitudinalResult(6,10.0)
@test find_neighbor(scene, roadway, scene[1], lane=rightlane(roadway, scene[1])) == NeighborLongitudinalResult(5,10.0)
@test find_neighbor(scene, roadway, scene[1], lane=rightlane(roadway, scene[1]), rear=true) == NeighborLongitudinalResult(4,10.0)
trajdata = get_test_trajdata(roadway)
scene = trajdata[1]
@test find_neighbor(scene, roadway, scene[1]) == NeighborLongitudinalResult(2, 3.0)
@test find_neighbor(scene, roadway, scene[2]) == NeighborLongitudinalResult(nothing, 250.0)
scene = trajdata[2]
@test find_neighbor(scene, roadway, scene[1]) == NeighborLongitudinalResult(2, 4.0)
@test find_neighbor(scene, roadway, scene[2]) == NeighborLongitudinalResult(nothing, 250.0)
roadway = gen_stadium_roadway(1)
scene = Scene(Entity{VehicleState, VehicleDef, Int64}, 2)
scene.n = 2
def = VehicleDef(AgentClass.CAR, 2.0, 1.0)
function place_at!(i, s)
roadproj = proj(VecSE2(0.0,0.0,0.0), roadway)
roadind = RoadIndex(roadproj.curveproj.ind, roadproj.tag)
roadind = move_along(roadind, roadway, s)
frenet = Frenet(roadind, roadway[roadind].s, 0.0, 0.0)
state = VehicleState(frenet, roadway, 0.0)
scene[i] = Entity(state, def, i)
end
place_at!(1, 0.0)
place_at!(2, 0.0)
foreinfo = find_neighbor(scene, roadway, scene[1], max_distance=Inf)
@test isapprox(foreinfo.Δs, 0.0)
place_at!(2, 100.0)
foreinfo = find_neighbor(scene, roadway, scene[1], max_distance=Inf)
@test foreinfo.ind == 2
@test isapprox(foreinfo.Δs, 100.0)
foreinfo = find_neighbor(scene, roadway, scene[2], max_distance=Inf)
@test foreinfo.ind == 1
@test isapprox(foreinfo.Δs, 277.07, atol=1e-2)
place_at!(2, 145.0)
foreinfo = find_neighbor(scene, roadway, scene[1], max_distance=Inf)
@test foreinfo.ind == 2
@test isapprox(foreinfo.Δs, 145.0, atol=1e-5)
place_at!(2, 240.0)
foreinfo = find_neighbor(scene, roadway, scene[1], max_distance=Inf)
@test foreinfo.ind == 2
@test isapprox(foreinfo.Δs, 240.0, atol=1e-5)
place_at!(1, 240.0)
foreinfo = find_neighbor(scene, roadway, scene[1], max_distance=Inf)
@test foreinfo.ind == 2
@test isapprox(foreinfo.Δs, 0.0, atol=1e-5)
################################################
# get_frenet_relative_position
place_at!(1, 0.0)
place_at!(2, 10.0)
frp = get_frenet_relative_position(scene[2].state.posG, scene[1].state.posF.roadind, roadway, max_distance_fore=Inf)
@test frp.origin == scene[1].state.posF.roadind
@test frp.target.ind.i == 1
@test isapprox(frp.target.ind.t, 0.1, atol=0.01)
@test frp.target.tag == scene[1].state.posF.roadind.tag
@test isapprox(frp.Δs, 10.0, atol=1e-2)
@test isapprox(frp.t, 0.0, atol=1e-5)
@test isapprox(frp.ϕ, 0.0, atol=1e-7)
place_at!(1, 10.0)
place_at!(2, 20.0)
frp = get_frenet_relative_position(scene[2].state.posG, scene[1].state.posF.roadind, roadway, max_distance_fore=Inf)
@test frp.origin == scene[1].state.posF.roadind
@test frp.target.ind.i == 1
@test isapprox(frp.target.ind.t, 0.2, atol=0.01)
@test frp.target.tag == scene[1].state.posF.roadind.tag
@test isapprox(frp.Δs, 10.0, atol=1e-2)
@test isapprox(frp.t, 0.0, atol=1e-5)
@test isapprox(frp.ϕ, 0.0, atol=1e-7)
place_at!(1, 0.0)
place_at!(2, 120.0)
frp = get_frenet_relative_position(scene[2].state.posG, scene[1].state.posF.roadind, roadway, max_distance_fore=Inf)
@test frp.target.tag == LaneTag(1, 1)
@test scene[1].state.posF.roadind.tag == LaneTag(6, 1)
@test isapprox(frp.Δs, 120.0, atol=1e-2)
@test isapprox(frp.t, 0.0, atol=1e-5)
@test isapprox(frp.ϕ, 0.0, atol=1e-7)
place_at!(1, 0.0)
place_at!(2, 250.0)
frp = get_frenet_relative_position(scene[2].state.posG, scene[1].state.posF.roadind, roadway, max_distance_fore=Inf)
@test frp.target.tag != scene[1].state.posF.roadind.tag
@test isapprox(frp.Δs, 250.0, atol=1e-2)
@test isapprox(frp.t, 0.0, atol=1e-5)
@test isapprox(frp.ϕ, 0.0, atol=1e-7)
end
@testset "feature extraction" begin
roadway = gen_straight_roadway(4, 100.0)
scene = Scene([Entity(VehicleState(VecSE2( 0.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Entity(VehicleState(VecSE2(10.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
])
# test each feature individually
pos1 = extract_feature(featuretype(posgx), posgx, roadway, [scene], 1)
pos2 = extract_feature(featuretype(posgx), posgx, roadway, [scene], 2)
poss = extract_feature(featuretype(posgx), posgx, roadway, [scene], [1,2])
@test poss[1][1] == pos1[1]
@test poss[2][1] == pos2[2]
@test pos1[1] == 0.0
@test pos2[2] == 10.0
scene = Scene([Entity(VehicleState(VecSE2(1.1,1.2,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1)])
posy = extract_feature(featuretype(posgy), posgy, roadway, [scene], 1)
@test posy[1] == 1.2
posθ = extract_feature(featuretype(posgθ), posgθ, roadway, [scene], 1)
@test posθ[1] == 0.0
poss = extract_feature(featuretype(posfs), posfs, roadway, [scene], 1)
@test poss[1] == 1.1
post = extract_feature(featuretype(posft), posft, roadway, [scene], 1)
@test post[1] == 1.2
posϕ = extract_feature(featuretype(posfϕ), posfϕ, roadway, [scene], 1)
@test posϕ[1] == 0.0
scene = Scene([Entity(VehicleState(VecSE2(1.1,1.2,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Entity(VehicleState(VecSE2(1.5,1.2,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2)])
coll = extract_feature(featuretype(iscolliding), iscolliding, roadway, [scene], 1)
@test coll[1]
d = extract_feature(featuretype(distance_to(1)), distance_to(1), roadway, [scene], 1)
@test d[1] == 0.0
d = extract_feature(featuretype(distance_to(2)), distance_to(2), roadway, [scene], 1)
@test d[1] ≈ 0.4
df = extract_feature(featuretype(turn_rate_g), turn_rate_g, roadway, [scene, scene], [1])
@test df[1][1] === missing
@test df[1][2] == 0.0
# extract multiple features
roadway = gen_straight_roadway(3, 1000.0, lane_width=1.0)
scene = Scene([
Entity(VehicleState(VecSE2( 0.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Entity(VehicleState(VecSE2(10.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
])
dfs = extract_features((iscolliding, markerdist_left, markerdist_right), roadway, [scene], [1,2])
@test isapprox(dfs[1][1,3], 0.5)
@test isapprox(dfs[2][1,3], 0.5)
@test isapprox(dfs[1][1,2], 0.5)
@test isapprox(dfs[2][1,2], 0.5)
# integration testing, all the features
feature_list = (posgx, posgy, posgθ, posfs, posft, posfϕ, vel, velfs, velft, velgx, velgy,
time_to_crossing_right, time_to_crossing_left,
estimated_time_to_lane_crossing, iswaiting, acc, accfs, accft, jerk,
jerkft, turn_rate_g, turn_rate_f, isbraking, isaccelerating,
lane_width, lane_offset_left, lane_offset_right, has_lane_left,
has_lane_right, lane_curvature)
dfs = extract_features(feature_list, roadway, [scene, scene], [1,2])
for id=[1,2]
@test ncol(dfs[id]) == length(feature_list)
@test nrow(dfs[id]) == 2
end
scene = Scene([
Entity(VehicleState(VecSE2( 1.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 1),
Entity(VehicleState(VecSE2(10.0,0.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 2),
Entity(VehicleState(VecSE2(12.0,1.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 3),
Entity(VehicleState(VecSE2( 0.0,1.0,0.0), roadway, 10.0), VehicleDef(AgentClass.CAR, 5.0, 2.0), 4),
])
dfs= extract_features((dist_to_front_neighbor, front_neighbor_speed, time_to_collision), roadway, [scene], [1,2,3,4])
@test isapprox(dfs[1][1,1], 9.0)
# type inferrence
for fun in feature_list
@inferred featuretype(fun)
end
end # features
@testset "lidar sensor" begin
#=
Create a scene with 7 vehicles, an ego in the middle and 6 surrounding
vehicles. Use this setup to check that lidar sensors work for various
range and angle settings.
=#
num_veh = 7
ego_index = 1
roadway = gen_straight_roadway(4, 400.)
scene = Scene(Entity{VehicleState,VehicleDef,Int64}, num_veh)
# order: ego, fore, rear, left, right, fore_fore, fore_fore_fore
speeds = [10., 15., 15., 0., -5, 20., 20.]
positions = [200., 220., 150., 200., 200., 240., 350.]
lanes = [2,2,2,4,1,2,2]
for i in 1:num_veh
lane = roadway.segments[1].lanes[lanes[i]]
road_idx = RoadIndex(proj(VecSE2(0.0, 0.0, 0.0), lane, roadway))
veh_state = VehicleState(Frenet(road_idx, roadway), roadway, speeds[i])
veh_state = move_along(veh_state, roadway, positions[i])
veh_def = VehicleDef(AgentClass.CAR, 2., 2.)
push!(scene, Entity(veh_state, veh_def, i))
end
# basic lidar with sufficient range for all vehicles
nbeams = 4
lidar = LidarSensor(nbeams, max_range=200., angle_offset=0.)
observe!(lidar, scene, roadway, ego_index)
# order: right, fore, left, back
@test isapprox(lidar.ranges[1], 2.0, atol=4)
@test isapprox(lidar.ranges[2], 19.0, atol=4)
@test isapprox(lidar.ranges[3], 5.0, atol=4)
@test isapprox(lidar.ranges[4], 49.0, atol=4)
@test isapprox(lidar.range_rates[1], 0.0, atol=4)
@test isapprox(lidar.range_rates[2], 5.0, atol=4)
@test isapprox(lidar.range_rates[3], 0.0, atol=4)
@test isapprox(lidar.range_rates[4], -5.0, atol=4)
# angles are such that all the vehicles are missed
nbeams = 4
lidar = LidarSensor(nbeams, max_range=200., angle_offset=π/4)
observe!(lidar, scene, roadway, ego_index)
# order: right, fore, left, back
@test isapprox(lidar.ranges[1], 200.0, atol=4)
@test isapprox(lidar.ranges[2], 200.0, atol=4)
@test isapprox(lidar.ranges[3], 200.0, atol=4)
@test isapprox(lidar.ranges[4], 200.0, atol=4)
@test isapprox(lidar.range_rates[1], 0.0, atol=4)
@test isapprox(lidar.range_rates[2], 0.0, atol=4)
@test isapprox(lidar.range_rates[3], 0.0, atol=4)
@test isapprox(lidar.range_rates[4], 0.0, atol=4)
# range short enough that it misses the rear vehicle
nbeams = 4
lidar = LidarSensor(nbeams, max_range=20., angle_offset=0.)
observe!(lidar, scene, roadway, ego_index)
# order: right, fore, left, back
@test isapprox(lidar.ranges[1], 2.0, atol=4)
@test isapprox(lidar.ranges[2], 19.0, atol=4)
@test isapprox(lidar.ranges[3], 5.0, atol=4)
@test isapprox(lidar.ranges[4], 20.0, atol=4)
@test isapprox(lidar.range_rates[1], 0.0, atol=4)
@test isapprox(lidar.range_rates[2], 5.0, atol=4)
@test isapprox(lidar.range_rates[3], 0.0, atol=4)
@test isapprox(lidar.range_rates[4], 0.0, atol=4)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 26561 | get_test_curve1() = [CurvePt(VecSE2(0.0,0.0,0.0), 0.0),
CurvePt(VecSE2(1.0,0.0,0.0), 1.0),
CurvePt(VecSE2(3.0,0.0,0.0), 3.0)]
function get_test_roadway()
roadway = Roadway()
seg1 = RoadSegment(1,
[Lane(LaneTag(1,1),
[CurvePt(VecSE2(-2.0,0.0,0.0), 0.0),
CurvePt(VecSE2(-1.0,0.0,0.0), 1.0)]),
Lane(LaneTag(1,2),
[CurvePt(VecSE2(-2.0,1.0,0.0), 0.0),
CurvePt(VecSE2(-1.0,1.0,0.0), 1.0)]),
Lane(LaneTag(1,3),
[CurvePt(VecSE2(-2.0,2.0,0.0), 0.0),
CurvePt(VecSE2(-1.0,2.0,0.0), 1.0)])
])
seg2 = RoadSegment(2,
[Lane(LaneTag(2,1),
[CurvePt(VecSE2(0.0,0.0,0.0), 0.0),
CurvePt(VecSE2(1.0,0.0,0.0), 1.0),
CurvePt(VecSE2(2.0,0.0,0.0), 2.0),
CurvePt(VecSE2(3.0,0.0,0.0), 3.0)]),
Lane(LaneTag(2,2),
[CurvePt(VecSE2(0.0,1.0,0.0), 0.0),
CurvePt(VecSE2(1.0,1.0,0.0), 1.0),
CurvePt(VecSE2(2.0,1.0,0.0), 2.0),
CurvePt(VecSE2(3.0,1.0,0.0), 3.0)]),
Lane(LaneTag(2,3),
[CurvePt(VecSE2(0.0,2.0,0.0), 0.0),
CurvePt(VecSE2(1.0,2.0,0.0), 1.0),
CurvePt(VecSE2(2.0,2.0,0.0), 2.0),
CurvePt(VecSE2(3.0,2.0,0.0), 3.0)])
])
seg3 = RoadSegment(3,
[Lane(LaneTag(3,1),
[CurvePt(VecSE2(4.0,0.0,0.0), 0.0),
CurvePt(VecSE2(5.0,0.0,0.0), 1.0)]),
Lane(LaneTag(3,2),
[CurvePt(VecSE2(4.0,1.0,0.0), 0.0),
CurvePt(VecSE2(5.0,1.0,0.0), 1.0)]),
Lane(LaneTag(3,3),
[CurvePt(VecSE2(4.0,2.0,0.0), 0.0),
CurvePt(VecSE2(5.0,2.0,0.0), 1.0)])
])
for i in 1:3
connect!(seg1.lanes[i], seg2.lanes[i])
connect!(seg2.lanes[i], seg3.lanes[i])
end
push!(roadway.segments, seg1)
push!(roadway.segments, seg2)
push!(roadway.segments, seg3)
roadway
end
@testset "Curves" begin
p = lerp(CurvePt(VecSE2(0.0,0.0,0.0), 0.0), CurvePt(VecSE2(1.0,2.0,3.0), 4.0), 0.25)
show(IOBuffer(), p)
@test isapprox(convert(VecE2, p.pos), VecE2(0.25, 0.5))
@test isapprox(p.pos.θ, 0.75)
@test isapprox(p.s, 1.0)
show(IOBuffer(), CurveIndex(1,0.0))
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(1.0,0.0), VecE2(1.0,0.0)), 1.0)
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(1.0,0.0), VecE2(0.5,0.0)), 0.5)
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(1.0,0.0), VecE2(0.5,0.5)), 0.5)
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(1.0,1.0), VecE2(0.5,0.5)), 0.5)
@test isapprox(get_lerp_time(VecE2(1.0,0.0), VecE2(2.0,0.0), VecE2(1.5,0.5)), 0.5)
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(-1.0,0.0), VecE2(1.0,0.0)), 0.0)
@test isapprox(get_lerp_time(VecE2(0.0,0.0), VecE2(-1.0,0.0), VecE2(-0.75,0.0)), 0.75)
curve = get_test_curve1()
@inferred index_closest_to_point(curve, VecE2(0.0,0.0))
@test index_closest_to_point(curve, VecE2(0.0,0.0)) == 1
@test index_closest_to_point(curve, VecE2(1.0,0.0)) == 2
@test index_closest_to_point(curve, VecE2(2.1,0.0)) == 3
@test index_closest_to_point(curve, VecE2(0.49,0.0)) == 1
@test index_closest_to_point(curve, VecE2(1.9,-100.0)) == 2
@test index_closest_to_point(curve, VecSE2(1.9,-100.0,0.0)) == 2
@test index_closest_to_point(curve, VecSE2(-1.0,0.0,0.0)) == 1
@test index_closest_to_point([CurvePt(VecSE2(0.0,0.0,0.0),0.0)], VecE2(0.0,0.0)) == 1
@test get_curve_index(curve, 0.0) == CurveIndex(1, 0.0)
@test get_curve_index(curve, 1.0) == CurveIndex(2, 0.0)
@test get_curve_index(curve, 1.5) == CurveIndex(2, 0.25)
@test get_curve_index(curve, 3.5) == CurveIndex(2, 1.0)
@test get_curve_index(curve,-0.5) == CurveIndex(1, 0.0)
p = curve[CurveIndex(1, 0.75)]
@test isapprox(convert(VecE2, p.pos), VecE2(0.75, 0.0))
@test isapprox(p.pos.θ, 0.0)
@test isapprox(p.s, 0.75)
@test get_curve_index(CurveIndex(1, 0.0), curve, 0.25) == CurveIndex(1,0.25)
@test get_curve_index(CurveIndex(1, 0.0), curve, 1.25) == CurveIndex(2,0.125)
@test get_curve_index(CurveIndex(1, 0.5), curve, 1.50) == CurveIndex(2,0.5)
@test get_curve_index(CurveIndex(1, 0.5), curve, -0.25) == CurveIndex(1,0.25)
@test get_curve_index(CurveIndex(2, 0.0), curve, -0.50) == CurveIndex(1,0.50)
res = proj(VecSE2(0.0,0.0,0.0), curve)
@inferred proj(VecSE2(0.0,0.0,0.0), curve)
show(IOBuffer(), res)
@test res.ind == CurveIndex(1, 0.0)
@test isapprox(res.t, 0.0)
@test isapprox(res.ϕ, 0.0)
res = proj(VecSE2(0.25,0.5,0.1), curve)
@inferred proj(VecSE2(0.25,0.5,0.1), curve)
@test res.ind == CurveIndex(1, 0.25)
@test isapprox(res.t, 0.5)
@test isapprox(res.ϕ, 0.1)
res = proj(VecSE2(0.25,-0.5,-0.1), curve)
@test res.ind == CurveIndex(1, 0.25)
@test isapprox(res.t, -0.5)
@test isapprox(res.ϕ, -0.1)
res = proj(VecSE2(1.5,0.5,-0.1), curve)
@test res.ind == CurveIndex(2, 0.25)
@test isapprox(res.t, 0.5)
@test isapprox(res.ϕ, -0.1)
res = proj(VecSE2(10.0,0.0,0.0), curve)
@test res.ind == CurveIndex(length(curve)-1, 1.0)
@test isapprox(res.t, 0.0)
@test isapprox(res.ϕ, 0.0)
curve2 = [CurvePt(VecSE2(-1.0,-1.0,π/4), 0.0),
CurvePt(VecSE2( 1.0, 1.0,π/4), hypot(2.0,2.0)),
CurvePt(VecSE2( 3.0, 3.0,π/4), hypot(4.0,4.0))]
res = proj(VecSE2(0.0,0.0,0.0), curve2)
@test res.ind == CurveIndex(1, 0.5)
@test isapprox(res.t, 0.0)
@test isapprox(res.ϕ, -π/4)
end # curve tests
@testset "roadways" begin
curve = get_test_curve1()
lanetag = LaneTag(1,1)
lane = Lane(lanetag, curve)
show(IOBuffer(), lanetag)
@test !has_next(lane)
@test !has_prev(lane)
show(IOBuffer(), RoadIndex(CurveIndex(1,0.0), lanetag))
roadway = get_test_roadway()
io = IOBuffer()
show(io, roadway)
close(io)
lane = roadway[LaneTag(1,1)]
@test has_next(lane)
@test !has_prev(lane)
@test lane.exits[1].target == RoadIndex(CurveIndex(1,0.0), LaneTag(2,1))
lane = roadway[LaneTag(2,1)]
@test has_next(lane)
@test has_prev(lane)
@test lane.exits[1].target == RoadIndex(CurveIndex(1,0.0), LaneTag(3,1))
@test lane.entrances[1].target == RoadIndex(CurveIndex(1,1.0), LaneTag(1,1))
res = proj(VecSE2(1.0,0.0,0.0), lane, roadway)
@inferred proj(VecSE2(1.0,0.0,0.0), lane, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.0,0.0,0.0), lane, roadway, move_along_curves=false)
@inferred proj(VecSE2(1.0,0.0,0.0), lane, roadway, move_along_curves=false)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.5,0.25,0.1), lane, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.5)
@test isapprox(res.curveproj.t, 0.25)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(0.0,0.0,0.0), lane, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(-0.75,0.0,0.0), lane, roadway)
@test res.curveproj.ind == CurveIndex(0, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(-1.75,0.0,0.0), lane, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == prev_lane(lane, roadway).tag
res = proj(VecSE2(-1.75,0.0,0.0), lane, roadway, move_along_curves=false)
@test res.curveproj.ind == CurveIndex(0, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(4.25,0.2,0.1), lane, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(4.25,0.2,0.1), lane, roadway, move_along_curves=false)
@test res.curveproj.ind == CurveIndex(4, 1.0)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(3.25,0.2,0.1), lane, roadway)
@test res.curveproj.ind == CurveIndex(4, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(4.25,0.2,0.1), prev_lane(lane, roadway), roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(-0.75,0.0,0.0), next_lane(lane, roadway), roadway)
@test res.curveproj.ind == CurveIndex(0, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
####
seg = roadway[2]
res = proj(VecSE2(1.0,0.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.5,0.25,0.1), seg, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.5)
@test isapprox(res.curveproj.t, 0.25)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(0.0,0.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(-0.75,0.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(0, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(-1.75,0.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == prev_lane(lane, roadway).tag
res = proj(VecSE2(4.25,0.2,0.1), seg, roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(3.25,0.2,0.1), seg, roadway)
@test res.curveproj.ind == CurveIndex(4, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(4.25,0.2,0.1), roadway[1], roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(-0.75,0.0,0.0), roadway[3], roadway)
@test res.curveproj.ind == CurveIndex(0, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.0,1.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == LaneTag(2,2)
res = proj(VecSE2(1.0,2.0,0.0), seg, roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == LaneTag(2,3)
###
res = proj(VecSE2(1.0,0.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.5,0.25,0.1), roadway)
@test res.curveproj.ind == CurveIndex(2, 0.5)
@test isapprox(res.curveproj.t, 0.25)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(0.0,0.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(1, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(-0.75,0.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(2, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == prev_lane(lane, roadway).tag
res = proj(VecSE2(-1.75,0.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == prev_lane(lane, roadway).tag
res = proj(VecSE2(4.25,0.2,0.1), roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(3.25,0.2,0.1), roadway)
@test res.curveproj.ind == CurveIndex(4, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == lane.tag
res = proj(VecSE2(4.25,0.2,0.1), roadway[1], roadway)
@test res.curveproj.ind == CurveIndex(1, 0.25)
@test isapprox(res.curveproj.t, 0.2)
@test isapprox(res.curveproj.ϕ, 0.1)
@test res.tag == next_lane(lane, roadway).tag
res = proj(VecSE2(-0.75,0.0,0.0), roadway[3], roadway)
@test res.curveproj.ind == CurveIndex(0, 0.25)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == lane.tag
res = proj(VecSE2(1.0,1.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == LaneTag(2,2)
res = proj(VecSE2(1.0,2.0,0.0), roadway)
@test res.curveproj.ind == CurveIndex(2, 0.0)
@test isapprox(res.curveproj.t, 0.0)
@test isapprox(res.curveproj.ϕ, 0.0)
@test res.tag == LaneTag(2,3)
###
roadind_0 = RoadIndex(CurveIndex(1, 0.0), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, 0.0)
@inferred move_along(roadind_0, roadway, 0.0)
@test roadind == roadind_0
roadind = move_along(roadind_0, roadway, 1.0)
@test roadind == RoadIndex(CurveIndex(2,0.0), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, 1.25)
@test roadind == RoadIndex(CurveIndex(2,0.25), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, 3.0)
@test roadind == RoadIndex(CurveIndex(3,1.0), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, 4.0)
@test roadind == RoadIndex(CurveIndex(1,0.0), LaneTag(3,1))
roadind = move_along(roadind_0, roadway, 4.5)
@test roadind == RoadIndex(CurveIndex(1,0.5), LaneTag(3,1))
roadind = move_along(roadind_0, roadway, 3.75)
@test roadind == RoadIndex(CurveIndex(0,0.75), LaneTag(3,1))
roadind = move_along(roadind_0, roadway, -1.0)
@test roadind == RoadIndex(CurveIndex(0,0.0), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, -1.75)
@test roadind == RoadIndex(CurveIndex(1,0.25), LaneTag(1,1))
roadind = move_along(roadind_0, roadway, -0.75)
@test roadind == RoadIndex(CurveIndex(0,0.25), LaneTag(2,1))
roadind = move_along(roadind_0, roadway, -Inf)
@test roadind == RoadIndex(CurveIndex(1,0.0), LaneTag(1,1))
roadind = move_along(roadind_0, roadway, Inf)
@test roadind == RoadIndex(CurveIndex(1,1.0), LaneTag(3,1))
####
@test n_lanes_right(roadway, roadway[LaneTag(2,1)]) == 0
@test n_lanes_right(roadway, roadway[LaneTag(2,2)]) == 1
@test n_lanes_right(roadway, roadway[LaneTag(2,3)]) == 2
@test n_lanes_left(roadway, roadway[LaneTag(2,1)]) == 2
@test n_lanes_left(roadway, roadway[LaneTag(2,2)]) == 1
@test n_lanes_left(roadway, roadway[LaneTag(2,3)]) == 0
####
roadway = get_test_roadway()
all_lanes = lanes(roadway)
all_lane_tags = lanetags(roadway)
@test all_lane_tags == [l.tag for l in all_lanes]
@test all_lanes == Lane{Float64}[roadway[tag] for tag in all_lane_tags]
for i=1:2
for j=1:3
@test roadway[LaneTag(i,j)] in all_lanes
@test LaneTag(i,j) in all_lane_tags
end
end
end # roadway test
@testset "roadway read/write" begin
roadway = Roadway()
seg1 = RoadSegment(1,
[Lane(LaneTag(1,1),
[CurvePt(VecSE2(0.0,0.0,0.0), 0.0),
CurvePt(VecSE2(1.0,0.0,0.0), 1.0)],
width=1.0,
boundary_left = LaneBoundary(:solid, :white),
boundary_right = LaneBoundary(:broken, :yellow)),
Lane(LaneTag(1,2),
[CurvePt(VecSE2(0.0,1.0,0.0), 0.0),
CurvePt(VecSE2(1.0,1.0,0.0), 1.0)],
width=2.0,
boundary_left = LaneBoundary(:double, :white))],
)
seg2 = RoadSegment(2,
[Lane(LaneTag(2,1),
[CurvePt(VecSE2(4.0,0.0,0.0), 0.0),
CurvePt(VecSE2(5.0,0.0,0.0), 1.0)]),
Lane(LaneTag(2,2),
[CurvePt(VecSE2(4.0,1.0,0.0), 0.0),
CurvePt(VecSE2(5.0,1.0,0.0), 1.0)])],
)
connect!(seg1.lanes[1], seg2.lanes[2])
push!(roadway.segments, seg1)
push!(roadway.segments, seg2)
############
path, io = mktemp()
write(io, roadway)
close(io)
lines = open(readlines, path)
for (line_orig, line_test) in zip(lines,
[
"ROADWAY",
"2",
"1",
" 2",
" 1",
" 1.000",
" -Inf Inf",
" solid white",
" broken yellow",
" 1",
" D (1 1.000000) 1 0.000000 2 2",
" 2",
" (0.0000 0.0000 0.000000) 0.0000 NaN NaN",
" (1.0000 0.0000 0.000000) 1.0000 NaN NaN",
" 2",
" 2.000",
" -Inf Inf",
" double white",
" unknown unknown",
" 0",
" 2",
" (0.0000 1.0000 0.000000) 0.0000 NaN NaN",
" (1.0000 1.0000 0.000000) 1.0000 NaN NaN",
"2",
" 2",
" 1",
" 3.000",
" -Inf Inf",
" unknown unknown",
" unknown unknown",
" 0",
" 2",
" (4.0000 0.0000 0.000000) 0.0000 NaN NaN",
" (5.0000 0.0000 0.000000) 1.0000 NaN NaN",
" 2",
" 3.000",
" -Inf Inf",
" unknown unknown",
" unknown unknown",
" 1",
" U (1 0.000000) 1 1.000000 1 1",
" 2",
" (4.0000 1.0000 0.000000) 0.0000 NaN NaN",
" (5.0000 1.0000 0.000000) 1.0000 NaN NaN",
]
)
@test strip(line_orig) == strip(line_test)
end
io = open(path)
roadway2 = read(io, Roadway)
close(io)
rm(path)
@test length(roadway.segments) == length(roadway2.segments)
for (seg1, seg2) in zip(roadway.segments, roadway2.segments)
@test seg1.id == seg2.id
@test length(seg1.lanes) == length(seg2.lanes)
for (lane1, lane2) in zip(seg1.lanes, seg2.lanes)
@test lane1.tag == lane2.tag
@test isapprox(lane1.width, lane2.width, atol=1e-3)
@test isapprox(lane1.speed_limit.lo, lane2.speed_limit.lo, atol=1e-3)
@test isapprox(lane1.speed_limit.hi, lane2.speed_limit.hi, atol=1e-3)
@test lane1.boundary_left == lane2.boundary_left
@test lane1.boundary_right == lane2.boundary_right
for (conn1, conn2) in zip(lane1.exits, lane2.exits)
@test conn1.downstream == conn2.downstream
@test conn1.mylane.i == conn2.mylane.i
@test isapprox(conn1.mylane.t, conn2.mylane.t, atol=1e-3)
@test conn1.target.tag == conn2.target.tag
@test conn1.target.ind.i == conn2.target.ind.i
@test isapprox(conn1.target.ind.t, conn2.target.ind.t, atol=1e-3)
end
for (conn1, conn2) in zip(lane1.entrances, lane2.entrances)
@test conn1.downstream == conn2.downstream
@test conn1.mylane.i == conn2.mylane.i
@test isapprox(conn1.mylane.t, conn2.mylane.t, atol=1e-3)
@test conn1.target.tag == conn2.target.tag
@test conn1.target.ind.i == conn2.target.ind.i
@test isapprox(conn1.target.ind.t, conn2.target.ind.t, atol=1e-3)
end
for (pt1, pt2) in zip(lane1.curve, lane2.curve)
@test normsquared(convert(VecE2, pt1.pos) - convert(VecE2, pt2.pos)) < 0.01
@test angledist(pt1.pos.θ, pt2.pos.θ) < 1e-5
@test isnan(pt1.s) || isapprox(pt1.s, pt2.s, atol=1e-3)
@test isnan(pt1.k) || isapprox(pt1.k, pt2.k, atol=1e-6)
@test isnan(pt1.kd) || isapprox(pt1.kd, pt2.kd, atol=1e-6)
end
end
end
end # roadway read/write tests
@testset "Lane connection" begin
lc = LaneConnection(true, CurveIndex(1,0.0), RoadIndex(CurveIndex(2,0.0), LaneTag(2,2)))
show(IOBuffer(), lc)
end
@testset "Frenet" begin
@test isapprox(AutomotiveSimulator._mod2pi2(0.0), 0.0)
@test isapprox(AutomotiveSimulator._mod2pi2(0.5), 0.5)
@test isapprox(AutomotiveSimulator._mod2pi2(2pi + 1), 1.0)
@test isapprox(AutomotiveSimulator._mod2pi2(1 - 2pi), 1.0)
roadway = get_test_roadway()
roadproj = proj(VecSE2(0.0, 0.0, 0.0), roadway)
roadind = RoadIndex(roadproj)
@test roadind.ind.i == 1
@test isapprox(roadind.ind.t, 0.0)
@test roadind.tag == LaneTag(2,1)
f = Frenet(roadind, roadway, t=0.1, ϕ=0.2)
@test f.roadind === roadind
@test isapprox(f.s, 0.0)
@test f.t == 0.1
@test f.ϕ == 0.2
f = Frenet(roadproj, roadway)
@test f.roadind === roadind
@test isapprox(f.s, 0.0)
@test f.t == 0.0
@test f.ϕ == 0.0
f = Frenet(VecSE2(0.0, 0.0, 0.0), roadway)
@test f.roadind === roadind
@test isapprox(f.s, 0.0)
@test f.t == 0.0
@test f.ϕ == 0.0
@test posg(f, roadway) == VecSE2(0.0, 0.0, 0.0)
lane = roadway[LaneTag(1,1)]
f = Frenet(lane, 1.0, 0.0, 0.0)
@test f.roadind.tag == lane.tag
@test isapprox(f.s, 1.0)
@test f.t == 0.0
@test f.ϕ == 0.0
end
@testset "straight roadway" begin
curve = gen_straight_curve(VecE2(25.0, -10.0), VecE2(25.0, 10.0), 2)
@inferred gen_straight_curve(VecE2(25.0, -10.0), VecE2(25.0, 10.0), 2)
@test length(curve) == 2
@test curve[1].pos.x == 25.0
roadway = gen_straight_roadway(1, 1000.0)
@test length(roadway.segments) == 1
seg = roadway[1]
@test length(seg.lanes) == 1
lane = seg.lanes[1]
@test isapprox(lane.width, DEFAULT_LANE_WIDTH)
@test lane.curve[1] == CurvePt(VecSE2(0.0,0.0,0.0), 0.0)
@test lane.curve[2] == CurvePt(VecSE2(1000.0,0.0,0.0), 1000.0)
roadway = gen_straight_roadway(3, 500.0, lane_width=1.0)
@test length(roadway.segments) == 1
seg = roadway[1]
@test length(seg.lanes) == 3
lane = seg.lanes[1]
@test isapprox(lane.width, 1.0)
@test lane.curve[1] == CurvePt(VecSE2(0.0,0.0,0.0), 0.0)
@test lane.curve[2] == CurvePt(VecSE2(500.0,0.0,0.0), 500.0)
lane = seg.lanes[2]
@test isapprox(lane.width, 1.0)
@test lane.curve[1] == CurvePt(VecSE2(0.0,1.0,0.0), 0.0)
@test lane.curve[2] == CurvePt(VecSE2(500.0,1.0,0.0), 500.0)
lane = seg.lanes[3]
@test isapprox(lane.width, 1.0)
@test lane.curve[1] == CurvePt(VecSE2(0.0,2.0,0.0), 0.0)
@test lane.curve[2] == CurvePt(VecSE2(500.0,2.0,0.0), 500.0)
origin = VecSE2(1.0,2.0,deg2rad(90))
roadway = gen_straight_roadway(1, 100.0, lane_width=1.0, origin=origin)
@test length(roadway.segments) == 1
lane = roadway[1].lanes[1]
@test lane.curve[1].pos == origin
@test isapprox(lane.curve[2].pos.x, 1.0, atol=1e-6)
@test isapprox(lane.curve[2].pos.y, 102.0, atol=1e-6)
@test isapprox(lane.curve[2].pos.θ, deg2rad(90), atol=1e-6)
roadway = gen_straight_roadway(2, 100.0, lane_widths=[1.0, 2.0])
@test length(roadway.segments) == 1
@test isapprox(roadway[1].lanes[1].curve[1].pos.y, 0.0, atol=1e-6)
@test isapprox(roadway[1].lanes[2].curve[1].pos.y, 0.5 + 1.0, atol=1e-6)
end
@testset "bezier curve" begin
# see intersection tutorial for visualization
roadway = Roadway()
# Define coordinates of the entry and exit points to the intersection
r = 5.0 # turn radius
A = VecSE2(0.0,DEFAULT_LANE_WIDTH,-π)
B = VecSE2(0.0,0.0,0.0)
C = VecSE2(r,-r,-π/2)
D = VecSE2(r+DEFAULT_LANE_WIDTH,-r,π/2)
E = VecSE2(2r+DEFAULT_LANE_WIDTH,0,0)
F = VecSE2(2r+DEFAULT_LANE_WIDTH,DEFAULT_LANE_WIDTH,-π)
# helper function
function append_to_curve!(target::Curve, newstuff::Curve)
s_end = target[end].s
for c in newstuff
push!(target, CurvePt(c.pos, c.s+s_end, c.k, c.kd))
end
return target
end
# Append right turn coming from the left
curve = gen_straight_curve(convert(VecE2, B+VecE2(-100,0)), convert(VecE2, B), 2)
append_to_curve!(curve, gen_bezier_curve(B, C, 0.6r, 0.6r, 51)[2:end])
@test length(curve) == 52
append_to_curve!(curve, gen_straight_curve(convert(VecE2, C), convert(VecE2, C+VecE2(0,-50.0)), 2))
@test length(curve) == 54
lane = Lane(LaneTag(length(roadway.segments)+1,1), curve)
push!(roadway.segments, RoadSegment(lane.tag.segment, [lane]))
end
@testset "stadium roadway" begin
roadway = gen_stadium_roadway(1, length=100.0, width=10.0,
radius=25.0, ncurvepts_per_turn=2)
@test length(roadway.segments) == 6
seg = roadway[1]
@test length(seg.lanes) == 1
lane = seg.lanes[1]
@test lane.curve[1] == CurvePt(VecSE2(100.0,0.0,0.0), 0.0)
@test lane.curve[2] == CurvePt(VecSE2(125.0,25.0,π/2), 25*π/2)
@test roadway[LaneTag(2,1)].curve[1] == CurvePt(VecSE2(125.0,35.0,π/2), 0.0)
roadway = gen_stadium_roadway(4)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 2976 | @testset "Scene" begin
@testset begin
scene = Scene([1,2,3])
@test length(scene) == 3
@test capacity(scene) == 3
for i in 1 : 3
@test scene[i] == i
end
scene = Scene([1,2,3], capacity=5)
@test length(scene) == 3
@test capacity(scene) == 5
for i in 1 : 3
@test scene[i] == i
end
@test_throws ErrorException Scene([1,2,3], capacity=2)
scene = Scene(Int)
@test length(scene) == 0
@test capacity(scene) > 0
@test lastindex(scene) == scene.n
scene = Scene(Int, 2)
@test length(scene) == 0
@test capacity(scene) == 2
scene[1] = 999
scene[2] = 888
@test scene[1] == 999
@test scene[2] == 888
@test length(scene) == 0 # NOTE: length does not change
@test capacity(scene) == 2
empty!(scene)
@test length(scene) == 0
@test capacity(scene) == 2
push!(scene, 999)
push!(scene, 888)
@test length(scene) == 2
@test capacity(scene) == 2
@test_throws BoundsError push!(scene, 777)
scene = Scene([999,888])
deleteat!(scene, 1)
@test length(scene) == 1
@test capacity(scene) == 2
@test scene[1] == 888
deleteat!(scene, 1)
@test length(scene) == 0
@test capacity(scene) == 2
scene = Scene([1,2,3])
scene2 = copy(scene)
for i in 1 : 3
@test scene[i] == scene2[i]
end
scene[1] = 999
@test scene2[1] == 1
end
@testset begin
scene = EntityScene(Int, Float64, String)
scene = EntityScene(Int, Float64, String, 10)
@test eltype(scene) == Entity{Int,Float64,String}
@test capacity(scene) == 10
scene = Scene([Entity(1,1,"A"),Entity(2,2,"B"),Entity(3,3,"C")])
@test in("A", scene)
@test in("B", scene)
@test in("C", scene)
@test !in("D", scene)
@test findfirst("A", scene) == 1
@test findfirst("B", scene) == 2
@test findfirst("C", scene) == 3
@test findfirst("D", scene) == nothing
@test id2index(scene, "A") == 1
@test id2index(scene, "B") == 2
@test id2index(scene, "C") == 3
@test_throws BoundsError id2index(scene, "D")
scene = Scene([Entity(1,1,"A"),Entity(2,2,"B"),Entity(3,3,"C")])
@test get_by_id(scene, "A") == scene[1]
@test get_by_id(scene, "B") == scene[2]
@test get_by_id(scene, "C") == scene[3]
delete!(scene, Entity(2,2,"B"))
@test scene[1] == Entity(1,1,"A")
@test scene[2] == Entity(3,3,"C")
@test length(scene) == 2
delete!(scene, "A")
@test scene[1] == Entity(3,3,"C")
@test length(scene) == 1
scene = Scene([Entity(1,1,1),Entity(2,2,2)], capacity=3)
@test get_first_available_id(scene) == 3
end
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3180 | struct NoCallback end
struct NoActionCallback end
AutomotiveSimulator.run_callback(callback::NoActionCallback, scenes::Vector{Scene{E}}, roadway::R, models::Dict{I,M}, tick::Int) where {E,R,I,M<:DriverModel} = false
struct WithActionCallback end
AutomotiveSimulator.run_callback(callback::WithActionCallback, scenes::Vector{Scene{E}}, actions::Union{Nothing, Vector{Scene{A}}}, roadway::R, models::Dict{I,M}, tick::Int) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel} = false
@testset "simulation" begin
roadway = gen_straight_roadway(1, 500.0)
models = Dict{Int, DriverModel}()
models[1] = IntelligentDriverModel(k_spd = 1.0, v_des = 10.0)
models[2] = IntelligentDriverModel(k_spd = 1.0, v_des = 5.0)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 5.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 70.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
scene = Scene([veh1, veh2])
n_steps = 40
dt = 0.1
@inferred simulate(scene, roadway, models, n_steps, dt)
reset_hidden_states!(models)
# initializing vehicles too close
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 10.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 5.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
scene = Scene([veh1, veh2])
scenes = @inferred simulate(scene, roadway, models, n_steps, dt, callbacks=(CollisionCallback(),))
@test length(scenes) < 10
open("test.txt", "w+") do io
write(io, scenes)
end
@test_throws ErrorException open("test.txt", "r") do io
read(io, Vector{EntityScene{VehicleState, VehicleDef,Symbol}})
end
open("test.txt", "r") do io
read(io, Vector{EntityScene{VehicleState, VehicleDef,String}})
end
r = open("test.txt", "r") do io
read(io, typeof(scenes))
end
@test length(r) == length(scenes)
for (i, s) in enumerate(r)
for (j, veh) in enumerate(r[i])
@test posg(veh) ≈ posg(scenes[i][j])
end
end
# make sure warnings, errors and deprecations in run_callback work as expected
@test_nowarn simulate(scene, roadway, models, 10, .1, callbacks=(WithActionCallback(),))
# collision right from start
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 0.0), roadway, 10.)
veh1 = Entity(veh_state, VehicleDef(), 1)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 1.0), roadway, 5.)
veh2 = Entity(veh_state, VehicleDef(), 2)
scene = Scene([veh1, veh2])
scenes = @inferred simulate(scene, roadway, models, n_steps, dt, callbacks=(CollisionCallback(),))
@test length(scenes) == 1
end
@testset "trajdata simulation" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
veh_state = VehicleState(Frenet(roadway[LaneTag(1,1)], 6.0), roadway, 10.)
ego = Entity(veh_state, VehicleDef(), 2)
model = ProportionalSpeedTracker()
scenes = simulate_from_history(model, roadway, trajdata, ego.id, 0.1)
@test findfirst(ego.id, scenes[end]) != nothing
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 4418 | function get_test_trajdata(roadway::Roadway)
scene1 = Scene([
Entity(VehicleState(VecSE2(0.0,0.0,0.0), roadway, 10.0), VehicleDef(), 1),
Entity(VehicleState(VecSE2(3.0,0.0,0.0), roadway, 20.0), VehicleDef(), 2)
]
)
scene2 = Scene([
Entity(VehicleState(VecSE2(1.0,0.0,0.0), roadway, 10.0), VehicleDef(), 1),
Entity(VehicleState(VecSE2(5.0,0.0,0.0), roadway, 20.0), VehicleDef(), 2)
]
)
trajdata = [scene1, scene2]
return trajdata
end
@testset "VehicleState" begin
s = VehicleState(VecSE2(0.0,0.0,0.0), Frenet(NULL_ROADINDEX, 0.0, 0.0, 0.0), 10.0)
@test isapprox(velf(s).s, 10.0)
@test isapprox(velf(s).t, 0.0)
show(IOBuffer(), s.posF)
show(IOBuffer(), s)
s = VehicleState(VecSE2(0.0,0.0,0.0), Frenet(NULL_ROADINDEX, 0.0, 0.0, 0.1), 10.0)
@test isapprox(velf(s).s, 10.0*cos(0.1))
@test isapprox(velf(s).t, 10.0*sin(0.1))
@test isapprox(velg(s).x, 10.0)
@test isapprox(velg(s).y, 0.0)
@test isapprox(vel(s), 10.0)
vehdef = VehicleDef(AgentClass.CAR, 5.0, 3.0)
veh = Entity(s, vehdef, 1)
@test isapprox(get_footpoint(veh), VecSE2(0.0,0.0,0.0))
show(IOBuffer(), vehdef)
show(IOBuffer(), veh)
ri = RoadIndex(CurveIndex(1,0.1), LaneTag(1,2))
@test isapprox(Frenet(ri, 0.0, 0.0, 0.1), Frenet(ri, 0.0, 0.0, 0.1))
@test VehicleState(VecSE2(0.1,0.2,0.3), 1.0) == VehicleState(VecSE2(0.1,0.2,0.3), NULL_FRENET, 1.0)
@test get_front(veh).x == vehdef.length/2
@test get_rear(veh).x == -vehdef.length/2
roadway = gen_straight_roadway(3, 100.0)
veh = VehicleState(VecSE2(0.0, 0.0, 0.0), roadway, 0.0)
veh = Entity(veh, VehicleDef(), 1)
@test get_lane(roadway, veh).tag == LaneTag(1,1)
@test get_lane(roadway, veh).tag == get_lane(roadway, veh.state).tag
veh = VehicleState(VecSE2(0.0, 3.0, 0.0), roadway, 0.0)
@test get_lane(roadway, veh).tag == LaneTag(1,2)
veh = VehicleState(VecSE2(0.0, 6.0, 0.0), roadway, 0.0)
@test get_lane(roadway, veh).tag == LaneTag(1,3)
end
@testset "scene" begin
roadway = get_test_roadway()
trajdata = get_test_trajdata(roadway)
s1 = VehicleState(VecSE2(0.0, 0.0, 0.0), roadway, 0.0)
s2 = VehicleState(VecSE2(5.0, 0.0, 0.0), roadway, 0.0)
s3 = lerp(s1, s2, 0.5, roadway)
@test s3.posG.x == 2.5
@test s3.posF.s == 2.5
vehstate = VehicleState(VecSE2(0.0, 0.0, 0.0), roadway, 0.0)
vehstate1 = VehicleState(VecSE2(0.0, 0.0, 0.0), roadway[LaneTag(1,1)], roadway, 0.0)
@test vehstate1 == vehstate
veh = Entity(vehstate, VehicleDef(), 1)
scene1 = Scene([veh])
scene2 = Scene([veh])
@test first(scene1.entities) == first(scene2.entities)
@test scene1.n == scene2.n
io = IOBuffer()
show(io, scene1)
close(io)
veh2 = Entity(vehstate, BicycleModel(VehicleDef()), 1)
veh3 = convert(Entity{VehicleState, VehicleDef, Int64}, veh2)
@test veh3 == veh
scene = Scene([veh, veh2, veh3])
io = IOBuffer()
show(io, scene)
close(io)
scene = Scene(typeof(veh))
copyto!(scene, trajdata[1])
@test length(scene) == 2
for (i,veh) in enumerate(scene)
@test scene[i].state == trajdata[1][i].state
@test scene[i].def == trajdata[1][i].def
end
scene2 = Scene(deepcopy(scene.entities), 2)
@test length(scene2) == 2
for (i,veh) in enumerate(scene2)
@test scene2[i].state == trajdata[1][i].state
@test scene2[i].def == trajdata[1][i].def
end
@test get_by_id(scene, 1) == scene[1]
empty!(scene2)
@test length(scene2) == 0
copyto!(scene2, scene)
@test length(scene2) == 2
for (i,veh) in enumerate(scene2)
@test scene2[i].state == trajdata[1][i].state
@test scene2[i].def == trajdata[1][i].def
end
delete!(scene2, scene2[1])
@test length(scene2) == 1
@test scene2[1].state == trajdata[1][2].state
@test scene2[1].def == trajdata[1][2].def
scene2[1] = deepcopy(scene[1])
@test scene2[1].state == trajdata[1][1].state
@test scene2[1].def == trajdata[1][1].def
@test findfirst(1, scene) == 1
@test findfirst(2, scene) == 2
@test get_first_available_id(scene) == 3
@test in(1, scene)
@test in(2, scene)
@test !in(3, scene)
veh = scene[2]
@test veh.state == trajdata[1][2].state
@test veh.def == trajdata[1][2].def
push!(scene, trajdata[1][1].state)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 5378 | let
@test degrees_to_deg_min_sec(30.0) == (30,0,0)
lla = LatLonAlt(deg2rad(deg_min_sec_to_degrees(73, 0, 0)),
deg2rad(deg_min_sec_to_degrees(45, 0, 0)),
0.0)
utm = convert(UTM, lla, INTERNATIONAL)
# @printf("%3d %1d %2.3f %3d %1d %2.3f → ", degrees_to_deg_min_sec(rad2deg(lla.lat))..., degrees_to_deg_min_sec(rad2deg(lla.lon))...)
# @printf("%2d %7.2f %6.2f\n", utm.zone, utm.n, utm.e)
lla = LatLonAlt(deg2rad(deg_min_sec_to_degrees( 30, 0, 0)),
deg2rad(deg_min_sec_to_degrees(102, 0, 0)),
0.0)
utm = convert(UTM, lla, INTERNATIONAL)
# @printf("%3d %1d %2.3f %3d %1d %2.3f → ", degrees_to_deg_min_sec(rad2deg(lla.lat))..., degrees_to_deg_min_sec(rad2deg(lla.lon))...)
# @printf("%2d %7.2f %6.2f\n", utm.zone, utm.n, utm.e)
utm = UTM(210577.93, 3322824.35, 0.0, 48)
lla_target = LatLonAlt(deg2rad(deg_min_sec_to_degrees(30, 0, 6.489)),
deg2rad(deg_min_sec_to_degrees(101, 59, 59.805)), # E
0.0)
lla = convert(LatLonAlt, utm, INTERNATIONAL)
# @printf("%3d %1d %2.3f %3d %1d %2.3f ← ", degrees_to_deg_min_sec(rad2deg(lla.lat))..., degrees_to_deg_min_sec(rad2deg(lla.lon))...)
# @printf("%2d %7.2f %6.2f\n", utm.zone, utm.n, utm.e)
# @printf("%3d %1d %2.3f %3d %1d %2.3f (should be this)\n", degrees_to_deg_min_sec(rad2deg(lla_target.lat))..., degrees_to_deg_min_sec(rad2deg(lla_target.lon))...)
@test isapprox(lla.lat, lla_target.lat, atol=1e-8)
@test isapprox(lla.lon, lla_target.lon, atol=1e-8)
utm = UTM(789411.59, 3322824.08, 0.0, 47)
lla_target = LatLonAlt(deg2rad(deg_min_sec_to_degrees(30, 0, 6.489)),
deg2rad(deg_min_sec_to_degrees(101, 59, 59.805)), # E
0.0)
lla = convert(LatLonAlt, utm, INTERNATIONAL)
# @printf("%3d %1d %2.3f %3d %1d %2.3f ← ", degrees_to_deg_min_sec(rad2deg(lla.lat))..., degrees_to_deg_min_sec(rad2deg(lla.lon))...)
# @printf("%2d %7.2f %6.2f\n", utm.zone, utm.n, utm.e)
# @printf("%3d %1d %2.3f %3d %1d %2.3f (should be this)\n", degrees_to_deg_min_sec(rad2deg(lla_target.lat))..., degrees_to_deg_min_sec(rad2deg(lla_target.lon))...)
@test isapprox(lla.lat, lla_target.lat, atol=1e-8)
@test isapprox(lla.lon, lla_target.lon, atol=1e-8)
utm = UTM(200000.00, 1000000.00, 0.0, 31)
lla_target = LatLonAlt(deg2rad(deg_min_sec_to_degrees(9, 2, 10.706)),
deg2rad(deg_min_sec_to_degrees(0, 16, 17.099)), # E
0.0)
lla = convert(LatLonAlt, utm, INTERNATIONAL)
# @printf("%3d %1d %2.3f %3d %1d %2.3f ← ", degrees_to_deg_min_sec(rad2deg(lla.lat))..., degrees_to_deg_min_sec(rad2deg(lla.lon))...)
# @printf("%2d %7.2f %6.2f\n", utm.zone, utm.n, utm.e)
# @printf("%3d %1d %2.3f %3d %1d %2.3f (should be this)\n", degrees_to_deg_min_sec(rad2deg(lla_target.lat))..., degrees_to_deg_min_sec(rad2deg(lla_target.lon))...)
@test isapprox(lla.lat, lla_target.lat, atol=1e-8)
@test isapprox(lla.lon, lla_target.lon, atol=1e-8)
buf = IOBuffer()
print(buf, lla)
close(buf)
# should NOT create a warning
check_is_in_radians(LatLonAlt(0.1,0.1,0.1))
lla = LatLonAlt(0.1,0.2-2π,0.3)
@test isapprox(ensure_lon_between_pies(lla).lon, 0.2, atol=1e-10)
lla = LatLonAlt(0.1,0.2+2π,0.3)
@test isapprox(ensure_lon_between_pies(lla).lon, 0.2, atol=1e-10)
@test isapprox(get_earth_radius(0.0), 6378137.0, atol=0.1)
@test isapprox(get_earth_radius(π/2), 6356752.3, atol=0.1)
v3 = convert(VecE3, ECEF(0.1,0.2,0.3))
@test v3.x == 0.1
@test v3.y == 0.2
@test v3.z == 0.3
ecef = convert(ECEF, VecE3(0.1,0.2,0.3))
@test ecef.x == 0.1
@test ecef.y == 0.2
@test ecef.z == 0.3
v3 = convert(VecE3, UTM(0.1,0.2,0.3,1))
@test v3.x == 0.1
@test v3.y == 0.2
@test v3.z == 0.3
utm = UTM(0.1,0.2,0.3,1) + UTM(0.2,0.3,0.4,1)
@test utm.e ≈ 0.3
@test utm.n ≈ 0.5
@test utm.u ≈ 0.7
@test utm.zone == 1
utm = UTM(0.1,0.2,0.3,1) - UTM(0.2,0.3,0.4,1)
@test utm.e ≈ -0.1
@test utm.n ≈ -0.1
@test utm.u ≈ -0.1
@test utm.zone == 1
v3 = convert(VecE3, ENU(0.1,0.2,0.3))
@test v3.x == 0.1
@test v3.y == 0.2
@test v3.z == 0.3
enu = convert(ENU, VecE3(0.1,0.2,0.3))
@test enu.e == 0.1
@test enu.n == 0.2
@test enu.u == 0.3
enu = ENU(0.1,0.2,0.3) + ENU(0.2,0.3,0.4)
@test enu.e ≈ 0.3
@test enu.n ≈ 0.5
@test enu.u ≈ 0.7
enu = ENU(0.1,0.2,0.3) - ENU(0.2,0.3,0.4)
@test enu.e ≈ -0.1
@test enu.n ≈ -0.1
@test enu.u ≈ -0.1
for (lla, ecef) in [(LatLonAlt(deg2rad( 0),deg2rad( 0), 0.0), ECEF(6378137.0,0.0,0.0)),
(LatLonAlt(deg2rad(90),deg2rad( 0), 0.0), ECEF(0.0,0.0,6356752.31)),
(LatLonAlt(deg2rad(20),deg2rad(40),110.0), ECEF(4593156.33, 3854115.78, 2167734.41))]
lla2 = convert(LatLonAlt, ecef)
@test isapprox(lla2.lat, lla.lat, atol=1e-2)
@test isapprox(lla2.lon, lla.lon, atol=1e-2)
@test isapprox(lla2.alt, lla.alt, atol=1e-2)
ecef2 = convert(ECEF, lla)
@test isapprox(ecef2.x, ecef.x, atol=1.0)
@test isapprox(ecef2.y, ecef.y, atol=1.0)
@test isapprox(ecef2.z, ecef.z, atol=1.0)
end
end | AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 1207 | using ForwardDiff
using LinearAlgebra
let
f(x) = x+x
g(x) = 5*x
h(x) = dot(x, x)
# Once we get ForwardDiff working, this should work
# h(x::VecE) = dot(x, x)
@test ForwardDiff.jacobian(f, VecE2(1.0, 2.0)) == [2.0 0.0; 0.0 2.0]
@test ForwardDiff.jacobian(g, VecE2(1.0, 2.0)) == [5.0 0.0; 0.0 5.0]
@test ForwardDiff.gradient(h, VecE2(1.0, 2.0)) == [2.0, 4.0]
@test ForwardDiff.hessian(h, VecE2(1.0, 2.0)) == [2.0 0.0; 0.0 2.0]
@test ForwardDiff.jacobian(f, VecE3(1.0, 2.0, 3.0)) == 2.0*Matrix{Float64}(I, 3, 3)
@test ForwardDiff.jacobian(g, VecE3(1.0, 2.0, 3.0)) == 5.0*Matrix{Float64}(I, 3, 3)
@test ForwardDiff.gradient(h, VecE3(1.0, 2.0, 3.0)) == [2.0, 4.0, 6.0]
@test ForwardDiff.hessian(h, VecE3(1.0, 2.0, 3.0)) == 2.0*Matrix{Float64}(I, 3, 3)
@test ForwardDiff.jacobian(f, VecSE2(1.0, 2.0, 3.0)) == 2.0*Matrix{Float64}(I, 3, 3)
# Once we get ForwardDiff working, this should work...
# h(x::VecSE2) = normsquared(VecE2(x))
# @test ForwardDiff.jacobian(g, VecSE2(1.0, 2.0, 3.0)) == diagm([5.0, 5.0, 1.0])
# @test ForwardDiff.gradient(h, VecSE2(1.0, 2.0, 3.0)) == [2.0, 4.0, 0.0]
# @test ForwardDiff.hessian(h, VecSE2(1.0, 2.0, 3.0)) == [2.0 0.0 0.0; 0.0 2.0 0.0; 0.0 0.0 0.0]
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 11347 | let
@test isapprox(deltaangle(0.0, 0.0), 0.0)
@test isapprox(deltaangle(0.0, 1.0), 1.0)
@test isapprox(deltaangle(0.0, 2π), 0.0, atol=1e-10)
@test isapprox(deltaangle(0.0, π + 1.0), -(π- 1.0))
@test isapprox(angledist(0.0, 0.0), 0.0)
@test isapprox(angledist(0.0, 1.0), 1.0)
@test isapprox(angledist(0.0, 2π), 0.0, atol=1e-10)
@test isapprox(angledist(0.0, π + 1.0), π- 1.0)
@test isapprox(lerp_angle(0.0, 0.0, 1.0), 0.0)
@test isapprox(lerp_angle(0.0, 2π, 0.5), 0.0, atol=1e-10)
@test isapprox(lerp_angle(0.0, 2.0, 0.75), 1.5)
@test isapprox(lerp_angle(0.0, 2π-2, 0.75), -1.5)
@test are_collinear(VecE2(0.0,0.0), VecE2(1.0,1.0), VecE2(2.0,2.0))
@test are_collinear(VecE2(0.0,0.0), VecE2(1.0,1.0), VecE2(-2.0,-2.0))
@test are_collinear(VecE2(0.0,0.0), VecE2(0.5,1.0), VecE2(1.0,2.0))
@test are_collinear(VecE2(1.0,2.0), VecE2(0.0,0.0), VecE2(0.5,1.0))
@test !are_collinear(VecE2(0.0,0.0), VecE2(1.0,0.0), VecE2(0.0,1.0))
end
let
seg = LineSegment1D(0,1)
seg2 = seg + 0.5
@test isapprox(seg2.a, 0.5)
@test isapprox(seg2.b, 1.5)
seg2 = seg - 0.3
@test isapprox(seg2.a, -0.3)
@test isapprox(seg2.b, 0.7)
seg = LineSegment1D(2,5)
@test isapprox(get_distance(seg, 1.5), 0.5)
@test isapprox(get_distance(seg, -1.5), 3.5)
@test isapprox(get_distance(seg, 2.5), 0.0)
@test isapprox(get_distance(seg, 2.0), 0.0)
@test isapprox(get_distance(seg, 5.0), 0.0)
@test isapprox(get_distance(seg, 5.5), 0.5)
@test isapprox(get_distance(seg, 15.5), 10.5)
@test !in(-1.0, seg)
@test !in(1.0, seg)
@test in(2.0, seg)
@test in(3.0, seg)
@test in(5.0, seg)
@test !in(5.5, seg)
@test in(LineSegment1D(3.0, 3.5), seg)
@test in(LineSegment1D(3.0, 3.0), seg)
@test !in(LineSegment1D(3.0, 13.0), seg)
@test !in(LineSegment1D(-3.0, 3.0), seg)
@test !in(LineSegment1D(-3.0, -2.0), seg)
@test !in(LineSegment1D(13.0, 15.0), seg)
@test intersects(seg, LineSegment1D(3.0, 3.5))
@test intersects(seg, LineSegment1D(3.0, 3.0))
@test intersects(seg, LineSegment1D(3.0, 13.0))
@test intersects(seg, LineSegment1D(-3.0, 3.0))
@test !intersects(seg, LineSegment1D(-3.0, -2.0))
@test !intersects(seg, LineSegment1D(13.0, 15.0))
end
let
L = Line(VecE2(0,0), π/4)
L2 = L + VecE2(-1,1)
@test isapprox(L2.C, VecE2(-1,1))
@test isapprox(L2.θ, π/4)
L2 = L - VecE2(-1,1)
@test isapprox(L2.C, VecE2(1,-1))
@test isapprox(L2.θ, π/4)
L2 = rot180(L)
@test isapprox(L2.θ, π/4 + π)
@test isapprox(get_polar_angle(L), atan(1,1))
@test isapprox(get_distance(L, VecE2(0,0)), 0)
@test isapprox(get_distance(L, VecE2(1,1)), 0, atol=1e-10)
@test isapprox(get_distance(L, VecE2(1,0)), √2/2)
@test isapprox(get_distance(L, VecE2(0,1)), √2/2)
@test get_side(L, VecE2(0,0)) == 0
@test get_side(L, VecE2(1,1)) == 0
@test get_side(L, VecE2(0,1)) == 1
@test get_side(L, VecE2(1,0)) == -1
end
let
L = LineSegment(VecE2(0,0), VecE2(1,1))
L2 = L + VecE2(-1,1)
@test isapprox(L2.A, VecE2(-1,1))
@test isapprox(L2.B, VecE2( 0,2))
L2 = L - VecE2(-1,1)
@test isapprox(L2.A, VecE2(1,-1))
@test isapprox(L2.B, VecE2(2, 0))
@test isapprox(get_polar_angle(L), atan(1,1))
@test isapprox(get_distance(L, VecE2(0,0)), 0)
@test isapprox(get_distance(L, VecE2(1,1)), 0)
@test isapprox(get_distance(L, VecE2(1,0)), √2/2)
@test isapprox(get_distance(L, VecE2(0,1)), √2/2)
@test get_side(L, VecE2(1,1)) == 0
@test get_side(L, VecE2(0,1)) == 1
@test get_side(L, VecE2(1,0)) == -1
@test angledist(L, L2) ≈ 0.0
@test parallel(L, L2)
L2 = LineSegment(VecE2(0,0), VecE2(-1,1))
@test angledist(L, L2) ≈ π/2
@test !parallel(L, L2)
@test intersects(L, L2)
L2 = LineSegment(VecE2(0,0), VecE2(1,-1))
@test angledist(L, L2) ≈ π/2
@test !parallel(L, L2)
@test intersects(L, L2)
L2 = LineSegment(VecE2(0,0), VecE2(1,-1)) + VecE2(5,-7)
@test angledist(L, L2) ≈ π/2
@test !parallel(L, L2)
@test !intersects(L, L2)
@test intersects(L, LineSegment(VecE2(1,1), VecE2(2,-1)))
@test !intersects(L, LineSegment(VecE2(2,2), VecE2(5,6)))
@test !intersects(L, LineSegment(VecE2(-5,-5), VecE2(5,-5)))
end
let
@test isapprox(intersect(Ray(-1,0,0), Ray(0,-1,π/2)), VecE2(0.0,0.0))
@test intersects(Ray(0,0,0), Ray(1,-1,π/2))
@test !intersects(Ray(0,0,0), Ray(1,-1,-π/2))
# @test intersects(Ray(0,0,0), Ray(1,0,0)) # TODO: get this to work
@test intersects(Ray(0,0,0), Line(VecE2(0,0), VecE2(1,1)))
@test !intersects(Ray(0,0,0), Line(VecE2(0,1), VecE2(1,1)))
@test intersects(Ray(0,0,0), Line(VecE2(1,0), VecE2(2,0)))
@test intersects(Ray(0,0,0), Line(VecE2(1,-1), VecE2(1,1)))
@test intersects(Ray(0,0,π/2), Line(VecE2(-1,1), VecE2(1,1)))
@test !intersects(Ray(0,0,π/2), Line(VecE2(-1,1), VecE2(-1,2)))
@test intersects(Ray(0,0,π/2), Line(VecE2(-1,1), VecE2(-1.5,1.5)))
@test intersects(Ray(0,0,0), LineSegment(VecE2(0,0), VecE2(1,1)))
@test !intersects(Ray(0,0,0), LineSegment(VecE2(0,1), VecE2(1,1)))
@test intersects(Ray(0,0,0), LineSegment(VecE2(1,0), VecE2(2,0)))
@test !intersects(Ray(0,0,0), LineSegment(VecE2(-1,0), VecE2(-2,0)))
@test isapprox(intersect(VecSE2(4,0,3pi/4), LineSegment(VecE2(5.6,0), VecE2(0,3.6))),
VecE2(1.12, 2.88), atol=1e-3)
end
let
proj1 = Projectile(VecSE2(0.0,0.0,0.0), 1.0)
proj2 = Projectile(VecSE2(1.0,1.0,1.0), 1.0)
@test isapprox(VecE2(Vec.propagate(proj1, 2.0).pos), VecE2(2.0,0.0))
@test isapprox(VecE2(Vec.propagate(proj2, 0.0).pos), VecE2(1.0,1.0))
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, Projectile(VecSE2(0.0,1.0,0.0), 1.0))
@test isapprox(t_PCA, 0.0)
@test isapprox(d_PCA, 1.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, Projectile(VecSE2(0.0,2.0,0.0), 1.0))
@test isapprox(t_PCA, 0.0)
@test isapprox(d_PCA, 2.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, Projectile(VecSE2(0.0,1.0,0.0), 2.0))
@test isapprox(t_PCA, 0.0)
@test isapprox(d_PCA, 1.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(Projectile(VecSE2(0.0,-0.0,0.2), 1.0), Projectile(VecSE2(0.0,1.0,-0.2), 1.0))
@test t_PCA > 0.0
@test isapprox(d_PCA, 0.0)
@test isapprox(get_intersection_time(proj1, LineSegment(VecE2(0, 0), VecE2(0,1))), 0.0)
@test isapprox(get_intersection_time(proj1, LineSegment(VecE2(1,-1), VecE2(1,1))), 1.0)
@test isinf(get_intersection_time(proj1, LineSegment(VecE2(-1,0), VecE2(-1,1))))
@test isapprox(get_intersection_time(proj1, LineSegment(VecE2(3,0), VecE2(2,0))), 2.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(0, 0), VecE2(0,1)))
@test isapprox(t_PCA, 0.0)
@test isapprox(d_PCA, 0.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(1,-1), VecE2(1,1)))
@test isapprox(t_PCA, 1.0)
@test isapprox(d_PCA, 0.0)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(1,0.5), VecE2(1,1)))
@test isapprox(t_PCA, 1.0)
@test isapprox(d_PCA, 0.5)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(1,-0.5), VecE2(1,-1)))
@test isapprox(t_PCA, 1.0)
@test isapprox(d_PCA, 0.5)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(1,-0.5), VecE2(2,-1)))
@test isapprox(t_PCA, 1.0)
@test isapprox(d_PCA, 0.5)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(2,-1), VecE2(1,-0.5)))
@test isapprox(t_PCA, 1.0)
@test isapprox(d_PCA, 0.5)
t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(2,-1), VecE2(1,-0.5)), true)
@test isinf(t_PCA)
@test isinf(d_PCA)
# t_PCA, d_PCA = closest_time_of_approach_and_distance(proj1, LineSegment(VecE2(-1,1), VecE2(1,1)))
# println((t_PCA, d_PCA ))
# @test isapprox(t_PCA, 0.0)
# @test isapprox(d_PCA, 1.0)
end
let
@test in(VecE2(0,0), Circ(0,0,1.0))
@test !in(VecE2(0,0), Circ(2,0,1.0))
@test in(VecE2(1.5, 0), Circ(2,0,1.0))
@test in(VecE3(1.5,0,3), Circ(2,0,3,1.0))
box = AABB(VecE2(0.0, 0.5), 2.0, 5.0)
@test in(VecE2( 0.0,0.0), box)
@test in(VecE2(-1.0,0.0), box)
@test !in(VecE2(-2.0,0.0), box)
@test !in(VecE2( 1.0,3.1), box)
box = AABB(VecE2(-1.0, -2.0), VecE2(1.0, 3.0))
@test in(VecE2( 0.0,0.0), box)
@test in(VecE2(-1.0,0.0), box)
@test !in(VecE2(-2.0,0.0), box)
@test !in(VecE2( 1.0,3.1), box)
end
let
box = OBB(VecSE2(0.0, 0.5, 0.0), 2.0, 5.0)
@test in(VecE2( 0.0,0.0), box)
@test in(VecE2(-1.0,0.0), box)
@test !in(VecE2(-2.0,0.0), box)
@test !in(VecE2( 1.0,3.1), box)
box = OBB(VecSE2(0.0, 0.0, π/4), 2.0, 2.0)
@test in(VecE2( 0.0,0.0), box)
@test in(VecE2( 1.0,0.0), box)
@test in(VecE2( √2/2-0.1,√2/2-0.1), box)
@test !in(VecE2( 1.0,1.0), box)
@test !in(VecE2( √2/2+0.1,√2/2+0.1), box)
box = OBB(VecSE2(0.0, 0.0, 0.0), 1.0, 1.0)
box2 = inertial2body(box, VecSE2(1.0,0.0,0.0))
@test isapprox(box2.aabb.center.x, -1.0)
@test isapprox(box2.aabb.center.y, 0.0)
@test isapprox(box2.θ, 0.0)
box2 = inertial2body(box, VecSE2(1.0,0.0,π))
@test isapprox(box2.aabb.center.x, 1.0)
@test isapprox(box2.aabb.center.y, 0.0, atol=1e-10)
@test isapprox(angledist(box2.θ, π), 0.0, atol=1e-10)
end
let
plane = Plane3()
@test plane.normal == VecE3(1.0,0.0,0.0)
@test plane.offset == 0.0
plane = Plane3(VecE3(2.0,0.0,0.0), 0.5)
@test plane.normal == VecE3(1.0,0.0,0.0)
@test plane.offset == 0.5
plane = Plane3(VecE3(2.0,0.0,0.0), VecE3(0.0,0.0,0.0))
@test plane.normal == VecE3(1.0,0.0,0.0)
@test plane.offset == 0.0
plane = Plane3(VecE3(2.0,0.0,0.0), VecE3(1.0,1.0,1.0))
@test plane.normal == VecE3(1.0,0.0,0.0)
@test isapprox(plane.offset, -1.0, atol=1e-10)
plane = Plane3(VecE3(1.0,1.0,0.0), VecE3(1.0,0.0,0.0), VecE3(0.0,0.0,0.0))
@test norm(plane.normal - VecE3(0.0,0.0,1.0)) < 1e-8
@test isapprox(plane.offset, 0.0, atol=1e-10)
plane = Plane3(VecE3(0.0,0.0,0.0), VecE3(1.0,0.0,0.0), VecE3(1.0,1.0,0.0))
@test norm(plane.normal - VecE3(0.0,0.0,-1.0)) < 1e-8
@test isapprox(plane.offset, 0.0, atol=1e-10)
plane = Plane3()
@test isapprox(get_signed_distance(plane, VecE3( 0.0,0.0,0.0)), 0.0, atol=1e-10)
@test isapprox(get_signed_distance(plane, VecE3( 1.0,0.0,0.0)), 1.0, atol=1e-10)
@test isapprox(get_signed_distance(plane, VecE3(-1.0,0.0,0.0)), -1.0, atol=1e-10)
@test isapprox(get_signed_distance(plane, VecE3( 1.0,0.5,0.7)), 1.0, atol=1e-10)
@test isapprox(get_signed_distance(plane, VecE3(-1.0,0.7,0.5)), -1.0, atol=1e-10)
@test isapprox(get_distance(plane, VecE3(-1.0,0.7,0.5)), 1.0, atol=1e-10)
@test norm(proj(VecE3(-1.0,0.7,0.5), plane) - VecE3(0.0,0.7,0.5)) < 1e-10
@test get_side(plane, VecE3( 0.0,0.0,0.0)) == 0
@test get_side(plane, VecE3( 1.0,0.0,0.0)) == 1
@test get_side(plane, VecE3(-1.0,0.0,0.0)) == -1
@test get_side(plane, VecE3( 1.0,0.5,0.7)) == 1
@test get_side(plane, VecE3(-1.0,0.7,0.5)) == -1
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 1235 | let
q = Quat(1.0,2.0,3.0,4.5)
@test length(q) == 4
@test imag(q) == VecE3(1.0,2.0,3.0)
@test conj(q) == Quat(-1.0,-2.0,-3.0,4.5)
@test vec(q) == [1.0,2.0,3.0,4.5]
@test vec(copy(q)) == vec(q)
@test convert(Quat, [1.0,2.0,3.0,4.5]) == q
@test norm(q) == norm(vec(q))
@test vec(normalize(q)) == vec(q) ./ norm(vec(q))
q = Quat(-0.002, -0.756, 0.252, -0.604)
sol = push!(vec(get_axis(q)), get_rotation_angle(q))
@test isapprox(sol, [-0.00250956, -0.948614, 0.316205, mod2pi(-1.84447)], atol=1e-3) ||
isapprox(sol, [ 0.00250956, 0.948614, -0.316205, mod2pi( 1.84447)], atol=1e-3)
seed!(0)
for i in 1 : 5
a = normalize(VecE3(rand(),rand(),rand()))
b = normalize(VecE3(rand(),rand(),rand()))
q = quat_for_a2b(a,b)
@test norm(rot(q, a) - b) < 1e-8
end
@test isapprox(angledist(Quat(1,0,0,0), Quat(0,1,0,0)), π, atol=1e-6)
@test norm(lerp(Quat(1,0,0,0), Quat(0,1,0,0), 0.5) - Quat(√2/2, √2/2, 0, 0)) < 1e-6
seed!(0)
for i in 1 : 5
q = rand(Quat)
@test isapprox(norm(q), 1.0, atol=1e-8)
@test norm(inv(q)*q - Quat(0,0,0,1)) < 1e-8
@test norm(q*inv(q) - Quat(0,0,0,1)) < 1e-8
end
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 3405 | let
a = VecE2()
@test typeof(a) <: VecE
@test typeof(a) <: AbstractVec
@test a.x == 0.0
@test a.y == 0.0
b = VecE2(0.0,0.0)
@test b.x == 0.0
@test b.y == 0.0
@test length(a) == 2
@test a == b
@test isequal(a, b)
@test copy(a) == a
@test convert(Vector{Float64}, a) == [0.0,0.0]
@test convert(VecE2, [0.0,0.0]) == a
@test isapprox(polar(1.0,0.0), VecE2(1.0,0.0))
@test isapprox(polar(2.0,π/2), VecE2(0.0,2.0))
@test isapprox(polar(3.0,-π/2), VecE2(0.0,-3.0))
@test isapprox(polar(-0.5,1.0*π), VecE2(0.5,0.0))
a = VecE2(0.0,1.0)
b = VecE2(0.5,2.0)
@test a != b
@test a + b == VecE2(0.5, 3.0)
@test a .+ 1 == VecE2(1.0, 2.0)
@test a .+ 0.5 == VecE2(0.5, 1.5)
@test a - b == VecE2(-0.5, -1.0)
@test a .- 1 == VecE2(-1.0, 0.0)
@test a .- 0.5 == VecE2(-0.5, 0.5)
@test a * 2 == VecE2(0.0, 2.0)
@test a * 0.5 == VecE2(0.0, 0.5)
@test a / 2 == VecE2(0.0, 0.5)
@test a / 0.5 == VecE2(0.0, 2.0)
@test b.^2 == VecE2(0.25, 4.0)
@test b.^0.5 == VecE2(0.5^0.5, 2.0^0.5)
@test a.%2.0 == VecE2(0.0, 1.0)
@test isfinite(a)
@test !isfinite(VecE2(Inf,0))
@test !isfinite(VecE2(0,Inf))
@test !isfinite(VecE2(0,-Inf))
@test !isfinite(VecE2(Inf,Inf))
@test !isinf(a)
@test isinf(VecE2(Inf,0))
@test isinf(VecE2(0,Inf))
@test isinf(VecE2(0,-Inf))
@test isinf(VecE2(Inf,Inf))
@test !isnan(a)
@test isnan(VecE2(NaN,0))
@test isnan(VecE2(0,NaN))
@test isnan(VecE2(NaN,NaN))
@test round.(VecE2(0.25,1.75)) == VecE2(0.0,2.0)
@test round.(VecE2(-0.25,-1.75)) == VecE2(-0.0,-2.0)
@test floor.(VecE2(0.25,1.75)) == VecE2(0.0,1.0)
@test floor.(VecE2(-0.25,-1.75)) == VecE2(-1.0,-2.0)
@test ceil.(VecE2(0.25,1.75)) == VecE2(1.0,2.0)
@test ceil.(VecE2(-0.25,-1.75)) == VecE2(-0.0,-1.0)
@test trunc.(VecE2(0.25,1.75)) == VecE2(0.0,1.0)
@test trunc.(VecE2(-0.25,-1.75)) == VecE2(-0.0,-1.0)
@test clamp.(VecE2(1.0, 10.0), 0.0, 5.0) == VecE2(1.0, 5.0)
@test clamp.(VecE2(-1.0, 4.0), 0.0, 5.0) == VecE2(0.0, 4.0)
c = VecE2(3.0,4.0)
@test isapprox(abs.(a), VecE2(0.0, 1.0))
@test isapprox(abs.(c), VecE2(3.0, 4.0))
@test isapprox(norm(a), 1.0)
@test isapprox(norm(c), 5.0)
@test isapprox(normalize(a), VecE2(0.0,1.0))
@test isapprox(normalize(b), VecE2(0.5/sqrt(4.25),2.0/sqrt(4.25)))
@test isapprox(normalize(c), VecE2(3.0/5,4.0/5))
@test isapprox(dist(a,a), 0.0)
@test isapprox(dist(b,b), 0.0)
@test isapprox(dist(c,c), 0.0)
@test isapprox(dist(a,b), hypot(0.5, 1.0))
@test isapprox(dist(a,c), hypot(3.0, 3.0))
@test isapprox(dist2(a,a), 0.0)
@test isapprox(dist2(b,b), 0.0)
@test isapprox(dist2(c,c), 0.0)
@test isapprox(dist2(a,b), 0.5^2 + 1^2)
@test isapprox(dist2(a,c), 3^2 + 3^2)
@test isapprox(dot(a, b), 2.0)
@test isapprox(dot(b, c), 1.5 + 8.0)
@test isapprox(dot(c, c), norm(c)^2)
@test isapprox(proj(b, a, Float64), 2.0)
@test isapprox(proj(c, a, Float64), 4.0)
@test isapprox(proj(b, a, VecE2), VecE2(0.0, 2.0))
@test isapprox(proj(c, a, VecE2), VecE2(0.0, 4.0))
@test isapprox(lerp(VecE2(0,0), VecE2(2,-2), 0.25), VecE2(0.5,-0.5))
@test isapprox(lerp(VecE2(2,-2), VecE2(3,-3), 0.5), VecE2(2.5,-2.5))
@test isapprox(rot180(b), VecE2(-0.5,-2.0))
@test isapprox(rotr90(b), VecE2( 2.0,-0.5))
@test isapprox(rotl90(b), VecE2(-2.0, 0.5))
@test isapprox(rot(b, 1.0*pi), VecE2(-0.5,-2.0))
@test isapprox(rot(b, -π/2), VecE2( 2.0,-0.5))
@test isapprox(rot(b, π/2), VecE2(-2.0, 0.5))
@test isapprox(rot(b, 2π), b)
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 4251 | let
a = VecE3()
@test typeof(a) <: VecE3
@test typeof(a) <: AbstractVec
@test a.x == 0.0
@test a.y == 0.0
@test a.z == 0.0
b = VecE3(0.0,0.0,0.0)
@test b.x == 0.0
@test b.y == 0.0
@test b.z == 0.0
@test length(a) == 3
@test a == b
@test isequal(a, b)
@test copy(a) == a
@test convert(Vector{Float64}, a) == [0.0,0.0,0.0]
@test convert(VecE3, [0.0,0.0,0.0]) == a
@test isapprox(polar(1.0,0.0,0.0), VecE3(1.0,0.0,0.0))
@test isapprox(polar(2.0,π/2,1.0), VecE3(0.0,2.0,1.0))
@test isapprox(polar(3.0,-π/2,-0.5), VecE3(0.0,-3.0,-0.5))
@test isapprox(polar(-0.5,1.0*π,1.0*π), VecE3(0.5,0.0,1.0*π))
a = VecE3(0.0,1.0, 2.0)
b = VecE3(0.5,2.0,-3.0)
@test a != b
@test a + b == VecE3(0.5, 3.0, -1.0)
@test a .+ 1 == VecE3(1.0, 2.0, 3.0)
@test a .+ 0.5 == VecE3(0.5, 1.5, 2.5)
@test a - b == VecE3(-0.5, -1.0, 5.0)
@test a .- 1 == VecE3(-1.0, 0.0, 1.0)
@test a .- 0.5 == VecE3(-0.5, 0.5, 1.5)
@test a * 2 == VecE3(0.0, 2.0, 4.0)
@test a * 0.5 == VecE3(0.0, 0.5, 1.0)
@test a / 2 == VecE3(0.0, 0.5, 1.0)
@test a / 0.5 == VecE3(0.0, 2.0, 4.0)
@test b.^2 == VecE3(0.25, 4.0, 9.0)
@test VecE3(0.5, 2.0, 3.0).^0.5 == VecE3(0.5^0.5, 2.0^0.5, 3.0^0.5)
@test isfinite(a)
@test !isfinite(VecE3(Inf,0,0))
@test !isfinite(VecE3(0,Inf,0))
@test !isfinite(VecE3(0,-Inf,0))
@test !isfinite(VecE3(Inf,Inf,Inf))
@test !isinf(a)
@test isinf(VecE3(Inf,0,0))
@test isinf(VecE3(0,Inf,0))
@test isinf(VecE3(0,-Inf,0))
@test isinf(VecE3(Inf,Inf,Inf))
@test !isnan(a)
@test isnan(VecE3(NaN,0,NaN))
@test isnan(VecE3(0,NaN,NaN))
@test isnan(VecE3(NaN,NaN,NaN))
@test round.(VecE3(0.25,1.75,0)) == VecE3(0.0,2.0,0.0)
@test round.(VecE3(-0.25,-1.75,0)) == VecE3(-0.0,-2.0,0.0)
@test floor.(VecE3(0.25,1.75,0.0)) == VecE3(0.0,1.0,0.0)
@test floor.(VecE3(-0.25,-1.75,0.0)) == VecE3(-1.0,-2.0,0.0)
@test ceil.(VecE3(0.25,1.75,0.0)) == VecE3(1.0,2.0,0.0)
@test ceil.(VecE3(-0.25,-1.75,0.0)) == VecE3(-0.0,-1.0,0.0)
@test trunc.(VecE3(0.25,1.75,0.0)) == VecE3(0.0,1.0,0.0)
@test trunc.(VecE3(-0.25,-1.75,0.0)) == VecE3(-0.0,-1.0,0.0)
@test clamp.(VecE3(1.0, 10.0, 0.5), 0.0, 5.0) == VecE3(1.0, 5.0, 0.5)
@test clamp.(VecE3(-1.0, 4.0, 5.5), 0.0, 5.0) == VecE3(0.0, 4.0, 5.0)
c = VecE3(3.0,4.0,5.0)
@test isapprox(abs.(a), a)
@test isapprox(abs.(c), c)
@test isapprox(norm(c), sqrt(3^2 + 4^2 + 5^2))
@test isapprox(normalize(a), VecE3(0.0,1.0/hypot(1.0,2.0), 2.0/hypot(1.0,2.0)))
@test isapprox(dist(a,a), 0.0)
@test isapprox(dist(b,b), 0.0)
@test isapprox(dist(c,c), 0.0)
@test isapprox(dist(a,b), norm([0.5, 1.0, 5.0]))
@test isapprox(dist(a,c), norm([3.0, 3.0, 3.0]))
@test isapprox(dist2(a,a), 0.0)
@test isapprox(dist2(b,b), 0.0)
@test isapprox(dist2(c,c), 0.0)
@test isapprox(dist2(a,b), 0.5^2 + 1^2 + 5^2)
@test isapprox(dist2(a,c), 3^2 + 3^2 + 3^2)
@test isapprox(dot(a, b), 2.0 - 6.0)
@test isapprox(dot(b, c), 1.5 + 8.0 - 15.0)
@test isapprox(dot(c, c), norm(c)^2)
@test isapprox(proj(b, a, Float64), -norm(VecE3(0.0, -0.8, -1.6)))
@test isapprox(proj(c, a, Float64), norm(VecE3(0.0, 2.8, 5.6)))
@test isapprox(proj(b, a, VecE3), VecE3(0.0, -0.8, -1.6))
@test isapprox(proj(c, a, VecE3), VecE3(0.0, 2.8, 5.6))
@test isapprox(lerp(VecE3(0,0,0), VecE3(2,-2,2), 0.25), VecE3(0.5,-0.5,0.5))
@test isapprox(lerp(VecE3(2,-2,2), VecE3(3,-3,3), 0.5), VecE3(2.5,-2.5,2.5))
@test isapprox(rot(VecE3(1,2,3), VecE3(2,0,0), 0.0), VecE3(1,2,3))
@test isapprox(rot(VecE3(1,2,3), VecE3(2,0,0), π/2), VecE3(1,-3,2))
@test isapprox(rot(VecE3(1,2,3), VecE3(2,0,0), -π/2), VecE3(1,3,-2))
@test isapprox(rot(VecE3(1,2,3), VecE3(2,0,0), 1.0π), VecE3(1,-2,-3))
@test isapprox(rot(VecE3(1,2,3), VecE3(0,2,0), π/2), VecE3(3,2,-1))
@test isapprox(rot(VecE3(1,2,3), VecE3(0,0,2), π/2), VecE3(-2,1,3))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(1,0,0), 0.0), VecE3(1,2,3))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(1,0,0), π/2), VecE3(1,-3,2))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(1,0,0), -π/2), VecE3(1,3,-2))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(1,0,0), 1.0π), VecE3(1,-2,-3))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(0,1,0), π/2), VecE3(3,2,-1))
@test isapprox(rot_normalized(VecE3(1,2,3), VecE3(0,0,1), π/2), VecE3(-2,1,3))
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 2505 | let
a = VecSE2()
@test typeof(a) <: VecSE
@test typeof(a) <: AbstractVec
@test a.x == 0.0
@test a.y == 0.0
@test a.θ == 0.0
b = VecSE2(0.0,0.0,0.0)
@test b.x == 0.0
@test b.y == 0.0
@test b.θ == 0.0
c = VecSE2(VecE2(0.0,0.0),0.0)
@test c.x == 0.0
@test c.y == 0.0
@test c.θ == 0.0
@test length(a) == 3
@test a == b
@test b == c
@test a == c
@test isequal(b, a)
@test copy(a) == a
@test convert(Vector{Float64}, a) == [0.0,0.0,0.0]
@test convert(VecSE2, [1.0,2.0,3.0]) == VecSE2(1.0,2.0,3.0)
@test convert(VecE2, VecSE2(1.0,2.0,3.0)) == VecE2(1.0,2.0)
@test isapprox(polar( 1.0, 0.0, 0.5), VecSE2(1.0,0.0,0.5))
@test isapprox(polar( 2.0, π/2,-0.5), VecSE2(0.0,2.0,-0.5))
@test isapprox(polar( 3.0,-π/2, 1), VecSE2(0.0,-3.0,1.0))
@test isapprox(polar(-0.5, 1π, -1), VecSE2(0.5,0.0,-1))
a = VecSE2(0.0,1.0,π/2)
b = VecSE2(0.5,2.0,-π)
unit_e2 = VecE2(1.0, 1.0)
@test a != b
@test a + b == VecSE2(0.5, 3.0, -π/2)
@test a + 1*unit_e2 == VecSE2(1.0, 2.0, π/2)
@test a + 0.5*unit_e2 == VecSE2(0.5, 1.5, π/2)
@test 1*unit_e2 + a == VecSE2(1.0, 2.0, π/2)
@test 0.5*unit_e2 + a == VecSE2(0.5, 1.5, π/2)
@test a - b == VecSE2(-0.5, -1.0, 3π/2)
@test a - 1*unit_e2 == VecSE2(-1.0, 0.0, π/2)
@test a - 0.5*unit_e2 == VecSE2(-0.5, 0.5, π/2)
@test 1*unit_e2 - a == VecSE2(1.0, 0.0, -π/2)
@test 0.5*unit_e2 - a == VecSE2(0.5, -0.5, -π/2)
@test scale_euclidean(a, 2) == VecSE2(0.0, 2.0, π/2)
@test scale_euclidean(a, 0.5) == VecSE2(0.0, 0.5, π/2)
@test scale_euclidean(a, 1/2) == VecSE2(0.0, 0.5, π/2)
@test scale_euclidean(a, 1/0.5) == VecSE2(0.0, 2.0, π/2)
@test clamp_euclidean(VecSE2(1.0, 10.0, 0.5), 0.0, 5.0) == VecSE2(1.0, 5.0, 0.5)
@test clamp_euclidean(VecSE2(-1.0, 4.0, 5.5), 0.0, 5.0) == VecSE2(0.0, 4.0, 5.5)
@test isfinite(a)
@test !isfinite(VecSE2(Inf,0))
@test !isfinite(VecSE2(0,Inf))
@test !isfinite(VecSE2(0,-Inf))
@test !isfinite(VecSE2(Inf,Inf))
@test !isinf(a)
@test isinf(VecSE2(Inf,0))
@test isinf(VecSE2(0,Inf))
@test isinf(VecSE2(0,-Inf))
@test isinf(VecSE2(Inf,Inf))
@test !isnan(a)
@test isnan(VecSE2(NaN,0))
@test isnan(VecSE2(0,NaN))
@test isnan(VecSE2(NaN,NaN))
c = VecSE2(3.0,4.0)
@test isapprox(norm(VecE2(a)), 1.0)
@test isapprox(norm(VecE2(b)), hypot(0.5, 2.0))
@test isapprox(norm(VecE2(c)), hypot(3.0, 4.0))
@test isapprox(normalize(VecE2(a)), VecE2(0.0,1.0))
@test isapprox(normalize(VecE2(b)), VecE2(0.5/sqrt(4.25),2.0/sqrt(4.25)))
@test isapprox(normalize(VecE2(c)), VecE2(3.0/5,4.0/5))
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | code | 639 | import LinearAlgebra: norm, normalize, dot
import Random: seed!
@test invlerp(0.0,1.0,0.5) ≈ 0.5
@test invlerp(0.0,1.0,0.4) ≈ 0.4
@test invlerp(0.0,1.0,0.7) ≈ 0.7
@test invlerp(10.0,20.0,12.0) ≈ 0.2
@testset "VecE2" begin
include("test_vecE2.jl")
end
@testset "VecE3" begin
include("test_vecE3.jl")
end
@testset "VecSE2" begin
include("test_vecSE2.jl")
end
@testset "quaternions" begin
include("test_quat.jl")
end
@testset "coordinate transforms" begin
include("test_coordinate_transforms.jl")
end
@testset "geom" begin
include("test_geomE2.jl")
end
@testset "diff" begin
include("test_diff.jl")
end
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 675 | # Automotive Simulator
A Julia package containing tools for automotive simulations in 2D.
[](https://github.com/sisl/AutomotiveSimulator.jl/actions)
[](https://codecov.io/gh/sisl/AutomotiveSimulator.jl)
[](https://sisl.github.io/AutomotiveSimulator.jl/dev)
For visualization code please see [AutomotiveVisualization](https://github.com/sisl/AutomotiveVisualization.jl).
## Installation
```julia
using Pkg
Pkg.add("AutomotiveSimulator")
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 3562 | # Roadways
## Data Types and Accessing Elements
The data structure to represent roadways can be decomposed as follows:
- **Roadway** The high level type containing all the information. It contains a list of `RoadSegment`.
- **RoadSegment**: a vector of lanes
- **Lane**: A driving lane on a roadway. It identified by a `LaneTag`. A lane is defined by a curve which
represents a center line and a width. In addition it has attributed like speed limit. A lane can be connected to other lane in the roadway, the connection are specified in the exits
and entrances fields.
**Lower level types:**
- **Curves**: A curve is a list of `CurvePt`
- **CurvePt**: the lowest level type. It represents a point on a curve by its global position, position along the curve, curvature at this point and derivative of the curvature at this point. Other types like `CurveIndex` or `CurveProjection` are used to identify a curve point along a curve.
```@docs
Roadway
RoadSegment
move_along
```
## Roadway generation
`AutomotiveSimulator.jl` provide high level functions to generate road networks by drawing straight road segment and circular curves. Two predefined road network can be generated easily: multi-lane straight roadway sections and a multi-lane stadium shaped roadway.
```@docs
gen_straight_curve
gen_straight_segment
gen_bezier_curve
gen_straight_roadway
gen_stadium_roadway
```
## Lane
The `Lane` data structure represent a driving lane in the roadway. The default lane width is 3m. It contains all the low level geometry information.
```@docs
Lane
LaneTag
lanes
lanetags
SpeedLimit
LaneBoundary
LaneConnection
is_in_exits
is_in_entrances
connect!
is_between_segments_hi
is_between_segments
has_segment
has_lanetag
next_lane
prev_lane
has_next
has_prev
next_lane_point
prev_lane_point
n_lanes_left(roadway::Roadway, lane::Lane)
n_lanes_right(roadway::Roadway, lane::Lane)
leftlane(::Roadway, ::Lane)
rightlane(::Roadway, ::Lane)
```
## Frenet frame
The Frenet frame is a lane relative frame to represent a position on the road network.
```@docs
Frenet
```
## Accessing objects and projections
The main `roadway` object can be indexed by different object to access different elements
such as lane or curve points:
- `LaneTag`: indexing roadway by a lane tag will return the lane associated to the lane tag
- `RoadIndex`: indexing roadway by a road index will return the curve point associated to this index
```@docs
RoadIndex
CurveIndex
RoadProjection
proj(posG::VecSE2{T}, lane::Lane{T}, roadway::Roadway{T};move_along_curves::Bool = true ) where T<: Real
proj(posG::VecSE2{T}, seg::RoadSegment, roadway::Roadway) where T<: Real
proj(posG::VecSE2{T}, roadway::Roadway) where T<: Real
Base.getindex(lane::Lane{T}, ind::CurveIndex{I,T}, roadway::Roadway{T}) where{I<:Integer, T<:Real}
Base.getindex(roadway::Roadway, segid::Int)
Base.getindex(roadway::Roadway, tag::LaneTag)
```
## Low level
```@docs
Curve
CurvePt
CurveProjection
is_at_curve_end
get_lerp_time
index_closest_to_point
get_curve_index
lerp(A::VecE2{T}, B::VecE2{T}, C::VecE2{T}, D::VecE2{T}, t::T) where T<:Real
lerp(A::VecE2{T}, B::VecE2{T}, C::VecE2{T}, t::T) where T<:Real
```
## Read and Write roadways
```@docs
Base.read(io::IO, ::Type{Roadway})
Base.write(io::IO, roadway::Roadway)
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 664 | # Vec
`Vec` is a submodule of AutomotiveSimulator that provides several vector types, named after their groups. All types are immutable and are subtypes of ['StaticArrays'](https://github.com/JuliaArrays/StaticArrays.jl)' `FieldVector`, so they can be indexed and used as vectors in many contexts.
* `VecE2` provides an (x,y) type of the Euclidean-2 group.
* `VecE3` provides an (x,y,z) type of the Euclidean-3 group.
* `VecSE2` provides an (x,y,theta) type of the special-Euclidean 2 group.
```julia
v = VecE2(0, 1)
v = VecSE2(0,1,0.5)
v = VecE3(0, 1, 2)
```
Additional geometry types include `Quat` for quaternions, `Line`, `LineSegment`, and `Projectile`.
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 495 | # Driving Actions
In the driving stack, the `actions` lie one level below
the `behaviors`. While the `behaviors` provide the high level
decision making, the actions enable the execution of these decisions in
the simulation.
## Interface
```@docs
propagate
```
## Action types available
```@docs
AccelDesang
```
```@docs
AccelSteeringAngle
```
```@docs
AccelTurnrate
```
```@docs
LaneFollowingAccel
```
```@docs
LatLonAccel
```
```@docs
PedestrianLatLonAccel
``` | AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 717 | # Agent Definition
Agent Definitions describe the static properties of a traffic participants such as the length and width of the vehicle.
It also contains information on the type of agent (car, pedestrian, motorcycle...).
## Interface
You can implement your own agent definition by creating a new type inheriting from the `AbstractAgentDefinition` type.
The following three functions must be implemented for your custom type:
```@docs
AbstractAgentDefinition
length
width
class
```
Agent classes such as car, truck, and pedestrian are defined by integer constant in a submodule AgentClass.
```@docs
AgentClass
```
## Available Agent Definitions
```@docs
VehicleDef
BicycleModel
``` | AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 1624 | # Behaviors
These stands one level above the `actions`. They provide a higher level decision that
the `actions` then implement in order to propagate the simulation forward.
A behavior model can be interpreted as a control law. Given the current scene, representing all
the vehicles present in the environment, a behavior model returns an action to execute.
## Interface
We provide an interface to interact with behavior model or implement your own. To implement your own driver model you can create a type that inherits from the abstract type `DriverModel`. Then you can implement the following methods:
```@docs
DriverModel{DriveAction}
action_type(::DriverModel{A}) where A
set_desired_speed!
reset_hidden_state!
reset_hidden_states!
observe!
Base.rand(model::DriverModel)
```
`observe!` and `rand` are usually the most important methods to implement. `observe!` sets the model state in a given situation and `rand` allows to sample an action from the model.
## Available Behaviors
```@docs
IntelligentDriverModel
```
```@docs
Tim2DDriver
```
```@docs
PrincetonDriver
```
```@docs
SidewalkPedestrianModel
```
```@docs
StaticDriver
```
## Lane change helper functions
These are not standalone driver models but are used by the driver models to do
lane changing and lateral control.
```@docs
MOBIL
```
```@docs
TimLaneChanger
```
```@docs
ProportionalLaneTracker
```
## Longitudinal helper functions
These are not standalone driver models but are used to do longitudinal control by the
driver models.
```@docs
ProportionalSpeedTracker
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 1058 | # Collision Checker
There are two collisions checkers currently available in AutomotiveSimulator.jl.
The first collision checker is accessible through the function `is_colliding` and relies on Minkowski sum.
The second one is accessible through `collision_checker` and uses the parallel axis theorem. The latter is a bit faster.
A benchmark script is available in `test/collision_checkers_benchmark.jl` and relies on static arrays.
## Parallel Axis Theorem
This collision checker relies on the parallel axis theorem. It checks that two convex polygon overlap
```@docs
collision_checker
```
Vehicles can be converted to polygon (static matrices containing four vertices).
```@docs
polygon
```
## Minkowski Sum
Here are the methods available using Minkowski sum.
```@docs
is_colliding
ConvexPolygon
CPAMemory
CollisionCheckResult
to_oriented_bounding_box!
get_oriented_bounding_box
is_potentially_colliding
get_collision_time
get_first_collision
is_collision_free
get_distance
get_edge
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 4313 | # Feature Extraction
AutomotiveSimulator.jl provides useful functions to extract information from a scene.
## Feature Extraction Pipeline
The function `extract_features` can be used to extract information from a list of scenes. It takes as input a vector of scenes (which could be the output of `simulate`), as well as a list of feature functions to use. The output is a dictionary of DataFrame from [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl).
```@docs
extract_features
```
## Finding neighbors
Finding neighbors of an entity is a common query and can be done using the `find_neighbor` function.
This function allows to find the neighbor of an entity within a scene using a forward search method.
The search algorithm moves longitudinally along a given lane and its successors (according to the given road topology).
Once it finds a car it stops searching and return the results as a `NeighborLongitudinalResult`
```@docs
NeighborLongitudinalResult
```
The `find_neighbor` function accepts different keyword argument to search front or rear neighbors, or neighbors on different lanes.
```@docs
find_neighbor
```
When computing the distance to a neighbor, one might want to choose different reference points on the vehicle (center to center, bumper to bumper, etc...). AutomotiveSimulator provides the `VehicleTargetPoint` types to do so.
One can choose among three possible instances to use the front, center, or rear point of a vehicle to compute the distance to the neighbor.
```@docs
VehicleTargetPoint
VehicleTargetPointCenter
VehicleTargetPointFront
VehicleTargetPointRear
```
To get the relative position of two vehicles in the Frenet frame, the `get_frenet_relative_position` can be used.
It stores the result in a `FrenetRelativePosition` object.
```@docs
get_frenet_relative_position
FrenetRelativePosition
```
## Implementing Your Own Feature Function
In AutomotiveSimulator, features are functions. The current interface supports three methods:
- `myfeature(::Roadway, ::Entity)`
- `myfeature(::Roadway, ::Scene, ::Entity)`
- `myfeature(::Roadway, ::Vector{<:Scene}, ::Entity)`
For each of those methods, the last argument correspond to the entity with one of the ID given to the top level `extract_features` function.
Creating a new feature consists of implementing **one** of those methods for your feature function.
As an example, let's define a feature function that returns the distance to the rear neighbor. Such feature will use the second method since it needs information about the whole scene to find the neighbor. If there are not rear neighbor then the function will return `missing`. `DataFrame` are designed to handled missing values so it should not be an issue.
```julia
function distance_to_rear_neighbor(roadway::Roadway, scene::Scene, ego::Entity)
neighbor = find_neighbor(scene, roadway, ego, rear=true)
if neighbor.ind === nothing
return missing
else
return neighbor.Δs
end
end
```
Now you can use your feature function in extract features, the name of the function is used to name the column of the dataframe:
```julia
dfs = extract_features((distance_to_rear_neighbor,), roadway, scenes, [1])
dfs[1].distance_to_rear_neighbor # contains history of distances to rear neighor
```
!!!note
If the supported methods are limiting for your use case please open an issue or submit a PR.
It should be straightforward to extend the `extract_features` function to support other methods, as well as adding new feature trait.
## List of Available Features
```@docs
posgx
posgy
posgθ
posfs
posft
posfϕ
vel(roadway::Roadway, veh::Entity)
velfs
velft
velgx
velgy
time_to_crossing_right
time_to_crossing_left
estimated_time_to_lane_crossing
iswaiting
iscolliding
distance_to
acc
accfs
accft
jerk
jerkft
turn_rate_g
turn_rate_f
isbraking
isaccelerating
lane_width
markerdist_left
markerdist_right
road_edge_dist_left
road_edge_dist_right
lane_offset_left
lane_offset_right
n_lanes_left(roadway::Roadway, veh::Entity)
n_lanes_right(roadway::Roadway, veh::Entity)
has_lane_left
has_lane_right
lane_curvature
dist_to_front_neighbor
front_neighbor_speed
time_to_collision
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 2458 | # AutomotiveSimulator
This is the documentation for AutomotiveSimulator.jl.
## Concepts
This section defines a few terms that are used across the package.
### Entity
An entity (or sometimes called agent) is a traffic participant that navigates in the environment, it is defined by a physical state (position, velocity, ...), an agent definition (whether it is a car or pedestrian, how large it is, ...), and an ID.
`AutomotiveSimulator` is templated to efficiently run simulations with different types of entities.
An entity represents an agent in the simulation, and it is parameterized by
- `S`: state of the entity, may change over time
- `D`: definition of the entity, does not change over time
- `I`: unique identifier for the entity, typically an `Int64` or `Symbol`
The interface for implementing your own state type is described in [States](@ref).
Similarly, an interface for implementing your own entity definition is described in [Agent Definition](@ref)
In addition to the state, definition and identifier for each simulation agent,
one can also customize the actions, environment and the driver models used by
the agents.
### Actions
An action consists of a command applied to move the entity (e.g. longitudinal acceleration, steering). The state of the entity is updated using the `propagate` method which encodes the dynamics model.
### Scene
A scene represents a snapshot in time of a driving situation, it essentially consists of a list of entities at a given time.
It is implemented using the `Scene` object. `Scene` supports most of the operation that one can do on a collection (`iterate`, `in`, `push!`, ...).
In addition it supports `get_by_id` to retrieve an entity by its ID.
### Driver Model
A driver model is a distribution over actions. Given a scene, each entity can update its model, we call this process observation (the corresponding method is `observe!`). After observing the scene, an action can be sampled from the driver model (using `rand`).
## Tutorials
The following examples will showcase some of the simulation functionality of `AutomotiveSimulator`
- [Driving on a Straight Roadway](@ref)
- [Driving in a Stadium](@ref)
- [Intersection](@ref)
- [Crosswalk](@ref)
- [Sidewalk](@ref)
- [Feature Extraction](@ref)
!!! note
All AutomotiveSimulator tutorials are available as
[Jupyter notebooks](https://nbviewer.jupyter.org/)
by clicking on the badge at the beginning of the tutorial!
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 2698 | # Simulation
Simulations can be run using the `simulate` function.
A simulation updates the initial scene forward in time. Each simulation step consists of the following operations:
- call the `observe!` function for each vehicle to update their driver model given the current scene
- sample an action from the driver model by calling `rand` on the driver model.
- update the state of each vehicle using the sampled action and the `propagate` method.
- repeat for the desired number of steps
```@docs
simulate
simulate!
```
See the tutorials for more examples.
## Callbacks
One can define callback functions that will be run at each simulation step. The callback function can terminate the simulation by returning `true`. The default return value of a callback function should be `false`. Callback functions are also useful to log simulation information.
To run a custom callback function in the simulation loop, you must implement a custom callback type and an associated `run_callback` method for that type with the following signature
```julia
function AutomotiveSimulator.run_callback(
cb::ReachGoalCallback,
scenes::Vector{Scene{E}},
actions::Vector{Scene{A}},
roadway::R,
models::Dict{I,M},
tick::Int,
) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel}
end
```
The `scenes` object holds a snapshot of a scene at each timestep in the range `1:tick`, and the `actions` object holds a `scene` of `EntityAction`s which record the action of each vehicle for the time steps `1:(tick-1)`.
Here is an example of a callback that checks if a vehicle's longitudinal position has reached some goal position and stops the simulation if it is the case.
```julia
struct ReachGoalCallback # a callback that checks if vehicle veh_id has reach a certain position
goal_pos::Float64
veh_id::Int64
end
function AutomotiveSimulator.run_callback(
cb::ReachGoalCallback,
scenes::Vector{Scene{E}},
actions::Vector{Scene{A}},
roadway::R,
models::Dict{I,M},
tick::Int,
) where {E<:Entity,A<:EntityAction,R,I,M<:DriverModel}
veh = get_by_id(last(scenes), cb.veh_id)
return veh.state.posF.s > cb.goal_pos
end
```
A callback for collision is already implemented: `CollisionCallback`.
```@docs
CollisionCallback
```
```@docs
run_callback
```
## Woking with datasets
When working with datasets or pre-recorded datasets, one can replay the simulation using `simulate_from_history`. It allows to update the state of an ego vehicle while other vehicles follow the trajectory given in the dataset.
```@docs
simulate_from_history
simulate_from_history!
observe_from_history!
maximum_entities
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.2 | 8abb2a4050d43b49f41adcfb23ed82f136c76aea | docs | 2529 | # States
In this section of the documentation we explain the default vehicle state type provided by `AutomotiveSimulator`
as well as the data types used to represent a driving scene. Most of the underlying structures are defined in `Records.jl`.
The data structures provided in ADM.jl are concrete instances of parametric types defined in Records. It is possible in principle to define your custom state definition and use the interface defined in ADM.jl.
## Entity state
Entities are represented by the `Entity` data type.
The `Entity` data type has three fields: a state, a definition and an id.
```@docs
Entity
```
The state of an entity usually describes physical quantity such as position and velocity.
Two state data structures are provided.
## Scenes
Scenes are represented using the `Scene` object. It is a datastructure to represent a collection of entities.
```@docs
Scene
```
## Defining your own state type
You can define your own state type if the provided `VehicleState` does not contain the right information.
There are a of couple functions that need to be defined such that other functions in AutomotiveSimulator can work smoothly with your custom state type.
```@docs
posg
posf
vel
velf
velg
```
**Example of a custom state type containing acceleration:**
```julia
# you can use composition to define your custom state type based on existing ones
struct MyVehicleState
veh::VehicleState
acc::Float64
end
# define the functions from the interface
posg(s::MyVehicleState) = posg(s.veh) # those functions are implemented for the `VehicleState` type
posf(s::MyVehicleState) = posf(s.veh)
velg(s::MyVehicleState) = velg(s.veh)
velf(s::MyVehicleState) = velf(s.veh)
vel(s::MyVehicleState) = vel(s.veh)
```
## Provided State Type and Convenient Functions
Here we list useful functions to interact with vehicle states and retrieve interesting information like the position of the front of the vehicle or the lane to which the vehicle belongs.
```@docs
VehicleState
Vec.lerp(a::VehicleState, b::VehicleState, t::Float64, roadway::Roadway)
move_along(vehstate::VehicleState, roadway::Roadway, Δs::Float64; ϕ₂::Float64=vehstate.posF.ϕ, ::Float64=vehstate.posF.t, v₂::Float64=vehstate.v)
get_front
get_rear
get_center
get_footpoint
get_lane
leftlane(::Roadway, ::Entity)
rightlane(::Roadway, ::Entity)
Base.convert(::Type{Entity{S, VehicleDef, I}}, veh::Entity{S, D, I}) where {S,D<:AbstractAgentDefinition,I}
```
| AutomotiveSimulator | https://github.com/sisl/AutomotiveSimulator.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 2703 | module AxisKeysExt
using AxisKeys
using FlexiGroups.Accessors
using FlexiGroups.DataPipes
using FlexiGroups.Dictionaries: Dictionary
using FlexiGroups: flatten, total
import FlexiGroups: _group, _groupview, _groupfind, _groupmap, addmargins
for f in (:_group, :_groupview, :_groupfind)
@eval function $f(f, xs, ::Type{TA}; default=undef) where {TA <: KeyedArray}
gd = $f(f, xs, Dictionary)
_group_dict_to_ka(gd, default, TA)
end
end
function _groupmap(f, mapf, xs, ::Type{TA}; default=undef) where {TA <: KeyedArray}
gd = _groupmap(f, mapf, xs, Dictionary)
_group_dict_to_ka(gd, default, TA)
end
_proplenses(::Type{<:NTuple{N, Any}}) where {N} = map(IndexLens, 1:N)
_proplenses(::Type{<:NamedTuple{KS}}) where {KS} = map(PropertyLens, KS)
_KeyedArray(A, axkeys::Tuple) = KeyedArray(A, axkeys)
_KeyedArray(A, axkeys::NamedTuple) = KeyedArray(A; axkeys...)
@generated function _group_dict_to_ka(gd::Dictionary{K, V}, default::D, ::Type{KeyedArray}) where {K, V, D}
axkeys_exprs = map(_proplenses(K)) do l
col = :( map($l, keys(gd).values) |> unique |> sort )
end
quote
axkeys = $(constructorof(K))($(axkeys_exprs...),)
vals = gd.values
sz = map(length, values(axkeys))
$(if D === UndefInitializer
:( data = similar(vals, sz) )
else
:( data = fill!(similar(vals, $(Union{V, D}), sz), default) )
end)
for (k, v) in pairs(gd)
# searchsorted relies on sort above
ixs = map(only ∘ searchsorted, axkeys, k)
data[ixs...] = v
end
A = _KeyedArray(data, axkeys)
return A
end
end
function addmargins(A::KeyedArray{V}; combine=flatten, marginkey=total) where {V}
VT = Core.Compiler.return_type(combine, Tuple{Vector{V}})
Ares = convert(AbstractArray{VT}, A)
if ndims(A) == 1
nak = named_axiskeys(A)
nak_ = @modify(only(nak)) do ax
Union{eltype(ax), typeof(marginkey)}[marginkey]
end
m = KeyedArray([combine(A)]; nak_...)
return cat(Ares, m; dims=1)
else
res = Ares
alldims = Tuple(1:ndims(A))
allones = ntuple(Returns(1), ndims(A))
allcolons = map(ax -> Union{eltype(ax), typeof(marginkey)}[marginkey], named_axiskeys(A))
for i in 1:ndims(A)
nak = @set allcolons[i] = named_axiskeys(res)[i]
m = @p let
eachslice(res; dims=i)
map(combine)
reshape(__, @set allones[i] = :)
KeyedArray(__; nak...)
end
res = cat(res, m; dims=@delete alldims[i])
end
return res
end
end
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 242 | module CategoricalArraysExt
using CategoricalArrays
import FlexiGroups: _possible_values
_possible_values(X::CategoricalArray) = levels(X)
_possible_values(X::AbstractArray{<:CategoricalValue}) = isempty(X) ? nothing : levels(first(X))
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 996 | module OffsetArraysExt
using OffsetArrays
import FlexiGroups: _group_core_identity, _similar_1based
function _group_core_identity(X, vals, ::Type{OffsetVector}, len)
@assert eltype(X) == Int
dct = Base.IdentityUnitRange(minimum(X):maximum(X))
ngroups = length(dct)
starts = zeros(Int, first(dct):(last(dct)+1))
starts[begin] = 1
@inbounds for gid in X
starts[gid+1] += 1
end
cumsum!(starts, starts)
# now starts[gid] is the (#elements in groups begin:gid-1) + 1
# or the index of the first element of group gid in (future) rperm
rperm = _similar_1based(vals, length(X))
for (v, gid) in zip(vals, X)
rperm[starts[gid]] = v
starts[gid] += 1
end
# now starts[gid] is the index just after the last element of group gid in rperm
for gid in X
starts[gid] -= 1
end
# dct: key -> group_id
# rperm[starts[group_id]:starts[group_id+1]-1] = group_values
return (; dct, starts, rperm)
end
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 484 | module StructArraysExt
using StructArrays
import FlexiGroups: _possible_values
function _possible_values(X::StructArray{<:Tuple})
vals = map(_possible_values, StructArrays.components(X))
any(isnothing, vals) ? nothing : Iterators.product(vals...)
end
function _possible_values(X::StructArray{<:NamedTuple{KS}}) where {KS}
vals = map(_possible_values, StructArrays.components(X))
any(isnothing, vals) ? nothing : NamedTuple{KS}.(Iterators.product(vals...))
end
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 472 | module FlexiGroups
using Dictionaries
using Combinatorics: combinations
using FlexiMaps: FlexiMaps, flatten, mapview, _eltype, Accessors
using DataPipes
using AccessorsExtra # for values()
export
group, groupview, groupfind, groupmap,
group_vg, groupview_vg, groupfind_vg, groupmap_vg, Group, key, value,
addmargins, MultiGroup, total
include("base.jl")
include("dictbacked.jl")
include("arraybacked.jl")
include("margins.jl")
include("grouptype.jl")
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 934 | function _group_core_identity(X, vals, ::Type{Vector}, len)
@assert eltype(X) == Int
@assert minimum(X) ≥ 1
ngroups = maximum(X)
dct = Base.OneTo(ngroups)
starts = zeros(Int, ngroups)
@inbounds for gid in X
starts[gid] += 1
end
# now starts[gid] is the number of elements in group gid
pushfirst!(starts, 1)
cumsum!(starts, starts)
# now starts[gid] is the (#elements in groups 1:gid-1) + 1
# or the index of the first element of group gid in (future) rperm
rperm = _similar_1based(vals, length(X))
@inbounds for (v, gid) in zip(vals, X)
rperm[starts[gid]] = v
starts[gid] += 1
end
# now starts[gid] is the index just after the last element of group gid in rperm
for gid in X
starts[gid] -= 1
end
# dct: key -> group_id
# rperm[starts[group_id]:starts[group_id+1]-1] = group_values
return (; dct, starts, rperm)
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 5459 | """ group([keyf=identity], X; [restype=Dictionary])
Group elements of `X` by `keyf(x)`, returning a mapping `keyf(x)` values to lists of `x` values in each group.
The result is an (ordered) `Dictionary` by default, but can be specified to be a base `Dict` as well.
Alternatively to dictionaries, specifying `restype=KeyedArray` (from `AxisKeys.jl`) results in a `KeyedArray`. Its `axiskeys` are the group keys.
# Examples
```julia
xs = 3 .* [1, 2, 3, 4, 5]
g = group(isodd, xs)
g == dictionary([true => [3, 9, 15], false => [6, 12]])
g = group(x -> (a=isodd(x),), xs; restype=KeyedArray)
g == KeyedArray([[6, 12], [3, 9, 15]]; a=[false, true])
```
"""
function group end
""" groupview([keyf=identity], X; [restype=Dictionary])
Like the `group` function, but each group is a `view` of `X`: doesn't copy the input elements.
"""
function groupview end
""" groupmap([keyf=identity], mapf, X; [restype=Dictionary])
Like `map(mapf, group(keyf, X))`, but more efficient. Supports a limited set of `mapf` functions: `length`, `first`/`last`, `only`, `rand`.
"""
function groupmap end
group(X; kwargs...) = group(identity, X; kwargs...)
groupfind(X; kwargs...) = groupfind(identity, X; kwargs...)
groupview(X; kwargs...) = groupview(identity, X; kwargs...)
groupmap(mapf, X; kwargs...) = groupmap(identity, mapf, X; kwargs...)
group(f, X; restype=AbstractDictionary, kwargs...) = _group(f, X, restype; kwargs...)
groupfind(f, X; restype=AbstractDictionary, kwargs...) = _groupfind(f, X, restype; kwargs...)
groupview(f, X; restype=AbstractDictionary, kwargs...) = _groupview(f, X, restype; kwargs...)
groupmap(f, mapf, X; restype=AbstractDictionary, kwargs...) = _groupmap(f, mapf, X, restype; kwargs...)
const DICTS = Union{AbstractDict, AbstractDictionary}
const BASERESTYPES = Union{DICTS, AbstractVector}
struct GroupValues end
struct GroupValue end
Accessors.modify(f, obj, ::GroupValues) = @modify(f, values(obj)[∗] |> GroupValue())
Accessors.modify(f, obj, ::GroupValue) = f(obj)
function _groupfind(f::F, X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
@view rperm[starts[gid]:starts[gid + 1]-1]
end
end
function _groupview(f::F, X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
ix = @view rperm[starts[gid]:starts[gid + 1]-1]
@view X[ix]
end
end
function _group(f::F, X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, X, RT)
res = @modify(dct |> GroupValues()) do gid
@inline
@view rperm[starts[gid]:starts[gid + 1]-1]
end
end
function _groupmap(f::F, ::typeof(length), X, ::Type{RT}) where {F, RT <: BASERESTYPES}
vals = if X isa AbstractArray
fill!(similar(X, Nothing), nothing)
else
map(Returns(nothing), X)
end
(; dct, starts, rperm) = _group_core(f, X, vals, RT)
@modify(dct |> GroupValues()) do gid
starts[gid + 1] - starts[gid]
end
end
function _groupmap(f::F, ::typeof(first), X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
ix = rperm[starts[gid]]
X[ix]
end
end
function _groupmap(f::F, ::typeof(last), X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
ix = rperm[starts[gid + 1] - 1]
X[ix]
end
end
function _groupmap(f::F, ::typeof(only), X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
starts[gid + 1] == starts[gid] + 1 || throw(ArgumentError("groupmap(only, X) requires that each group has exactly one element"))
ix = rperm[starts[gid]]
X[ix]
end
end
function _groupmap(f::F, ::typeof(rand), X, ::Type{RT}) where {F, RT <: BASERESTYPES}
(; dct, starts, rperm) = _group_core(f, X, keys(X), RT)
@modify(dct |> GroupValues()) do gid
ix = rperm[rand(starts[gid]:starts[gid + 1]-1)]
X[ix]
end
end
_group_core(f::F, X::AbstractArray, vals, dicttype) where {F} = _group_core(f, X, vals, dicttype, length(X))
_group_core(f::F, X, vals, dicttype) where {F} = _group_core(f, X, vals, dicttype, Base.IteratorSize(X) isa Base.SizeUnknown ? missing : length(X))
_group_core(f::F, X, vals, dicttype, length) where {F} = _group_core_identity(mapview(f, X), vals, dicttype, length)
# XXX: are these specializations useful? seemed to be, before adding ::F specialization to higher-level group...() funcs
# __precompile__(false)
# @eval AccessorsExtra modify(f::F, obj::KVPWrapper{typeof(values)}, ::Elements) where {F} = map(f, obj.obj)
# @eval Dictionaries function Base.map(f::F, d::AbstractDictionary) where {F}
# out = similar(d, Core.Compiler.return_type(f, Tuple{eltype(d)}))
# @inbounds map!(f, out, d)
# return out
# end
if VERSION < v"1.10-"
_similar_1based(vals::AbstractArray, len::Integer) = similar(vals, len)
_similar_1based(vals, len::Integer) = Vector{_eltype(vals)}(undef, len)
else
# applicable() is compiletime in 1.10+
_similar_1based(vals, len::Integer) = applicable(similar, vals, len) ? similar(vals, len) : Vector{_eltype(vals)}(undef, len)
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 3969 |
# Bool group keys: fastpath for performance
function _group_core_identity(X::AbstractArray{Bool}, vals, ::Type{AbstractDictionary}, length::Integer)
ngroups = 0
true_first = isempty(X) ? false : first(X)
dct = isempty(X) ? ArrayDictionary(ArrayIndices(Bool[]), Int[]) : ArrayDictionary(ArrayIndices([true_first, !true_first]), [1, 2])
rperm = _similar_1based(vals, length)
i0 = 1
i1 = length
@inbounds for (v, gid) in zip(vals, X)
atstart = gid == true_first
rperm[atstart ? i0 : i1] = v
atstart ? (i0 += 1) : (i1 -= 1)
end
reverse!(@view(rperm[i0:end]))
if i0 == length + 1 && length > 0
delete!(dct, !true_first)
end
starts = [1, i0, length+1]
return (; dct, starts, rperm)
end
# exhaustive list of possible values in X, eg categories or enum values
# nothing if can't be determined without iterating X
_possible_values(X) = nothing
function _group_core_identity(X, vals, ::Type{DT}, len) where {DT<:DICTS}
levs = @something _possible_values(X) eltype(X)[]
dct = _dict_kv_constructor(DT)(levs, isempty(levs) ? Int[] : Base.OneTo(length(levs)))
ngroups = length(dct)
groups = _groupid_container(len)
@inbounds for (i, x) in enumerate(X)
gid = get!(dct, x, ngroups + 1)
_push_or_set!(groups, i, gid, len)
if gid == ngroups + 1
ngroups += 1
end
end
starts = zeros(Int, ngroups)
@inbounds for gid in groups
starts[gid] += 1
end
# now starts[gid] is the number of elements in group gid
pushfirst!(starts, 1)
cumsum!(starts, starts)
# now starts[gid] is the (#elements in groups 1:gid-1) + 1
# or the index of the first element of group gid in (future) rperm
rperm = _similar_1based(vals, length(groups))
@inbounds for (v, gid) in zip(vals, groups)
rperm[starts[gid]] = v
starts[gid] += 1
end
# now starts[gid] is the index just after the last element of group gid in rperm
for gid in groups
starts[gid] -= 1
end
# dct: key -> group_id
# rperm[starts[group_id]:starts[group_id+1]-1] = group_values
return (; dct, starts, rperm)
end
struct MultiGroup{G}
groups::G
end
Base.hash(mg::MultiGroup, h::UInt) = error("Deliberately unsupported, should be unreachable")
function _group_core_identity(X::AbstractArray{MultiGroup{GT}}, vals, ::Type{DT}, len) where {DT<:DICTS,GT}
dct = _dict_kv_constructor(DT)(eltype(GT)[], Int[])
ngroups = Ref(length(dct))
groups = Vector{_similar_container_type(GT, Int)}(undef, len)
@inbounds for (i, x) in enumerate(X)
groups[i] = map(x.groups) do gkey
gid = get!(dct, gkey, ngroups[] + 1)
if gid == ngroups[] + 1
ngroups[] += 1
end
return gid
end
end
starts = zeros(Int, ngroups[])
@inbounds for gids in groups
for gid in gids
starts[gid] += 1
end
end
cumsum!(starts, starts)
push!(starts, sum(length, groups))
rperm = _similar_1based(vals, sum(length, groups))
@inbounds for (v, gids) in zip(vals, groups)
for gid in gids
rperm[starts[gid]] = v
starts[gid] -= 1
end
end
return (; dct, starts, rperm)
end
_groupid_container(len::Missing) = Int[]
_push_or_set!(groups, i, gid, len::Missing) = push!(groups, gid)
_groupid_container(len::Integer) = Vector{Int}(undef, len)
_push_or_set!(groups, i, gid, len::Integer) = groups[i] = gid
_similar_container_type(::Type{<:AbstractArray}, ::Type{T}) where {T} = Vector{T}
_similar_container_type(::Type{<:NTuple{N,Any}}, ::Type{T}) where {N,T} = NTuple{N,T}
_dict_kv_constructor(::Type{AbstractDict}) = _dict_kv_constructor(Dict)
_dict_kv_constructor(::Type{AbstractDictionary}) = Dictionary
_dict_kv_constructor(::Type{T}) where {T<:AbstractDict} = (ks, vs) -> T(zip(ks, vs))
_dict_kv_constructor(::Type{T}) where {T} = T
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 2214 | struct GroupAny{K,VS}
key::K
value::VS
end
struct GroupArray{K,T,N,VS<:AbstractArray{T,N}} <: AbstractArray{T,N}
key::K
value::VS
end
const Group{K,VS} = Union{GroupAny{K,VS}, GroupArray{K,<:Any,<:Any,VS}}
Group(key, value) = GroupAny(key, value)
Group(key, value::AbstractArray) = GroupArray(key, value)
AccessorsExtra.constructorof(::Type{<:Group}) = Group
key(g::Group) = getfield(g, :key)
value(g::Group) = getfield(g, :value)
Base.values(g::Group) = value(g)
Accessors.set(g::Group, ::typeof(key), k) = Group(k, value(g))
Accessors.set(g::Group, ::typeof(value), v) = Group(key(g), v)
Accessors.set(g::Group, ::typeof(values), v::AbstractArray) = Group(key(g), v)
Accessors.modify(f, obj::Group, ::GroupValue) = modify(f, obj, value)
Base.similar(A::GroupArray) = similar(values(A))
Base.similar(A::GroupArray, ::Type{T}) where {T} = similar(values(A), T)
Base.similar(A::GroupArray, dims) = similar(values(A), dims)
Base.similar(A::GroupArray, ::Type{T}, dims::Tuple{Union{Integer, Base.OneTo}, Vararg{Union{Integer, Base.OneTo}}}) where {T} = similar(values(A), T, dims)
Base.size(g::GroupArray) = size(value(g))
Base.getindex(g::GroupArray, i...) = getindex(value(g), i...)
Base.getproperty(g::Group, p) = getproperty(value(g), p)
Base.getproperty(g::Group, p::Symbol) = getproperty(value(g), p) # disambiguate
Base.:(==)(a::Group, b::Group) = key(a) == key(b) && value(a) == value(b)
Base.:(==)(a::Group, b::AbstractArray) = error("Cannot compare Group with $(typeof(b))")
Base.:(==)(a::AbstractArray, b::Group) = error("Cannot compare Group with $(typeof(a))")
group_vg(args...; kwargs...) = group(args...; kwargs..., restype=Vector{Group})
groupview_vg(args...; kwargs...) = groupview(args...; kwargs..., restype=Vector{Group})
groupfind_vg(args...; kwargs...) = groupfind(args...; kwargs..., restype=Vector{Group})
groupmap_vg(args...; kwargs...) = groupmap(args...; kwargs..., restype=Vector{Group})
function _group_core_identity(X, vals, ::Type{Vector{Group}}, len)
(; dct, starts, rperm) = _group_core_identity(X, vals, AbstractDictionary, len)
grs = @p dct |> pairs |> map() do (k, gid)
Group(k, gid)
end |> collect
(; dct=grs, starts, rperm)
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 3098 | """ addmargins(grouping; [combine=flatten])
Add margins to a `group` or `groupmap` result for all combinations of group key components.
For example, if a dataset is grouped by `a` and `b` (`keyf=x -> (;x.a, x.b)` in `group`), this adds groups for each `a` value and for each `b` value separately.
`combine` specifies how multiple groups are combined into margins. The default `combine=flatten` concatenates all relevant groups into a single collection.
# Examples
```julia
xs = [(a=1, b=:x), (a=2, b=:x), (a=2, b=:y), (a=3, b=:x), (a=3, b=:x), (a=3, b=:x)]
# basic grouping by unique combinations of a and b
g = group(xs)
map(length, g) == dictionary([(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3])
# add margins
gm = addmargins(g)
map(length, gm) == dictionary([
(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3, # original grouping result
(a=1, b=total) => 1, (a=2, b=total) => 2, (a=3, b=total) => 3, # margins for all values of a
(a=total, b=:x) => 5, (a=total, b=:y) => 1, # margins for all values of b
(a=total, b=total) => 6, # total
])
```
"""
function addmargins end
struct MarginKey end
const total = MarginKey()
Base.show(io::IO, ::MIME"text/plain", ::MarginKey) = print(io, "total")
Base.show(io::IO, ::MarginKey) = print(io, "total")
@generated function addmargins(dict::AbstractDictionary{K, V}; combine=flatten, marginkey=total) where {KS, K<:NamedTuple{KS}, V}
dictexprs = map(combinations(reverse(KS))) do ks
kf = :(_marginalize_key_func($(Val(Tuple(ks))), marginkey))
:(merge!(res, _combine_groups_by($kf, dict, combine)))
end
KTs = map(combinations(KS)) do ks
NamedTuple{KS, Tuple{[k ∈ ks ? marginkey : fieldtype(K, k) for k in KS]...}}
end
quote
KT = Union{$K, $(KTs...)}
VT = Core.Compiler.return_type(combine, Tuple{Vector{$V}})
res = Dictionary{KT, VT}()
merge!(res, map(combine ∘ Base.vect, dict))
$(dictexprs...)
end
end
addmargins(dict::AbstractDictionary{K, V}; combine=flatten, marginkey=total) where {N, K<:NTuple{N,Any}, V} =
throw(ArgumentError("`addmargins()` is not implemented for Tuples as group keys. Use NamedTuples instead."))
function addmargins(dict::AbstractDictionary{K, V}; combine=flatten, marginkey=total) where {K, V}
KT = Union{K, typeof(marginkey)}
VT = Core.Compiler.return_type(combine, Tuple{Vector{V}})
res = Dictionary{KT, VT}()
merge!(res, map(combine ∘ Base.vect, dict))
merge!(res, _combine_groups_by(Returns(marginkey), dict, combine))
end
_marginalize_key_func(::Val{ks_colon}, marginkey) where {ks_colon} = key -> merge(key, NamedTuple{ks_colon}(ntuple(Returns(marginkey), length(ks_colon))))
_combine_groups_by(kf, dict::AbstractDictionary, combine) = @p begin
keys(dict)
groupfind(kf)
map() do grixs
combine(mapview(ix -> dict[ix], grixs))
end
end
# could be defaults?
# for arrays/collections/iterables:
# _merge(vals) = flatten(vals)
# for onlinestats:
# _merge(vals) = reduce(merge!, vals; init=copy(first(vals)))
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | code | 18996 | using TestItems
using TestItemRunner
@run_package_tests
@testitem "basic" begin
using Dictionaries
xs = 3 .* [1, 2, 3, 4, 5]
g = @inferred group(isodd, xs)
@test g == dictionary([true => [3, 9, 15], false => [6, 12]])
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
g = @inferred group(x -> isodd(x) ? nothing : false, xs)
@test g == dictionary([nothing => [3, 9, 15], false => [6, 12]])
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
@test group(isodd, [1, 3, 5]) == dictionary([true => [1, 3, 5]])
@test group(Int ∘ isodd, [1, 3, 5]) == dictionary([1 => [1, 3, 5]])
@test group(isodd, Int[]) == dictionary([])
@test group(Int ∘ isodd, Int[]) == dictionary([])
# ensure we get a copy
gc = deepcopy(g)
xs[1] = 123
@test g == gc
xs = 3 .* [1, 2, 3, 4, 5]
g = @inferred groupview(isodd, xs)
@test g == dictionary([true => [3, 9, 15], false => [6, 12]])
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
# ensure we get a view
xs[1] = 123
@test g == dictionary([true => [123, 9, 15], false => [6, 12]])
xs = 3 .* [1, 2, 3, 4, 5]
g = @inferred groupfind(isodd, xs)
@test g == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
g = @inferred(group(isnothing, [1, 2, 3, nothing, 4, 5, nothing]))
@test g == dictionary([false => [1, 2, 3, 4, 5], true => [nothing, nothing]])
@test valtype(g) <: SubArray{Union{Nothing, Int}}
end
@testitem "groupmap" begin
using Dictionaries
xs = 3 .* [1, 2, 3, 4, 5]
for f in [length, first, last]
@test @inferred(groupmap(isodd, f, xs)) == map(f, group(isodd, xs))
end
@test all(@inferred(groupmap(isodd, rand, xs)) .∈ group(isodd, xs))
@test_throws "exactly one element" groupmap(isodd, only, xs)
@test @inferred(groupmap(isodd, only, [10, 11])) == dictionary([false => 10, true => 11])
end
@testitem "multigroup" begin
using Dictionaries
xs = 1:5
G = @inferred(groupmap(
x -> MultiGroup([isodd(x) ? "odd" : "even", x >= 3 ? "large" : "small"]),
length, xs
))
@test G == dictionary([
"odd" => 3,
"small" => 2,
"even" => 2,
"large" => 3,
])
@test @inferred(groupmap(
x -> MultiGroup(x >= 3 ? ["L", "XL"] : x >= 2 ? ["L"] : ["S"]),
length, xs)) == dictionary([
"S" => 1,
"L" => 4,
"XL" => 3,
])
@test @inferred(groupmap(
x -> MultiGroup((isodd(x) ? "odd" : "even", x >= 3 ? "large" : "small")),
length, xs)) == dictionary([
"odd" => 3,
"small" => 2,
"even" => 2,
"large" => 3,
])
@test @inferred(groupmap(
x -> MultiGroup((isodd(x) ? "odd" : "even", x >= 3)),
length, xs)) == dictionary([
"odd" => 3,
false => 2,
"even" => 2,
true => 3,
])
end
@testitem "to vector, offsetvector" begin
using OffsetArrays
xs = [1, 2, 1, 1, 3]
g = group(identity, xs, restype=Vector)
@test g == [[1, 1, 1], [2], [3]]
g = group(x -> isodd(x) ? 2 : 1, xs, restype=Vector)
@test g == [[2], [1, 1, 1, 3]]
@test groupmap(x -> isodd(x) ? 2 : 1, length, xs, restype=Vector) == [1, 4]
@test groupmap(identity, length, xs, restype=Vector) == [3, 1, 1]
@test groupmap(identity, length, 3 .* xs, restype=Vector) == [0, 0, 3, 0, 0, 1, 0, 0, 1]
@test group(identity, 3 .* xs, restype=Vector) == [[], [], [3, 3, 3], [], [], [6], [], [], [9]]
@test_throws AssertionError group(Int ∘ isodd, xs, restype=Vector)
g = group(Int ∘ isodd, xs, restype=OffsetVector)
@test axes(g, 1) == 0:1
@test g[0] == [2]
@test g == OffsetArray([[2], [1, 1, 1, 3]], 0:1)
end
@testitem "Groups" begin
using Accessors
using StructArrays
xs = StructArray(x=3 .* [1, 2, 3, 4, 5])
g = @inferred group_vg(x->isodd(x.x), xs)
@test length(g) == 2
@test key(first(g)) === true
@test values(first(g)).x::SubArray{Int} == [3, 9, 15]
@test isconcretetype(eltype(g))
@test g isa Vector{<:Group{Bool, <:StructArray}}
gr = first(g)
@test gr == gr
@test gr == Group(true, [(x = 3,), (x = 9,), (x = 15,)])
@test gr != Group(true, [(x = 3,), (x = 9,), (x = 10,)])
@test gr != Group(false, [(x = 3,), (x = 9,), (x = 15,)])
@test length(gr) == 3
@test gr[2] == (x=9,)
@test gr.x == [3, 9, 15]
@test map(identity, gr).x == [3, 9, 15]
@test modify(reverse, gr, values) == Group(true, [(x=15,), (x=9,), (x=3,)])
@test @modify(reverse, g |> Elements() |> values)[1] == Group(true, [(x=15,), (x=9,), (x=3,)])
xs = 3 .* [1, 2, 3, 4, 5]
g = @inferred group_vg(x->isodd(x) ? 1 : 0, xs)
@test length(g) == 2
@test key(first(g)) === 1
@test values(first(g))::SubArray{Int} == [3, 9, 15]
@test isconcretetype(eltype(g))
@test g isa Vector{<:Group{Int, <:SubArray{Int}}}
g = @inferred groupmap_vg(x->isodd(x) ? 1 : 0, length, xs)
@test g == [Group(1, 3), Group(0, 2)]
@test isconcretetype(eltype(g))
g = map(group_vg(x -> (o=isodd(x),), xs)) do gr
(; key(gr)..., cnt=length(values(gr)), tot=sum(values(gr)))
end
@test g == [(o=true, cnt=3, tot=27), (o=false, cnt=2, tot=18)]
# gm = @inferred addmargins(g; combine=sum)
# @test g == [Group(1, 3), Group(0, 2), Group(total, 5)]
end
@testitem "margins" begin
using Dictionaries
using StructArrays
xs = [(a=1, b=:x), (a=2, b=:x), (a=2, b=:y), (a=3, b=:x), (a=3, b=:x), (a=3, b=:x)]
g = @inferred group(x -> x, xs)
@test map(length, g) == dictionary([(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3])
gm = @inferred addmargins(g)
@test map(length, gm) == dictionary([
(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3,
(a=1, b=total) => 1, (a=2, b=total) => 2, (a=3, b=total) => 3,
(a=total, b=:x) => 5, (a=total, b=:y) => 1,
(a=total, b=total) => 6,
])
@test keytype(gm) isa Union # of NamedTuples
@test valtype(gm) |> isconcretetype
@test valtype(gm) == Vector{NamedTuple{(:a, :b), Tuple{Int64, Symbol}}}
g = @inferred group(x -> x.a, xs)
@test map(length, g) == dictionary([1 => 1, 2 => 2, 3 => 3])
gm = @inferred addmargins(g)
@test map(length, gm) == dictionary([
1 => 1, 2 => 2, 3 => 3,
total => 6,
])
@test keytype(gm) == Union{Int, typeof(total)}
@test valtype(gm) |> isconcretetype
@test valtype(gm) == Vector{NamedTuple{(:a, :b), Tuple{Int64, Symbol}}}
g = @inferred group(x -> x.a > 2, xs)
@test map(length, g) == dictionary([false => 3, true => 3])
gm = @inferred addmargins(g)
@test map(length, gm) == dictionary([
false => 3, true => 3,
total => 6,
])
@test keytype(gm) == Union{Bool, typeof(total)}
@test valtype(gm) |> isconcretetype
@test valtype(gm) == Vector{NamedTuple{(:a, :b), Tuple{Int64, Symbol}}}
g = @inferred group(x -> x, StructArray(xs))
gm = @inferred addmargins(g)
@test map(length, gm) == dictionary([
(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3,
(a=1, b=total) => 1, (a=2, b=total) => 2, (a=3, b=total) => 3,
(a=total, b=:x) => 5, (a=total, b=:y) => 1,
(a=total, b=total) => 6,
])
@test keytype(gm) isa Union # of NamedTuples
@test valtype(gm) |> isconcretetype
@test valtype(gm) <: StructVector{NamedTuple{(:a, :b), Tuple{Int64, Symbol}}}
g = groupmap(x -> x, length, xs)
gm = @inferred addmargins(g; combine=sum)
@test gm == dictionary([
(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3,
(a=1, b=total) => 1, (a=2, b=total) => 2, (a=3, b=total) => 3,
(a=total, b=:x) => 5, (a=total, b=:y) => 1,
(a=total, b=total) => 6,
])
@test keytype(gm) isa Union # of NamedTuples
@test valtype(gm) == Int
end
@testitem "reassemble" begin
using FlexiMaps
xs = 3 .* [1, 2, 3, 4, 5]
g = groupview(isodd, xs)
gm = flatmap_parent(g -> g ./ sum(g), g)
@test gm == [1/9, 1/3, 1/3, 2/3, 5/9]
@test_throws "must be covered" flatmap_parent(g -> g ./ sum(g), filter(g -> length(g) > 2, g))
end
@testitem "to keyedarray" begin
using AxisKeys
xs = 3 .* [1, 2, 3, 4, 5]
g = group(x -> (isodd(x),), xs; restype=KeyedArray)
@test @inferred(FlexiGroups._group(x -> (isodd(x),), xs, KeyedArray)) == g
@test g == KeyedArray([[6, 12], [3, 9, 15]], ([false, true],))
g = group(x -> (a=isodd(x),), xs; restype=KeyedArray)
@test @inferred(FlexiGroups._group(x -> (a=isodd(x),), xs, KeyedArray)) == g
@test g == KeyedArray([[6, 12], [3, 9, 15]]; a=[false, true])
gl = groupmap(x -> (a=isodd(x),), length, xs; restype=KeyedArray)
@test @inferred(FlexiGroups._groupmap(x -> (a=isodd(x),), length, xs, KeyedArray)) == gl
@test gl == map(length, g) == KeyedArray([2, 3]; a=[false, true])
gl = groupmap(x -> (a=isodd(x), b=x == 6), length, xs; restype=KeyedArray, default=0)
@test gl == KeyedArray([1 1; 3 0]; a=[false, true], b=[false, true])
@test addmargins(g) == KeyedArray([[6, 12], [3, 9, 15], [6, 12, 3, 9, 15]]; a=[false, true, total])
@test eltype(addmargins(g)) == Vector{Int}
@test addmargins(gl; combine=sum) == KeyedArray([1 1 2; 3 0 3; 4 1 5]; a=[false, true, total], b=[false, true, total])
end
@testitem "iterators" begin
using Dictionaries
xs = (3x for x in [1, 2, 3, 4, 5])
g = @inferred group(isodd, xs)
@test g == dictionary([true => [3, 9, 15], false => [6, 12]])
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
g = @inferred group(Int∘isodd, xs)
@test g[false] == [6, 12]
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
@test (@inferred groupmap(length, xs))[15] == 1
@test_broken (@inferred groupmap(only, xs))
g = @inferred group(Int∘isodd, (3x for x in [1, 2, 3, 4, 5] if false))
@test isempty(g)
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Int}
g = @inferred group(isodd ∘ last, enumerate(3 .* [1, 2, 3, 4, 5]))
@test g[false] == [(2, 6), (4, 12)]
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Tuple{Int, Int}}
g = @inferred group(isodd ∘ last, pairs(3 .* [1, 2, 3, 4, 5]))
@test g[false] == [2 => 6, 4 => 12]
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Pair{Int, Int}}
g = @inferred group(pairs(3 .* [1, 2, 3, 4, 5]))
@test g[1 => 3] == [1 => 3]
@test isconcretetype(eltype(g))
@test valtype(g) <: SubArray{Pair{Int, Int}}
end
@testitem "dicttypes" begin
using Dictionaries
@testset for D in [Dict, Dictionary, UnorderedDictionary, ArrayDictionary, AbstractDict, AbstractDictionary]
@test group(isodd, 3 .* [1, 2, 3, 4, 5]; restype=D)::D |> pairs |> Dict == Dict(false => [6, 12], true => [3, 9, 15])
@test group(isodd, (3x for x in [1, 2, 3, 4, 5]); restype=D)::D |> pairs |> Dict == Dict(false => [6, 12], true => [3, 9, 15])
@test @inferred(FlexiGroups._group(isodd, 3 .* [1, 2, 3, 4, 5], D))::D == group(isodd, 3 .* [1, 2, 3, 4, 5]; restype=D)
@test @inferred(FlexiGroups._group(isodd, (3x for x in [1, 2, 3, 4, 5]), D))::D == group(isodd, (3x for x in [1, 2, 3, 4, 5]); restype=D)
end
end
@testitem "structarray" begin
using Dictionaries
using StructArrays
using FlexiMaps
using Accessors
xs = StructArray(a=3 .* [1, 2, 3, 4, 5])
g = @inferred group(x -> isodd(x.a), xs)
@test g == dictionary([true => [(a=3,), (a=9,), (a=15,)], false => [(a=6,), (a=12,)]])
@test isconcretetype(eltype(g))
@test g[false].a == [6, 12]
g = @inferred groupview(x -> isodd(x.a), xs)
@test g == dictionary([true => [(a=3,), (a=9,), (a=15,)], false => [(a=6,), (a=12,)]])
@test isconcretetype(eltype(g))
@test g[false].a == [6, 12]
xs = StructArray(
a=3 .* [1, 2, 3, 4, 5],
b=Vector{Any}(undef, 5)
)
@test_throws "access to undefined reference" groupmap(x -> isodd(x.a), length, xs)
@test groupmap((@optic isodd(_.a)), length, xs)[true] == 3
@test_throws "access to undefined reference" length(group((@optic isodd(_.a)), xs)[true])
@test groupview((@optic isodd(_.a)), xs)[true].a == [3, 9, 15]
end
@testitem "categoricalarray" begin
using Dictionaries
using StructArrays
using CategoricalArrays
using FlexiGroups.AccessorsExtra
a = CategoricalArray(["a", "a", "b", "c"])
@test group(a[1:3]) == dictionary(["a" => ["a", "a"], "b" => ["b"], "c" => []])
@test group(a[1:0]) == dictionary(["a" => [], "b" => [], "c" => []])
@test groupmap(length, a[1:3]) == dictionary(["a" => 2, "b" => 1, "c" => 0])
@test groupmap(length, a[1:0]) == dictionary(["a" => 0, "b" => 0, "c" => 0])
@test groupmap(length, StructArray((a[1:2],))) == dictionary([("a",) => 2, ("b",) => 0, ("c",) => 0])
@test groupmap(length, StructArray(;a=a[1:2])) == dictionary([(a="a",) => 2, (a="b",) => 0, (a="c",) => 0])
@test groupmap((@o _.a), length, StructArray(;a=a[1:2])) == dictionary(["a" => 2, "b" => 0, "c" => 0])
@test groupmap((@o _.a), length, StructArray(;a=a[1:0])) == dictionary(["a" => 0, "b" => 0, "c" => 0])
@test groupmap(length, StructArray(a=a[1:2], b=a[2:3])) == dictionary([(a="a", b="a") => 1, (a="b", b="a") => 0, (a="c", b="a") => 0, (a="a", b="b") => 1, (a="b", b="b") => 0, (a="c", b="b") => 0, (a="a", b="c") => 0, (a="b", b="c") => 0, (a="c", b="c") => 0])
@test groupmap((@optic₊ (_.a, _.b)), length, StructArray(a=a[1:2], b=a[2:3])) == dictionary([("a", "a") => 1, ("b", "a") => 0, ("c", "a") => 0, ("a", "b") => 1, ("b", "b") => 0, ("c", "b") => 0, ("a", "c") => 0, ("b", "c") => 0, ("c", "c") => 0])
@test groupmap(x -> x.a, length, StructArray(; a)) == dictionary(["a" => 2, "b" => 1, "c" => 1])
@test groupmap(x -> x.a, length, [(; a) for a in a]) == dictionary(["a" => 2, "b" => 1, "c" => 1])
# cannot extract levels for now, but should be possible:
@test groupmap(length, StructArray(;a=a[1:2], b=[1,1])) == dictionary([(a="a", b=1) => 2])
# probably no way to extract levels:
@test groupmap(x -> x.a, length, StructArray(;a=a[1:0])) |> isempty
# why this works?
G = groupmap((@o (_.a, _.b)), length, StructArray(a=a[1:2], b=a[2:3]))
@test length(G) == 9
@test G[("a", "a")] == 1
@test G[("b", "a")] == 0
@test sum(G) == 2
end
@testitem "keyedarray" begin
using Dictionaries
using AxisKeys
xs = KeyedArray(1:5, a=3 .* [1, 2, 3, 4, 5])
g = @inferred group(isodd, xs)
@test g == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
@test_broken axiskeys(g[false]) == ([6, 12],)
@test_broken g[false](a=6) == 2
g = @inferred groupview(isodd, xs)
@test g == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
@test axiskeys(g[false]) == ([6, 12],)
@test g[false](a=6) == 2
end
@testitem "offsetarrays" begin
using Dictionaries
using OffsetArrays
xs = OffsetArray(1:5, 10)
g = @inferred group(isodd, xs)
@test g::AbstractDictionary{Bool, <:AbstractVector{Int}} == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
g = @inferred groupview(isodd, xs)
@test g::AbstractDictionary{Bool, <:AbstractVector{Int}} == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
g = @inferred groupmap(isodd, length, xs)
@test g::AbstractDictionary{Bool, Int} == dictionary([true => 3, false => 2])
end
@testitem "pooledarray" begin
using PooledArrays
using StructArrays
using Dictionaries
xs = PooledArray([i for i in 1:255], UInt8)
@test groupmap(isodd, length, xs) == dictionary([true => 128, false => 127])
sa = StructArray(a=PooledArray(repeat(1:255, outer=100), UInt8), b=1:255*100)
@test all(==(100), groupmap(x -> x.a, length, sa))
@test all(==(1), groupmap(x -> x.b, length, sa))
@test all(==(1), map(length, group(x -> (x.a, x.b), sa)))
end
@testitem "typedtable" begin
using Dictionaries
using TypedTables
xs = Table(a=3 .* [1, 2, 3, 4, 5])
g = @inferred group(x -> isodd(x.a), xs)
@test g == dictionary([true => [(a=3,), (a=9,), (a=15,)], false => [(a=6,), (a=12,)]])
@test isconcretetype(eltype(g))
@test g[false].a == [6, 12]
g = @inferred groupview(x -> isodd(x.a), xs)
@test g == dictionary([true => [(a=3,), (a=9,), (a=15,)], false => [(a=6,), (a=12,)]])
@test isconcretetype(eltype(g))
@test g[false].a == [6, 12]
end
@testitem "dictionary" begin
using Dictionaries
# view(dct, range) doesn't work for dictionaries by default
Base.view(d::AbstractDictionary, inds::AbstractArray) = Dictionaries.ViewArray{valtype(d), ndims(inds)}(d, inds)
xs = dictionary(3 .* [1, 2, 3, 4, 5] .=> 1:5)
g = @inferred group(isodd, xs)
@test g == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
@test g[false] == [2, 4]
g = @inferred groupview(isodd, xs)
@test g == dictionary([true => [1, 3, 5], false => [2, 4]])
@test isconcretetype(eltype(g))
@test g[false] == [2, 4]
xs[6] = 123
@test g == dictionary([true => [1, 3, 5], false => [123, 4]])
end
@testitem "staticarray" begin
using Dictionaries
using StaticArrays
xs = SVector{5}(3 .* [1, 2, 3, 4, 5])
g = @inferred group(isodd, xs)
@test g == dictionary([true => [3, 9, 15], false => [6, 12]])
@test isconcretetype(eltype(g))
@test eltype(g) <: SubArray{Int}
@test g[false] == [6, 12]
end
# @testitem "distributedarray" begin
# using DistributedArrays
# DistributedArrays.allowscalar(true)
# xs = distribute(3 .* [1, 2, 3, 4, 5])
# g = @inferred group(isodd, xs)
# @test g == dictionary([true => [1, 3, 5], false => [2, 4]])
# @test isconcretetype(eltype(g))
# @test g[false] == [2, 4]
# end
@testitem "skipper" begin
using Skipper
using Dictionaries
g = group(isodd, skip(isnothing, [1., 2, nothing, 3]))
@test g == dictionary([true => [1, 3], false => [2]])
@test g isa AbstractDictionary{Bool, <:SubArray{Float64}}
g = group(isodd, skip(isnan, [1, 2, NaN, 3]))
@test g == dictionary([true => [1, 3], false => [2]])
@test g isa AbstractDictionary{Bool, <:SubArray{Float64}}
g = groupfind(isodd, skip(isnan, [1, 2, NaN, 3]))
@test g == dictionary([true => [1, 4], false => [2]])
@test g isa AbstractDictionary{Bool, <:SubArray{Int}}
end
@testitem "_" begin
import Aqua
Aqua.test_all(FlexiGroups; ambiguities=false)
# Aqua.test_ambiguities(FlexiGroups)
import CompatHelperLocal as CHL
CHL.@check()
end
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 0.1.26 | 90ae81797a6f8c631f2a7c129648ef5c76631038 | docs | 6028 | # FlexiGroups.jl
Arrange tabular or non-tabular datasets into groups according to a specified key function.
The main principle of `FlexiGroups` is that the result of a grouping operation is always a collection of groups, and each group is a collection of elements. Groups are typically indexed by the grouping key.
## `group`/`groupview`/`groupmap`
`group([keyf=identity], X; [restype=Dictionary])`: group elements of `X` by `keyf(x)`, returning a mapping `keyf(x)` values to lists of `x` values in each group.
The result is an (ordered) `Dictionary` by default, but can be changed to the base `Dict` or another dictionary type.
Alternatively to dictionaries, specifying `restype=KeyedArray` (from `AxisKeys.jl`) results in a `KeyedArray`. Its `axiskeys` are the group keys.
```julia
xs = 3 .* [1, 2, 3, 4, 5]
g = group(isodd, xs)
# g == dictionary([true => [3, 9, 15], false => [6, 12]]) from Dictionaries.jl
g = group(x -> (a=isodd(x),), xs; restype=KeyedArray)
# g == KeyedArray([[6, 12], [3, 9, 15]]; a=[false, true])
```
`groupview([keyf=identity], X; [restype=Dictionary])`: like the `group` function, but each group is a `view` of `X` and doesn't copy the input elements.
`groupmap([keyf=identity], mapf, X; [restype=Dictionary])`: like `map(mapf, group(keyf, X))`, but more efficient. Supports a limited set of `mapf` functions: `length`, `first`/`last`, `only`, `rand`.
# Margins
`addmargins(dict; [combine=flatten])`: add margins to a grouping for all combinations of group key components.
For example, if a dataset is grouped by `a` and `b` (`keyf=x -> (;x.a, x.b)` in `group`), this adds groups for each `a` value and for each `b` value separately.
`combine` specifies how multiple groups are combined into margins. The default `combine=flatten` concatenates all relevant groups into a single collection.
```julia
xs = [(a=1, b=:x), (a=2, b=:x), (a=2, b=:y), (a=3, b=:x), (a=3, b=:x), (a=3, b=:x)]
# basic grouping by unique combinations of a and b
g = group(xs)
map(length, g) == dictionary([(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3])
# add margins
gm = addmargins(g)
map(length, gm) == dictionary([
(a=1, b=:x) => 1, (a=2, b=:x) => 1, (a=2, b=:y) => 1, (a=3, b=:x) => 3, # original grouping result
(a=1, b=total) => 1, (a=2, b=total) => 2, (a=3, b=total) => 3, # margins for all values of a
(a=total, b=:x) => 5, (a=total, b=:y) => 1, # margins for all values of b
(a=total, b=total) => 6, # total
])
```
# More examples
Compute the fraction of elements in each group:
```julia
julia> using FlexiGroups, DataPipes
julia> x = rand(1:100, 100);
julia> @p x |>
groupmap(_ % 3, length) |> # group by x % 3 and compute length of each group
FlexiGroups.addmargins(combine=sum) |> # append the margin - here, the total of all group lengths
__ ./ __[total] # divide lengths by that total
4-element Dictionaries.Dictionary{Union{Colon, Int64}, Float64}
2 │ 0.34
0 │ 0.33
1 │ 0.33
total │ 1.0
```
Perform per-group computations and combine into a single flat collection:
```julia
julia> using FlexiGroups, FlexiMaps, DataPipes, StructArrays
julia> x = rand(1:100, 10)
10-element Vector{Int64}:
70
57
57
69
61
74
31
39
48
96
# regular flatmap: puts all elements of the first group first, then the second, and so on
# the resulting order is different from the original `x` above
julia> @p x |>
groupview(_ % 3) |>
flatmap(StructArray(x=_, ind_in_group=eachindex(_)))
10-element StructArray(::Vector{Int64}, ::Vector{Int64}) with eltype NamedTuple{(:x, :ind_in_group), Tuple{Int64, Int64}}:
(x = 70, ind_in_group = 1)
(x = 61, ind_in_group = 2)
(x = 31, ind_in_group = 3)
(x = 57, ind_in_group = 1)
(x = 57, ind_in_group = 2)
(x = 69, ind_in_group = 3)
(x = 39, ind_in_group = 4)
(x = 48, ind_in_group = 5)
(x = 96, ind_in_group = 6)
(x = 74, ind_in_group = 1)
# flatmap_parent: puts elements in the same order as they were in the parent `x` array above
julia> @p x |>
groupview(_ % 3) |>
flatmap_parent(StructArray(x=_, ind_in_group=eachindex(_)))
10-element StructArray(::Vector{Int64}, ::Vector{Int64}) with eltype NamedTuple{(:x, :ind_in_group), Tuple{Int64, Int64}}:
(x = 70, ind_in_group = 1)
(x = 57, ind_in_group = 1)
(x = 57, ind_in_group = 2)
(x = 69, ind_in_group = 3)
(x = 61, ind_in_group = 2)
(x = 74, ind_in_group = 1)
(x = 31, ind_in_group = 3)
(x = 39, ind_in_group = 4)
(x = 48, ind_in_group = 5)
(x = 96, ind_in_group = 6)
```
Pivot tables:
```julia
julia> using FlexiGroups, DataPipes, StructArrays, AxisKeys
# generate a simple table
julia> x = @p rand(1:100, 100) |> map((value=_, mod3=_ % 3, mod5=_ % 5)) |> StructArray
100-element StructArray(::Vector{Int64}, ::Vector{Int64}, ::Vector{Int64}) with eltype NamedTuple{(:value, :mod3, :mod5), Tuple{Int64, Int64, Int64}}:
(value = 29, mod3 = 2, mod5 = 4)
(value = 93, mod3 = 0, mod5 = 3)
(value = 1, mod3 = 1, mod5 = 1)
(value = 57, mod3 = 0, mod5 = 2)
(value = 2, mod3 = 2, mod5 = 2)
⋮
# compute sum of `value`s grouped by `mod3` and `mod5`
julia> @p x |>
group((; _.mod3, _.mod5); restype=KeyedArray) |>
map(sum(_.value))
2-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ mod3 ∈ 3-element Vector{Int64}
→ mod5 ∈ 5-element Vector{Int64}
And data, 3×5 Matrix{Int64}:
(0) (1) (2) (3) (4)
(0) 390 372 378 258 225
(1) 480 247 372 187 362
(2) 475 82 352 318 203
```
# Alternatives
- `SplitApplyCombine.jl` also provides `group` and `groupview` functions with similar basic semantics. Notable differences of `FlexiGroups` include:
- margins support;
- more flexibility in the return container type - various dictionaries, keyed arrays;
- group collection type is the same as the input collection type, when possible; for example, grouping a `StructArray`s results in each group also being a `StructArray`;
- better return eltype and type inference;
- often performs faster and with fewer allocations.
| FlexiGroups | https://github.com/JuliaAPlavin/FlexiGroups.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 456 | using Documenter
push!(LOAD_PATH, "../../src")
using GenieAuthentication
makedocs(
sitename = "GenieAuthentication - Authentication plugin for Genie",
format = Documenter.HTML(prettyurls = false),
pages = [
"Home" => "index.md",
"GenieAuthentication API" => [
"GenieAuthentication" => "API/genieauthentication.md",
]
],
)
deploydocs(
repo = "github.com/GenieFramework/GenieAuthentication.jl.git",
)
| GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 329 | module GenieAuthenticationViewHelper
using GenieAuthentication.GenieSession
using GenieAuthentication.GenieSessionFileSession
using GenieAuthentication.GenieSession.Flash
export output_flash
function output_flash() :: String
flash_has_message() ? """<div class="form-group alert alert-info">$(flash())</div>""" : ""
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 1518 | module AuthenticationController
using Genie, Genie.Renderer, Genie.Renderer.Html
using SearchLight
using Logging
using ..Main.UserApp.Users
using ..Main.UserApp.GenieAuthenticationViewHelper
using GenieAuthentication
using GenieAuthentication.GenieSession
using GenieAuthentication.GenieSession.Flash
using GenieAuthentication.GenieSessionFileSession
function show_login()
html(:authentication, :login, context = @__MODULE__)
end
function login()
try
user = findone(User, username = params(:username), password = Users.hash_password(params(:password)))
authenticate(user.id, GenieSession.session(params()))
redirect(:success)
catch ex
flash("Authentication failed! ")
redirect(:show_login)
end
end
function success()
html(:authentication, :success, context = @__MODULE__)
end
function logout()
deauthenticate(GenieSession.session(params()))
flash("Good bye! ")
redirect(:show_login)
end
function show_register()
html(:authentication, :register, context = @__MODULE__)
end
function register()
try
user = User(username = params(:username),
password = params(:password) |> Users.hash_password,
name = params(:name),
email = params(:email)) |> save!
authenticate(user.id, GenieSession.session(params()))
"Registration successful"
catch ex
@error ex
if hasfield(typeof(ex), :msg)
flash(ex.msg)
else
flash(string(ex))
end
redirect(:show_register)
end
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 783 | module Users
using SearchLight, SearchLight.Validation
using ..Main.UserApp.UsersValidator
using GenieAuthentication.SHA
export User
Base.@kwdef mutable struct User <: AbstractModel
### FIELDS
id::DbId = DbId()
username::String = ""
password::String = ""
name::String = ""
email::String = ""
end
Validation.validator(u::Type{User}) = ModelValidator([
ValidationRule(:username, UsersValidator.not_empty),
ValidationRule(:username, UsersValidator.unique),
ValidationRule(:password, UsersValidator.not_empty),
ValidationRule(:email, UsersValidator.not_empty),
ValidationRule(:email, UsersValidator.unique),
ValidationRule(:name, UsersValidator.not_empty)
])
function hash_password(password::AbstractString)
sha256(password) |> bytes2hex
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 650 | module UsersValidator
using SearchLight, SearchLight.Validation, SearchLight.QueryBuilder
function not_empty(field::Symbol, m::T)::ValidationResult where {T<:AbstractModel}
isempty(getfield(m, field)) && return ValidationResult(invalid, :not_empty, "should not be empty")
ValidationResult(valid)
end
function unique(field::Symbol, m::T)::ValidationResult where {T<:AbstractModel}
ispersisted(m) && return ValidationResult(valid) # don't validate updates
if SearchLight.count(typeof(m), where("$field = ?", getfield(m, field))) > 0
return ValidationResult(invalid, :unique, "is already used")
end
ValidationResult(valid)
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 451 | module CreateTableUsers
import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table
function up()
create_table(:users) do
[
primary_key()
column(:username, :string, limit = 100)
column(:password, :string, limit = 100)
column(:name, :string, limit = 100)
column(:email, :string, limit = 100)
]
end
add_index(:users, :username)
end
function down()
drop_table(:users)
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 858 | using Genie
using GenieAuthentication
import ..Main.UserApp.AuthenticationController
import ..Main.UserApp.Users
import SearchLight: findone
export current_user
export current_user_id
current_user() = findone(Users.User, id = get_authentication())
current_user_id() = current_user() === nothing ? nothing : current_user().id
route("/login", AuthenticationController.show_login, named = :show_login)
route("/login", AuthenticationController.login, method = POST, named = :login)
route("/success", AuthenticationController.success, method = GET, named = :success)
route("/logout", AuthenticationController.logout, named = :logout)
#===#
# UNCOMMENT TO ENABLE REGISTRATION ROUTES
# route("/register", AuthenticationController.show_register, named = :show_register)
# route("/register", AuthenticationController.register, method = POST, named = :register) | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | code | 6744 | """
Functionality for authenticating Genie users.
"""
module GenieAuthentication
import Genie, SearchLight
import GenieSession, GenieSessionFileSession
import GeniePlugins
import SHA
using Base64
export authenticate, deauthenticate, is_authenticated, isauthenticated, get_authentication, authenticated
export login, logout, with_authentication, without_authentication, @authenticated!, @with_authentication!, authenticated!
const USER_ID_KEY = :__auth_user_id
const PARAMS_USERNAME_KEY = :username
const PARAMS_PASSWORD_KEY = :password
"""
Stores the user id on the session.
"""
function authenticate(user_id::Any, session::GenieSession.Session) :: GenieSession.Session
GenieSession.set!(session, USER_ID_KEY, user_id)
end
function authenticate(user_id::SearchLight.DbId, session::GenieSession.Session)
authenticate(Int(user_id.value), session)
end
function authenticate(user_id::Union{String,Symbol,Int,SearchLight.DbId}, params::Dict{Symbol,Any} = Genie.Requests.payload()) :: GenieSession.Session
authenticate(user_id, params[:SESSION])
end
"""
deauthenticate(session)
deauthenticate(params::Dict{Symbol,Any})
Removes the user id from the session.
"""
function deauthenticate(session::GenieSession.Session) :: GenieSession.Session
Genie.Router.params!(:SESSION, GenieSession.unset!(session, USER_ID_KEY))
end
function deauthenticate(params::Dict = Genie.Requests.payload()) :: GenieSession.Session
deauthenticate(get(params, :SESSION, nothing))
end
"""
is_authenticated(session) :: Bool
is_authenticated(params::Dict{Symbol,Any}) :: Bool
Returns `true` if a user id is stored on the session.
"""
function is_authenticated(session::Union{GenieSession.Session,Nothing}) :: Bool
GenieSession.isset(session, USER_ID_KEY)
end
function is_authenticated(params::Dict = Genie.Requests.payload()) :: Bool
is_authenticated(get(params, :SESSION, nothing))
end
const authenticated = is_authenticated
const isauthenticated = is_authenticated
"""
@authenticate!(exception::E = ExceptionalResponse(Genie.Renderer.redirect(:show_login)))
If the current request is not authenticated it throws an ExceptionalResponse exception.
"""
macro authenticated!(exception = Genie.Exceptions.ExceptionalResponse(Genie.Renderer.redirect(:show_login)))
:(authenticated!($exception))
end
macro with_authentication!(ex, exception = Genie.Exceptions.ExceptionalResponse(Genie.Renderer.redirect(:show_login)))
quote
if ! GenieAuthentication.authenticated()
throw($exception)
else
esc(ex)
end
end |> esc
end
function authenticated!(exception = Genie.Exceptions.ExceptionalResponse(Genie.Renderer.redirect(:show_login)))
authenticated() || throw(exception)
end
"""
get_authentication(session) :: Union{Nothing,Any}
get_authentication(params::Dict{Symbol,Any}) :: Union{Nothing,Any}
Returns the user id stored on the session, if available.
"""
function get_authentication(session::GenieSession.Session) :: Union{Nothing,Any}
GenieSession.get(session, USER_ID_KEY)
end
function get_authentication(params::Dict = Genie.Requests.payload()) :: Union{Nothing,Any}
haskey(params, :SESSION) ? get_authentication(params[:SESSION]) : nothing
end
const authentication = get_authentication
"""
login(user, session)
login(user, params::Dict{Symbol,Any})
Persists on session the id of the user object and returns the session.
"""
function login(user::M, session::GenieSession.Session)::Union{Nothing,GenieSession.Session} where {M<:SearchLight.AbstractModel}
authenticate(getfield(user, Symbol(pk(user))), session)
end
function login(user::M, params::Dict = Genie.Requests.payload())::Union{Nothing,GenieSession.Session} where {M<:SearchLight.AbstractModel}
login(user, params[:SESSION])
end
"""
logout(session) :: Sessions.Session
logout(params::Dict{Symbol,Any}) :: Sessions.Session
Deletes the id of the user object from the session, effectively logging the user off.
"""
function logout(session::GenieSession.Session) :: GenieSession.Session
deauthenticate(session)
end
function logout(params::Dict = Genie.Requests.payload()) :: GenieSession.Session
logout(params[:SESSION])
end
"""
with_authentication(f::Function, fallback::Function, session)
with_authentication(f::Function, fallback::Function, params::Dict{Symbol,Any})
Invokes `f` only if a user is currently authenticated on the session, `fallback` is invoked otherwise.
"""
function with_authentication(f::Function, fallback::Function, session::Union{GenieSession.Session,Nothing})
if ! is_authenticated(session)
fallback()
else
f()
end
end
function with_authentication(f::Function, fallback::Function, params::Dict = Genie.Requests.payload())
with_authentication(f, fallback, params[:SESSION])
end
"""
without_authentication(f::Function, session)
without_authentication(f::Function, params::Dict{Symbol,Any})
Invokes `f` if there is no user authenticated on the current session.
"""
function without_authentication(f::Function, session::GenieSession.Session)
! is_authenticated(session) && f()
end
function without_authentication(f::Function, params::Dict = Genie.Requests.payload())
without_authentication(f, params[:SESSION])
end
"""
install(dest::String; force = false, debug = false) :: Nothing
Copies the plugin's files into the host Genie application.
"""
function install(dest::String; force = false, debug = false) :: Nothing
src = abspath(normpath(joinpath(pathof(@__MODULE__) |> dirname, "..", GeniePlugins.FILES_FOLDER)))
debug && @info "Preparing to install from $src into $dest"
debug && @info "Found these to install $(readdir(src))"
for f in readdir(src)
debug && @info "Processing $(joinpath(src, f))"
debug && @info "$(isdir(joinpath(src, f)))"
isdir(joinpath(src, f)) || continue
debug && "Installing from $(joinpath(src, f))"
GeniePlugins.install(joinpath(src, f), dest, force = force)
end
nothing
end
function basicauthparams(req, res, params)
headers = Dict(req.headers)
if haskey(headers, "Authorization")
auth = headers["Authorization"]
if startswith(auth, "Basic ")
try
auth = String(base64decode(auth[7:end]))
auth = split(auth, ":")
params[PARAMS_USERNAME_KEY] = auth[1]
params[PARAMS_PASSWORD_KEY] = auth[2]
catch _
end
end
end
req, res, params
end
function isbasicauthrequest(params::Dict = Genie.Requests.payload()) :: Bool
haskey(params, PARAMS_USERNAME_KEY) && haskey(params, PARAMS_PASSWORD_KEY)
end
function __init__() :: Nothing
GenieAuthentication.basicauthparams in Genie.Router.pre_match_hooks || pushfirst!(Genie.Router.pre_match_hooks, GenieAuthentication.basicauthparams)
nothing
end
end | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | docs | 157 | # CHANGELOG
## v0.2.1 - 2019-08-30
* fixed an issue with the `UserValidator` to not invalidate if the `User` is persisted (indicating an update operation)
| GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | docs | 5600 | # GenieAuthentication
Authentication plugin for `Genie.jl`
## Installation
The `GenieAuthentication.jl` package is an authentication plugin for `Genie.jl`, the highly productive Julia web framework.
As such, it requires installation within the environment of a `Genie.jl` MVC application, allowing the plugin to install its files (which include models, controllers, database migrations, plugins, and other files).
### Load your `Genie.jl` app
First load the `Genie.jl` application, for example using
```bash
$> cd /path/to/your/genie_app
$> ./bin/repl
```
Alternatively, you can create a new `Genie.jl` MVC application (`SearchLight.jl` ORM support is required in order to store the user accounts into the database). If you are not sure how to do that, please follow the documentation for `Genie.jl`, for example at <https://genieframework.com/docs/Genie/v5/tutorials/4-1--Developing_MVC_Web_Apps.html>.
### Add the plugin
Next, add the plugin:
```julia
julia> ]
(MyGenieApp) pkg> add GenieAuthentication
```
Once added, we can use its `install` function to add its files to the `Genie.jl` app (required only upon installation):
```julia
julia> using GenieAuthentication
julia> GenieAuthentication.install(@__DIR__)
```
The above command will set up the plugin's files within your `Genie.jl` app (will create various files including new views, controllers, models, migrations, initializers, etc).
## Usage
The main plugin file should now be found in the `plugins/` folder within your `Genie.jl` app. It sets up configuration and registers routes.
---
**HEADS UP**
Make sure to uncomment out the `/register` routes in `plugins/genie_authentication.jl` if you want to provide user registration features.
They are disabled by default in order to eliminate the risk of accidentally allowing random users to create accounts and expose your application.
---
### Set up the database
The plugin needs DB support to store user data. You will find a `*_create_table_users.jl` migration file within the `db/migrations/` folder. We need to run it:
```julia
julia> using SearchLight
julia> SearchLight.Migration.up("CreateTableUsers")
```
This will create the necessary table.
---
**HEADS UP**
If your app wasn't already set up to work with `SearchLight.jl`, you need to add `SearchLight.jl` support first.
Please check the `Genie.jl` documentation on how to do that, for example at <https://genieframework.com/docs/Genie/v5/tutorials/4-1--Developing_MVC_Web_Apps.html#Connecting-to-the-database>. This includes setting up a `db/connection.yml` and an empty migration table with `create_migrations_table` if it has not already been done.
---
### Set up the successful login route
Upon a successful login, the plugin will redirect the user to the `:success` route, which invokes `AuthenticationController.success`.
---
### Enforcing authentication
Now that we have a functional authentication system, there are two ways of enforcing authentication.
#### `authenticated!()`
The `authenticated!()` function will enforce authentication - meaning that it will check if a user is authenticated, and if not, it will automatically throw an `ExceptionalResponse` and force a redirect to the `:show_login` route which displays the login form.
We can use this anywhere in our route handling code, for example within routes:
```julia
# routes.jl
using GenieAuthentication
route("/protected") do; authenticated!()
# this code is only accessible for authenticated users
end
```
Or within handler functions inside controllers:
```julia
# routes.jl
route("/protected", ProtectedController.secret)
```
```julia
# ProtectedController.jl
using GenieAuthentication
function secret()
authenticated!()
# this code is only accessible for authenticated users
end
```
---
**HEADS UP**
If you're throwing an `ExceptionalResponse` as the result of the failed authentication, make sure to also be `using Genie.Exceptions`.
---
#### `authenticated()`
In addition to the imperative style of the `authenticated!()` function, we can also use the `authenticated()` function (no `!` at the end) which returns a `bool` indicated if a user is currently authenticated.
It is especially used for adding dynamic UI elements based on the state of the authentication:
```html
<div class="row align-items-center">
<div class="col col-12 text-center">
<% if ! authenticated() %>
<a href="/login" class="btn btn-light btn-lg" style="color: #fff;">Login</a>
<% end %>
</div>
</div>
```
We can also use it to mimic the behaviour of `authenticated!()`:
```julia
using Genie.Exceptions
using GenieAuthentication
# This function _can not_ be accessed without authentication
function index()
authenticated() || throw(ExceptionalResponse(redirect(:show_login)))
h1("Welcome Admin") |> html
end
```
Or to perform custom actions:
```julia
using GenieAuthentication
route("/you/shant/pass") do
authenticated() || return "Can't touch this!"
"You're welcome!"
end
```
---
### Adding a user
You can create a user at the REPL like this (using stronger usernames and passwords though 🙈):
```julia
julia> using Users
julia> u = User(email = "admin@admin", name = "Admin", password = Users.hash_password("admin"), username = "admin")
julia> save!(u)
```
---
### Get current user information
If the user was authenticated, check first with `authenticated()`, you can obtain the current user information with `current_user()`.
```julia
using GenieAuthentication
route("/your/email") do
authenticated() || return "Can't get it!"
user = current_user()
user.email
end
```
| GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | docs | 57 | # GenieAuthentication
Authentication plugin for Genie.jl | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 2.2.0 | 760079658e6284a1462c4232d965f0f77e7e3cf8 | docs | 98 | ```@meta
CurrentModule = GenieAuthentication
```
```@autodocs
Modules = [GenieAuthentication]
``` | GenieAuthentication | https://github.com/GenieFramework/GenieAuthentication.jl.git |
|
[
"MIT"
] | 1.1.0 | 77d62b670398cb9e9600d1250dd9386e52520082 | code | 6853 | module ExpiringCaches
using Dates
export Cache, @cacheable
struct TimestampedValue{T}
value::T
timestamp::DateTime
end
TimestampedValue(x::T) where {T} = TimestampedValue{T}(x, Dates.now(Dates.UTC))
TimestampedValue{T}(x) where {T} = TimestampedValue{T}(x, Dates.now(Dates.UTC))
timestamp(x::TimestampedValue) = x.timestamp
"""
ExpiringCaches.Cache{K, V}(timeout::Dates.Period; purge_on_timeout::Bool=false)
Create a thread-safe, expiring cache where values older than `timeout`
are "invalid" and will be deleted.
An `ExpiringCaches.Cache` is an `AbstractDict` and tries to emulate a regular
`Dict` in all respects. It is most useful when the cost of retrieving or
calculating a value is expensive and is able to be "cached" for a certain
amount of time. To avoid using the cache (i.e. to invalidate the cache),
a `Cache` supports the `delete!` and `empty!` methods to remove values
manually.
By default, expired keys will remain in the cache until requested (via
`haskey` or `get`); if `purge_on_timeout=true` keyword argument is passed,
then an async task will be spawned for each key upon entry. When the
timeout task has waited `timeout` length of time, the key will be removed
from the cache.
"""
struct Cache{K, V, P <: Dates.Period} <: AbstractDict{K, V}
lock::ReentrantLock
cache::Dict{K, TimestampedValue{V}}
timeout::P
purge_on_timeout::Bool
end
Cache{K, V}(timeout::Dates.Period=Dates.Minute(1); purge_on_timeout::Bool=false) where {K, V} = Cache(ReentrantLock(), Dict{K, TimestampedValue{V}}(), timeout, purge_on_timeout)
expired(x::TimestampedValue, timeout) = (Dates.now(Dates.UTC) - x.timestamp) > timeout
function Base.iterate(x::Cache)
lock(x.lock)
state = iterate(x.cache)
if state === nothing
unlock(x.lock)
return nothing
end
while expired(state[1][2], x.timeout)
state = iterate(x.cache, state[2])
if state === nothing
unlock(x.lock)
return nothing
end
end
return (state[1][1], state[1][2].value), state[2]
end
function Base.iterate(x::Cache, st)
state = iterate(x.cache, st)
if state === nothing
unlock(x.lock)
return nothing
end
while expired(state[1][2], x.timeout)
state = iterate(x.cache, state[2])
if state === nothing
unlock(x.lock)
return nothing
end
end
return (state[1][1], state[1][2].value), state[2]
end
function Base.haskey(cache::Cache{K, V}, k::K) where {K, V}
lock(cache.lock) do
if haskey(cache.cache, k)
x = cache.cache[k]
if !expired(x, cache.timeout)
return true
else
delete!(cache.cache, k)
return false
end
end
return false
end
end
function Base.setindex!(cache::Cache{K, V}, val::V, key::K) where {K, V}
lock(cache.lock) do
val1 = TimestampedValue{V}(val)
cache.cache[key] = val1
ts = timestamp(val1)
if cache.purge_on_timeout
Timer(div(Dates.toms(cache.timeout), 1000)) do _
lock(cache.lock) do
val2 = get(cache.cache, key, nothing)
# only delete if timestamp of original key matches
if val2 !== nothing && timestamp(val2) == ts
delete!(cache.cache, key)
end
end
end
end
return val
end
end
function Base.get(cache::Cache{K, V}, key::K, default::V) where {K, V}
lock(cache.lock) do
if haskey(cache.cache, key)
x = cache.cache[key]
if expired(x, cache.timeout)
delete!(cache.cache, key)
return default
else
return x.value
end
else
return default
end
end
end
function Base.get!(cache::Cache{K, V}, key::K, default::V) where {K, V}
lock(cache.lock) do
if haskey(cache.cache, key)
x = cache.cache[key]
if expired(x, cache.timeout)
return setindex!(cache, default, key)
else
return x.value
end
else
return setindex!(cache, default, key)
end
end
end
function Base.get!(f::Function, cache::Cache{K, V}, key::K) where {K, V}
lock(cache.lock) do
if haskey(cache.cache, key)
x = cache.cache[key]
if expired(x, cache.timeout)
return setindex!(cache, f()::V, key)
else
return x.value
end
else
return setindex!(cache, f()::V, key)
end
end
end
Base.delete!(cache::Cache{K}, key::K) where {K} = lock(() -> delete!(cache.cache, key), cache.lock)
Base.empty!(cache::Cache) = lock(() -> empty!(cache.cache), cache.lock)
Base.length(cache::Cache) = length(cache.cache)
"""
@cacheable timeout function_definition::ReturnType
For a function definition (`function_definition`, either short-form
or full), create an `ExpiringCaches.Cache` and store results for `timeout`
(hashed by the exact input arguments obviously).
Note that the function definition _MUST_ include the `ReturnType` declartion
as this is used as the value (`V`) type in the `Cache`.
"""
macro cacheable(timeout, func)
@assert func.head == :function
func.args[1].head == :(::) || throw(ArgumentError("@cacheable function must specify return type: $func"))
returnType = func.args[1].args[2]
sig = func.args[1].args[1]
functionBody = func.args[2]
funcName = sig.args[1]
internalFuncName = Symbol("__$funcName")
sig.args[1] = internalFuncName
funcArgs = sig.args[2:end]
argTypes = map(x->x.args[2], funcArgs)
internalFunction = Expr(:function, sig, functionBody)
cacheName = gensym()
return esc(quote
const $cacheName = ExpiringCaches.Cache{Tuple{$(argTypes...)}, $returnType}($timeout)
$internalFunction
Base.@__doc__ function $funcName($(funcArgs...))::$returnType
return get!($cacheName, tuple($(funcArgs...))) do
$internalFuncName($(funcArgs...))
end
end
ExpiringCaches.getcache(f::typeof($funcName)) = $cacheName
$funcName
end)
end
function getcache end
# @cacheable Dates.Minute(2) function foo(arg1::Int, arg2::String)::ReturnType
# x = x + 1
# y = y * 2
# return foobar
# end
# @cacheable Dates.Minute(2) foo(arg1::Int, arg2::Int)::String = # ...
# const CACHE_foo_Int_String = Cache{Tuple{Int, String}, ReturnType}(timeout)
# function foo(args...)::ReturnType
# return get!(CACHE_foo_Int_String, args) do
# _foo(args...)
# end
# end
# function _foo(arg1::Int, arg2::String)::ReturnType
# # ...
# end
end # module | ExpiringCaches | https://github.com/JuliaServices/ExpiringCaches.jl.git |
|
[
"MIT"
] | 1.1.0 | 77d62b670398cb9e9600d1250dd9386e52520082 | code | 1275 | using Test, Dates, ExpiringCaches
"""
foo(arg1::Int, arg2::String)
Some docs to check that it doesn't break.
"""
ExpiringCaches.@cacheable Dates.Second(3) function foo(arg1::Int, arg2::String)::Float64
sleep(2)
return arg1 / length(arg2)
end
@testset "ExpiringCaches" begin
cache = ExpiringCaches.Cache{Int, Int}(Dates.Second(5))
@test length(cache) == 0
@test isempty(cache)
@test get(cache, 1, 2) == 2
@test isempty(cache)
@test get!(cache, 1, 2) == 2
@test !isempty(cache)
for (k, v) in cache
@test v == 2
end
sleep(5)
# test that key isn't used after it expires
@test get(cache, 1, 3) == 3
@test get!(()->4, cache, 1) == 4
@test isempty(delete!(cache, 1))
cache[1] = 5
@test !isempty(cache)
@test isempty(empty!(cache))
@test foo(1, "ffff") == 0.25
tm = @elapsed foo(1, "ffff")
@test tm < 2 # test that normal function body wasn't executed
sleep(3)
tm = @elapsed foo(1, "ffff")
@test tm > 2 # test that normal function body was executed
cache = ExpiringCaches.Cache{Int, Int}(Dates.Second(5); purge_on_timeout=true)
cache[1] = 2
@test !isempty(cache)
sleep(3)
cache[1] = 3
sleep(2.5)
# key isn't purged because we replaced it, so timer is "reset"
@test !isempty(cache)
sleep(3)
# key is now purged w/o being accessed
@test isempty(cache)
end | ExpiringCaches | https://github.com/JuliaServices/ExpiringCaches.jl.git |
|
[
"MIT"
] | 1.1.0 | 77d62b670398cb9e9600d1250dd9386e52520082 | docs | 1305 |
# ExpiringCaches.jl
*A Dict type with expiring values and a `@cacheable` macro to cache function results in an expiring cache*
## Installation
The package is registered in the [`General`](https://github.com/JuliaRegistries/General) registry and so can be installed at the REPL with `] add ExpiringCaches`.
## Usage
### `Cache`
ExpiringCaches.Cache{K, V}(timeout::Dates.Period; purge_on_timeout::Bool=false)
Create a thread-safe, expiring cache where values older than `timeout`
are "invalid" and will be deleted.
An `ExpiringCaches.Cache` is an `AbstractDict` and tries to emulate a regular
`Dict` in all respects. It is most useful when the cost of retrieving or
calculating a value is expensive and is able to be "cached" for a certain
amount of time. To avoid using the cache (i.e. to invalidate the cache),
a `Cache` supports the `delete!` and `empty!` methods to remove values
manually.
### `@cacheable`
@cacheable timeout function_definition::ReturnType
For a function definition (`function_definition`, either short-form
or full), create an `ExpiringCaches.Cache` and store results for `timeout`
(hashed by the exact input arguments obviously).
Note that the function definition _MUST_ include the `ReturnType` declartion
as this is used as the value (`V`) type in the `Cache`. | ExpiringCaches | https://github.com/JuliaServices/ExpiringCaches.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 397 | using JuliaFormatter
# we asume the format_all.jl script is located in .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)
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1266 | using Pkg
project_path = Base.Filesystem.joinpath(Base.Filesystem.dirname(Base.source_path()), "..")
Pkg.develop(; path=project_path)
using Documenter
using ComputableDAGs
pages = [
"index.md",
"Manual" => "manual.md",
"Library" => [
"Public" => "lib/public.md",
"Graph" => "lib/internals/graph.md",
"Node" => "lib/internals/node.md",
"Task" => "lib/internals/task.md",
"Operation" => "lib/internals/operation.md",
"Models" => "lib/internals/models.md",
"Diff" => "lib/internals/diff.md",
"Utility" => "lib/internals/utility.md",
"Code Generation" => "lib/internals/code_gen.md",
"Devices" => "lib/internals/devices.md",
],
"Contribution" => "contribution.md",
]
makedocs(;
modules=[ComputableDAGs],
checkdocs=:exports,
authors="Anton Reinhard",
repo=Documenter.Remotes.GitHub("ComputableDAGs", "ComputableDAGs.jl"),
sitename="ComputableDAGs.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://ComputableDAGs.github.io/ComputableDAGs.jl",
assets=String[],
),
pages=pages,
)
deploydocs(; repo="github.com/ComputableDAGs/ComputableDAGs.jl.git", push_preview=false)
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 373 | module AMDGPUExt
using ComputableDAGs
using UUIDs
using AMDGPU
function __init__()
@debug "Loading AMDGPUExt"
push!(ComputableDAGs.DEVICE_TYPES, ROCmGPU)
ComputableDAGs.CACHE_STRATEGIES[ROCmGPU] = [LocalVariables()]
return nothing
end
# include specialized AMDGPU functions here
include("devices/rocm/impl.jl")
include("devices/rocm/function.jl")
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 365 | module CUDAExt
using ComputableDAGs
using UUIDs
using CUDA
function __init__()
@debug "Loading CUDAExt"
push!(ComputableDAGs.DEVICE_TYPES, CUDAGPU)
ComputableDAGs.CACHE_STRATEGIES[CUDAGPU] = [LocalVariables()]
return nothing
end
# include specialized CUDA functions here
include("devices/cuda/impl.jl")
include("devices/cuda/function.jl")
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 343 | module oneAPIExt
using ComputableDAGs
using UUIDs
using oneAPI
function __init__()
@debug "Loading oneAPIExt"
push!(ComputableDAGs.DEVICE_TYPES, oneAPIGPU)
ComputableDAGs.CACHE_STRATEGIES[oneAPIGPU] = [LocalVariables()]
return nothing
end
# include specialized oneAPI functions here
include("devices/oneapi/impl.jl")
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1126 | function ComputableDAGs.kernel(
::Type{CUDAGPU}, graph::DAG, instance, context_module::Module
)
machine = cpu_st()
tape = ComputableDAGs.gen_tape(graph, instance, machine, context_module)
init_caches = Expr(:block, tape.initCachesCode...)
assign_inputs = Expr(:block, ComputableDAGs.expr_from_fc.(tape.inputAssignCode)...)
code = Expr(:block, ComputableDAGs.expr_from_fc.(tape.computeCode)...)
function_id = ComputableDAGs.to_var_name(UUIDs.uuid1(ComputableDAGs.rng[1]))
res_sym = eval(
ComputableDAGs.gen_access_expr(
ComputableDAGs.entry_device(tape.machine), tape.outputSymbol
),
)
expr = Meta.parse(
"function compute_$(function_id)(input_vector, output_vector, n::Int64)
id = (blockIdx().x - 1) * blockDim().x + threadIdx().x
if (id > n)
return
end
@inline data_input = input_vector[id]
$(init_caches)
$(assign_inputs)
$code
@inline output_vector[id] = $res_sym
return nothing
end"
)
return expr
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 925 | ComputableDAGs.default_strategy(::Type{CUDAGPU}) = LocalVariables()
function ComputableDAGs.measure_device!(device::CUDAGPU; verbose::Bool)
verbose && @info "Measuring CUDA GPU $(device.device)"
# TODO implement
return nothing
end
"""
get_devices(::Type{CUDAGPU}; verbose::Bool)
Return a Vector of [`CUDAGPU`](@ref)s available on the current machine. If `verbose` is true, print some additional information.
"""
function ComputableDAGs.get_devices(::Type{CUDAGPU}; verbose::Bool=false)
devices = Vector{ComputableDAGs.AbstractDevice}()
if !CUDA.functional()
@warn "The CUDA extension is loaded but CUDA.jl is non-functional"
return devices
end
CUDADevices = CUDA.devices()
verbose && @info "Found $(length(CUDADevices)) CUDA devices"
for device in CUDADevices
push!(devices, CUDAGPU(device, default_strategy(CUDAGPU), -1))
end
return devices
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 965 | ComputableDAGs.default_strategy(::Type{oneAPIGPU}) = LocalVariables()
function ComputableDAGs.measure_device!(device::oneAPIGPU; verbose::Bool)
verbose && @info "Measuring oneAPI GPU $(device.device)"
# TODO implement
return nothing
end
"""
get_devices(::Type{oneAPIGPU}; verbose::Bool = false)
Return a Vector of [`oneAPIGPU`](@ref)s available on the current machine. If `verbose` is true, print some additional information.
"""
function ComputableDAGs.get_devices(::Type{oneAPIGPU}; verbose::Bool=false)
devices = Vector{ComputableDAGs.AbstractDevice}()
if !oneAPI.functional()
@warn "the oneAPI extension is loaded but oneAPI.jl is non-functional"
return devices
end
oneAPIDevices = oneAPI.devices()
verbose && @info "Found $(length(oneAPIDevices)) oneAPI devices"
for device in oneAPIDevices
push!(devices, oneAPIGPU(device, default_strategy(oneAPIGPU), -1))
end
return devices
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1137 | function ComputableDAGs.kernel(
::Type{ROCmGPU}, graph::DAG, instance, context_module::Module
)
machine = cpu_st()
tape = ComputableDAGs.gen_tape(graph, instance, machine, context_module)
init_caches = Expr(:block, tape.initCachesCode...)
assign_inputs = Expr(:block, ComputableDAGs.expr_from_fc.(tape.inputAssignCode)...)
code = Expr(:block, ComputableDAGs.expr_from_fc.(tape.computeCode)...)
function_id = ComputableDAGs.to_var_name(UUIDs.uuid1(ComputableDAGs.rng[1]))
res_sym = eval(
ComputableDAGs.gen_access_expr(
ComputableDAGs.entry_device(tape.machine), tape.outputSymbol
),
)
expr = Meta.parse(
"function compute_$(function_id)(input_vector, output_vector, n::Int64)
id = (workgroupIdx().x - 1) * workgroupDim().x + workgroupIdx().x
if (id > n)
return
end
@inline data_input = input_vector[id]
$(init_caches)
$(assign_inputs)
$code
@inline output_vector[id] = $res_sym
return nothing
end"
)
return expr
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 937 | ComputableDAGs.default_strategy(::Type{ROCmGPU}) = LocalVariables()
function ComputableDAGs.measure_device!(device::ROCmGPU; verbose::Bool)
verbose && @info "Measuring ROCm GPU $(device.device)"
# TODO implement
return nothing
end
"""
get_devices(::Type{ROCmGPU}; verbose::Bool = false)
Return a Vector of [`ROCmGPU`](@ref)s available on the current machine. If `verbose` is true, print some additional information.
"""
function ComputableDAGs.get_devices(::Type{ROCmGPU}; verbose::Bool=false)
devices = Vector{ComputableDAGs.AbstractDevice}()
if !AMDGPU.functional()
@warn "The AMDGPU extension is loaded but AMDGPU.jl is non-functional"
return devices
end
AMDDevices = AMDGPU.devices()
verbose && @info "Found $(length(AMDDevices)) AMD devices"
for device in AMDDevices
push!(devices, ROCmGPU(device, default_strategy(ROCmGPU), -1))
end
return devices
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 3281 | """
ComputableDAGs
A module containing tools to represent computations as DAGs.
"""
module ComputableDAGs
using RuntimeGeneratedFunctions
RuntimeGeneratedFunctions.init(@__MODULE__)
# graph types
export DAG, Node, Edge
export ComputeTaskNode, DataTaskNode
export AbstractTask, AbstractComputeTask, AbstractDataTask
export DataTask
export PossibleOperations
export GraphProperties
# graph functions
export make_node, make_edge
export insert_node!, insert_edge!
export is_entry_node, is_exit_node
export parents, children, partners, siblings
export compute, data, compute_effort, task
export get_properties, get_exit_node
export operation_stack_length
export is_valid, is_scheduled
# graph operation related
export Operation, AppliedOperation
export NodeReduction, NodeSplit
export push_operation!, pop_operation!, can_pop
export reset_graph!
export get_operations
# code generation related
export execute
export get_compute_function
export gen_tape, execute_tape
export unpack_identity
# estimator
export cost_type, graph_cost, operation_effect
export GlobalMetricEstimator, CDCost
# optimization
export AbstractOptimizer, GreedyOptimizer, RandomWalkOptimizer
export ReductionOptimizer, SplitOptimizer
export optimize_step!, optimize!
export fixpoint_reached, optimize_to_fixpoint!
# models
export AbstractModel, AbstractProblemInstance
export problem_instance, input_type, graph, input_expr
# machine info
export Machine
export NumaNode
export get_machine_info, cpu_st
export CacheStrategy, default_strategy
export LocalVariables, Dictionary
# GPU Extensions
export kernel, CUDAGPU, ROCmGPU, oneAPIGPU
include("devices/interface.jl")
include("task/type.jl")
include("node/type.jl")
include("diff/type.jl")
include("properties/type.jl")
include("operation/type.jl")
include("graph/type.jl")
include("scheduler/type.jl")
include("trie.jl")
include("utils.jl")
include("diff/print.jl")
include("diff/properties.jl")
include("graph/compare.jl")
include("graph/interface.jl")
include("graph/mute.jl")
include("graph/print.jl")
include("graph/properties.jl")
include("graph/validate.jl")
include("node/compare.jl")
include("node/create.jl")
include("node/print.jl")
include("node/properties.jl")
include("node/validate.jl")
include("operation/utility.jl")
include("operation/iterate.jl")
include("operation/apply.jl")
include("operation/clean.jl")
include("operation/find.jl")
include("operation/get.jl")
include("operation/print.jl")
include("operation/validate.jl")
include("properties/create.jl")
include("properties/utility.jl")
include("task/create.jl")
include("task/compare.jl")
include("task/compute.jl")
include("task/properties.jl")
include("estimator/interface.jl")
include("estimator/global_metric.jl")
include("optimization/interface.jl")
include("optimization/greedy.jl")
include("optimization/random_walk.jl")
include("optimization/reduce.jl")
include("optimization/split.jl")
include("models/interface.jl")
include("devices/measure.jl")
include("devices/detect.jl")
include("devices/impl.jl")
include("devices/numa/impl.jl")
include("devices/ext.jl")
include("scheduler/interface.jl")
include("scheduler/greedy.jl")
include("code_gen/type.jl")
include("code_gen/tape_machine.jl")
include("code_gen/function.jl")
end # module ComputableDAGs
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 4040 | """
NodeIdTrie
Helper struct for [`NodeTrie`](@ref). After the Trie's first level, every Trie level contains the vector of nodes that had children up to that level, and the TrieNode's children by UUID of the node's children.
"""
mutable struct NodeIdTrie{NodeType<:Node}
value::Vector{NodeType}
children::Dict{UUID,NodeIdTrie{NodeType}}
end
"""
NodeTrie
Trie data structure for node reduction, inserts nodes by children.
Assumes that given nodes have ordered vectors of children (see [`sort_node!`](@ref)).
First insertion level is the node's own task type and thus does not have a value (every node has a task type).
See also: [`insert!`](@ref) and [`collect`](@ref)
"""
mutable struct NodeTrie
children::Dict{DataType,NodeIdTrie}
end
"""
NodeTrie()
Constructor for an empty [`NodeTrie`](@ref).
"""
function NodeTrie()
return NodeTrie(Dict{DataType,NodeIdTrie}())
end
"""
NodeIdTrie()
Constructor for an empty [`NodeIdTrie`](@ref).
"""
function NodeIdTrie{NodeType}() where {NodeType<:Node}
return NodeIdTrie(Vector{NodeType}(), Dict{UUID,NodeIdTrie{NodeType}}())
end
"""
insert_helper!(trie::NodeIdTrie, node::Node, depth::Int)
Insert the given node into the trie. The depth is used to iterate through the trie layers, while the function calls itself recursively until it ran through all children of the node.
"""
function insert_helper!(
trie::NodeIdTrie{NodeType}, node::NodeType, depth::Int
) where {TaskType<:AbstractDataTask,NodeType<:DataTaskNode{TaskType}}
if (length(children(node)) == depth)
push!(trie.value, node)
return nothing
end
depth = depth + 1
id = node.children[depth][1].id
if (!haskey(trie.children, id))
trie.children[id] = NodeIdTrie{NodeType}()
end
return insert_helper!(trie.children[id], node, depth)
end
# TODO: Remove this workaround once https://github.com/JuliaLang/julia/issues/54404 is fixed in julia 1.10+
function insert_helper!(
trie::NodeIdTrie{NodeType}, node::NodeType, depth::Int
) where {TaskType<:AbstractComputeTask,NodeType<:ComputeTaskNode{TaskType}}
if (length(children(node)) == depth)
push!(trie.value, node)
return nothing
end
depth = depth + 1
id = node.children[depth][1].id
if (!haskey(trie.children, id))
trie.children[id] = NodeIdTrie{NodeType}()
end
return insert_helper!(trie.children[id], node, depth)
end
"""
insert!(trie::NodeTrie, node::Node)
Insert the given node into the trie. It's sorted by its type in the first layer, then by its children in the following layers.
"""
function Base.insert!(
trie::NodeTrie, node::NodeType
) where {TaskType<:AbstractDataTask,NodeType<:DataTaskNode{TaskType}}
if (!haskey(trie.children, NodeType))
trie.children[NodeType] = NodeIdTrie{NodeType}()
end
return insert_helper!(trie.children[NodeType], node, 0)
end
# TODO: Remove this workaround once https://github.com/JuliaLang/julia/issues/54404 is fixed in julia 1.10+
function Base.insert!(
trie::NodeTrie, node::NodeType
) where {TaskType<:AbstractComputeTask,NodeType<:ComputeTaskNode{TaskType}}
if (!haskey(trie.children, NodeType))
trie.children[NodeType] = NodeIdTrie{NodeType}()
end
return insert_helper!(trie.children[NodeType], node, 0)
end
"""
collect_helper(trie::NodeIdTrie, acc::Set{Vector{Node}})
Collects the Vectors of this [`NodeIdTrie`](@ref) node and all its children and puts them in the `acc` argument.
"""
function collect_helper(trie::NodeIdTrie, acc::Set{Vector{Node}})
if (length(trie.value) >= 2)
push!(acc, trie.value)
end
for (id, child) in trie.children
collect_helper(child, acc)
end
return nothing
end
"""
collect(trie::NodeTrie)
Return all sets of at least 2 [`Node`](@ref)s that have accumulated in leaves of the trie.
"""
function Base.collect(trie::NodeTrie)
acc = Set{Vector{Node}}()
for (t, child) in trie.children
collect_helper(child, acc)
end
return acc
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 3519 | """
noop()
Function with no arguments, returns nothing, does nothing. Useful for noop [`FunctionCall`](@ref)s.
"""
@inline noop() = nothing
"""
unpack_identity(x::SVector)
Function taking an `SVector`, returning it unpacked.
"""
@inline unpack_identity(x::SVector{1,<:Any}) = x[1]
@inline unpack_identity(x) = x
"""
bytes_to_human_readable(bytes)
Return a human readable string representation of the given number.
```jldoctest
julia> using ComputableDAGs
julia> ComputableDAGs.bytes_to_human_readable(4096)
"4.0 KiB"
```
"""
function bytes_to_human_readable(bytes)
units = ["B", "KiB", "MiB", "GiB", "TiB"]
unit_index = 1
while bytes >= 1024 && unit_index < length(units)
bytes /= 1024
unit_index += 1
end
return string(round(bytes; sigdigits=4), " ", units[unit_index])
end
"""
_lt_nodes(n1::Node, n2::Node)
Less-Than comparison between nodes. Uses the nodes' ids to sort.
"""
function _lt_nodes(n1::Node, n2::Node)
return n1.id < n2.id
end
"""
_lt_node_tuples(n1::Tuple{Node, Int}, n2::Tuple{Node, Int})
Less-Than comparison between nodes with indices.
"""
function _lt_node_tuples(n1::Tuple{Node,Int}, n2::Tuple{Node,Int})
if n1[2] == n2[2]
return n1[1].id < n2[1].id
else
return n1[2] < n2[2]
end
end
"""
sort_node!(node::Node)
Sort the nodes' parents and children vectors. The vectors are mostly very short so sorting does not take a lot of time.
Sorted nodes are required to make the finding of [`NodeReduction`](@ref)s a lot faster using the [`NodeTrie`](@ref) data structure.
"""
function sort_node!(node::Node)
sort!(children(node); lt=_lt_node_tuples)
return sort!(parents(node); lt=_lt_nodes)
end
"""
mem(graph::DAG)
Return the memory footprint of the graph in Byte. Should be the same result as `Base.summarysize(graph)` but a lot faster.
"""
function mem(graph::DAG)
size = 0
size += Base.summarysize(graph.nodes; exclude=Union{Node})
for n in graph.nodes
size += mem(n)
end
size += sizeof(graph.appliedOperations)
size += sizeof(graph.operationsToApply)
size += sizeof(graph.possibleOperations)
for op in graph.possibleOperations.nodeReductions
size += mem(op)
end
for op in graph.possibleOperations.nodeSplits
size += mem(op)
end
size += Base.summarysize(graph.dirtyNodes; exclude=Union{Node})
return size += sizeof(diff)
end
"""
mem(op::Operation)
Return the memory footprint of the operation in Byte. Used in [`mem(graph::DAG)`](@ref). Unlike `Base.summarysize()` this doesn't follow all references which would yield (almost) the size of the entire graph.
"""
function mem(op::Operation)
return Base.summarysize(op; exclude=Union{Node})
end
"""
mem(op::Operation)
Return the memory footprint of the node in Byte. Used in [`mem(graph::DAG)`](@ref). Unlike `Base.summarysize()` this doesn't follow all references which would yield (almost) the size of the entire graph.
"""
function mem(node::Node)
return Base.summarysize(node; exclude=Union{Node,Operation})
end
"""
unroll_symbol_vector(vec::Vector{Symbol})
Return the given vector as single String without quotation marks or brackets.
"""
function unroll_symbol_vector(vec::Vector)
result = ""
for s in vec
if (result != "")
result *= ", "
end
result *= "$s"
end
return result
end
function unroll_symbol_vector(vec::SVector)
return unroll_symbol_vector(Vector(vec))
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1985 | """
get_compute_function(
graph::DAG,
instance,
machine::Machine,
context_module::Module
)
Return a function of signature `compute_<id>(input::input_type(instance))`, which will return the result of the DAG computation on the given input.
The final argument `context_module` should always be `@__MODULE__` to be able to use functions defined in the caller's environment. For this to work,
you need
```Julia
using RuntimeGeneratedFunctions
RuntimeGeneratedFunctions.init(@__MODULE__)
```
in your top level.
"""
function get_compute_function(
graph::DAG, instance, machine::Machine, context_module::Module
)
tape = gen_tape(graph, instance, machine, context_module)
initCaches = Expr(:block, tape.initCachesCode...)
assignInputs = Expr(:block, expr_from_fc.(tape.inputAssignCode)...)
code = Expr(:block, expr_from_fc.(tape.computeCode)...)
functionId = to_var_name(UUIDs.uuid1(rng[1]))
resSym = eval(gen_access_expr(entry_device(tape.machine), tape.outputSymbol))
expr = #
Expr(
:function, # function definition
Expr(
:call,
Symbol("compute_$functionId"),
Expr(:(::), :data_input, input_type(instance)),
), # function name and parameters
Expr(:block, initCaches, assignInputs, code, Expr(:return, resSym)), # function body
)
return RuntimeGeneratedFunction(@__MODULE__, context_module, expr)
end
"""
execute(
graph::DAG,
instance,
machine::Machine,
input,
context_module::Module
)
Execute the code of the given `graph` on the given input values.
This is essentially shorthand for
```julia
tape = gen_tape(graph, instance, machine, context_module)
return execute_tape(tape, input)
```
"""
function execute(graph::DAG, instance, machine::Machine, input, context_module::Module)
tape = gen_tape(graph, instance, machine, context_module)
return execute_tape(tape, input)
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 5906 | # TODO: do this with macros
function call_fc(
fc::FunctionCall{VectorT,0}, cache::Dict{Symbol,Any}
) where {VectorT<:SVector{1}}
cache[fc.return_symbol] = fc.func(cache[fc.arguments[1]])
return nothing
end
function call_fc(
fc::FunctionCall{VectorT,1}, cache::Dict{Symbol,Any}
) where {VectorT<:SVector{1}}
cache[fc.return_symbol] = fc.func(fc.value_arguments[1], cache[fc.arguments[1]])
return nothing
end
function call_fc(
fc::FunctionCall{VectorT,0}, cache::Dict{Symbol,Any}
) where {VectorT<:SVector{2}}
cache[fc.return_symbol] = fc.func(cache[fc.arguments[1]], cache[fc.arguments[2]])
return nothing
end
function call_fc(
fc::FunctionCall{VectorT,1}, cache::Dict{Symbol,Any}
) where {VectorT<:SVector{2}}
cache[fc.return_symbol] = fc.func(
fc.value_arguments[1], cache[fc.arguments[1]], cache[fc.arguments[2]]
)
return nothing
end
function call_fc(fc::FunctionCall{VectorT,1}, cache::Dict{Symbol,Any}) where {VectorT}
cache[fc.return_symbol] = fc.func(
fc.value_arguments[1], getindex.(Ref(cache), fc.arguments)...
)
return nothing
end
"""
call_fc(fc::FunctionCall, cache::Dict{Symbol, Any})
Execute the given [`FunctionCall`](@ref) on the dictionary.
Several more specialized versions of this function exist to reduce vector unrolling work for common cases.
"""
function call_fc(fc::FunctionCall{VectorT,M}, cache::Dict{Symbol,Any}) where {VectorT,M}
cache[fc.return_symbol] = fc.func(
fc.value_arguments..., getindex.(Ref(cache), fc.arguments)...
)
return nothing
end
function expr_from_fc(fc::FunctionCall{VectorT,0}) where {VectorT}
func_call = Expr(
:call, fc.func, eval.(gen_access_expr.(Ref(fc.device), fc.arguments))...
)
access_expr = eval(gen_access_expr(fc.device, fc.return_symbol))
return Expr(:(=), access_expr, func_call)
end
"""
expr_from_fc(fc::FunctionCall)
For a given function call, return an expression evaluating it.
"""
function expr_from_fc(fc::FunctionCall{VectorT,M}) where {VectorT,M}
func_call = Expr(
:call,
fc.func,
fc.value_arguments...,
eval.(gen_access_expr.(Ref(fc.device), fc.arguments))...,
)
access_expr = eval(gen_access_expr(fc.device, fc.return_symbol))
return Expr(:(=), access_expr, func_call)
end
"""
gen_cache_init_code(machine::Machine)
For each [`AbstractDevice`](@ref) in the given [`Machine`](@ref), returning a `Vector{Expr}` doing the initialization.
"""
function gen_cache_init_code(machine::Machine)
initialize_caches = Vector{Expr}()
for device in machine.devices
push!(initialize_caches, gen_cache_init_code(device))
end
return initialize_caches
end
"""
gen_input_assignment_code(
input_symbols::Dict{String, Vector{Symbol}},
instance::AbstractProblemInstance,
machine::Machine,
context_module::Module
)
Return a `Vector{Expr}` doing the input assignments from the given `problem_input` onto the `input_symbols`.
"""
function gen_input_assignment_code(
input_symbols::Dict{String,Vector{Symbol}},
instance,
machine::Machine,
context_module::Module,
)
assign_inputs = Vector{FunctionCall}()
for (name, symbols) in input_symbols
# make a function for this, since we can't use anonymous functions in the FunctionCall
for symbol in symbols
device = entry_device(machine)
fc = FunctionCall(
RuntimeGeneratedFunction(
@__MODULE__,
context_module,
Expr(:->, :x, input_expr(instance, name, :x)),
),
SVector{0,Any}(),
SVector{1,Symbol}(:input),
symbol,
device,
)
push!(assign_inputs, fc)
end
end
return assign_inputs
end
"""
gen_tape(
graph::DAG,
instance::AbstractProblemInstance,
machine::Machine,
context_module::Module,
scheduler::AbstractScheduler = GreedyScheduler()
)
Generate the code for a given graph. The return value is a [`Tape`](@ref).
See also: [`execute`](@ref), [`execute_tape`](@ref)
"""
function gen_tape(
graph::DAG,
instance,
machine::Machine,
context_module::Module,
scheduler::AbstractScheduler=GreedyScheduler(),
)
schedule = schedule_dag(scheduler, graph, machine)
# get inSymbols
inputSyms = Dict{String,Vector{Symbol}}()
for node in get_entry_nodes(graph)
if !haskey(inputSyms, node.name)
inputSyms[node.name] = Vector{Symbol}()
end
push!(inputSyms[node.name], Symbol("$(to_var_name(node.id))_in"))
end
# get outSymbol
outSym = Symbol(to_var_name(get_exit_node(graph).id))
initCaches = gen_cache_init_code(machine)
assign_inputs = gen_input_assignment_code(inputSyms, instance, machine, context_module)
return Tape{input_type(instance)}(
initCaches, assign_inputs, schedule, inputSyms, outSym, Dict(), instance, machine
)
end
"""
execute_tape(tape::Tape, input::Input) where {Input}
Execute the given tape with the given input.
For implementation reasons, this disregards the set [`CacheStrategy`](@ref) of the devices and always uses a dictionary.
"""
function execute_tape(tape::Tape, input)
cache = Dict{Symbol,Any}()
cache[:input] = input
# simply execute all the code snippets here
@assert typeof(input) <: input_type(tape.instance) "expected tape input type to fit $(input_type(tape.instance)) but got $(typeof(input))"
for expr in tape.initCachesCode
@eval $expr
end
for function_call in tape.inputAssignCode
call_fc(function_call, cache)
end
for function_call in tape.computeCode
call_fc(function_call, cache)
end
return cache[tape.outputSymbol]
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 694 |
"""
Tape{INPUT}
TODO: update docs
- `INPUT` the input type of the problem instance
- `code::Vector{Expr}`: The julia expression containing the code for the whole graph.
- `inputSymbols::Dict{String, Vector{Symbol}}`: A dictionary of symbols mapping the names of the input nodes of the graph to the symbols their inputs should be provided on.
- `outputSymbol::Symbol`: The symbol of the final calculated value
"""
struct Tape{INPUT}
initCachesCode::Vector{Expr}
inputAssignCode::Vector{FunctionCall}
computeCode::Vector{FunctionCall}
inputSymbols::Dict{String,Vector{Symbol}}
outputSymbol::Symbol
cache::Dict{Symbol,Any}
instance::Any
machine::Machine
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 701 |
"""
get_machine_info(verbose::Bool)
Return the [`Machine`](@ref) currently running on. The parameter `verbose` defaults to true when interactive.
"""
function get_machine_info(; verbose::Bool=Base.is_interactive)
devices = Vector{AbstractDevice}()
for device in device_types()
devs = get_devices(device; verbose=verbose)
for dev in devs
push!(devices, dev)
end
end
noDevices = length(devices)
@assert noDevices > 0 "No devices were found, but at least one NUMA node should always be available!"
transferRates = Matrix{Float64}(undef, noDevices, noDevices)
fill!(transferRates, -1)
return Machine(devices, transferRates)
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1111 | # file for struct definitions used by the extensions
# since extensions can't export names themselves
"""
CUDAGPU <: AbstractGPU
Representation of a specific CUDA GPU that code can run on. Implements the [`AbstractDevice`](@ref) interface.
!!! note
This requires CUDA to be loaded to be useful.
"""
mutable struct CUDAGPU <: AbstractGPU
device::Any # CuDevice
cacheStrategy::CacheStrategy
FLOPS::Float64
end
"""
oneAPIGPU <: AbstractGPU
Representation of a specific Intel GPU that code can run on. Implements the [`AbstractDevice`](@ref) interface.
!!! note
This requires oneAPI to be loaded to be useful.
"""
mutable struct oneAPIGPU <: AbstractGPU
device::Any # oneAPI.oneL0.ZeDevice
cacheStrategy::CacheStrategy
FLOPS::Float64
end
"""
ROCmGPU <: AbstractGPU
Representation of a specific AMD GPU that code can run on. Implements the [`AbstractDevice`](@ref) interface.
!!! note
This requires AMDGPU to be loaded to be useful.
"""
mutable struct ROCmGPU <: AbstractGPU
device::Any # HIPDevice
cacheStrategy::CacheStrategy
FLOPS::Float64
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1771 | """
device_types()
Return a vector of available and implemented device types.
See also: [`DEVICE_TYPES`](@ref)
"""
function device_types()
return DEVICE_TYPES
end
"""
entry_device(machine::Machine)
Return the "entry" device, i.e., the device that starts CPU threads and GPU kernels, and takes input values and returns the output value.
"""
function entry_device(machine::Machine)
return machine.devices[1]
end
"""
strategies(t::Type{T}) where {T <: AbstractDevice}
Return a vector of available [`CacheStrategy`](@ref)s for the given [`AbstractDevice`](@ref).
The caching strategies are used in code generation.
"""
function strategies(t::Type{T}) where {T<:AbstractDevice}
if !haskey(CACHE_STRATEGIES, t)
error("Trying to get strategies for $T, but it has no strategies defined!")
end
return CACHE_STRATEGIES[t]
end
"""
cache_strategy(device::AbstractDevice)
Returns the cache strategy set for this device.
"""
function cache_strategy(device::AbstractDevice)
return device.cacheStrategy
end
"""
set_cache_strategy(device::AbstractDevice, cacheStrategy::CacheStrategy)
Sets the device's cache strategy. After this call, [`cache_strategy`](@ref) should return `cacheStrategy` on the given device.
"""
function set_cache_strategy(device::AbstractDevice, cacheStrategy::CacheStrategy)
device.cacheStrategy = cacheStrategy
return nothing
end
"""
cpu_st()
A function returning a [`Machine`](@ref) that only has a single thread of one CPU.
It is the simplest machine definition possible and produces a simple function when used with [`get_compute_function`](@ref).
"""
function cpu_st()
return Machine(
[NumaNode(0, 1, default_strategy(NumaNode), -1.0, UUIDs.uuid1())], [-1.0;;]
)
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 6267 | """
AbstractDevice
Abstract base type for every device, like GPUs, CPUs or any other compute devices.
Every implementation needs to implement various functions and needs a member `cacheStrategy`.
"""
abstract type AbstractDevice end
abstract type AbstractCPU <: AbstractDevice end
abstract type AbstractGPU <: AbstractDevice end
"""
Machine
A representation of a machine to execute on. Contains information about its architecture (CPUs, GPUs, maybe more). This representation can be used to make a more accurate cost prediction of a [`DAG`](@ref) state.
See also: [`Scheduler`](@ref)
"""
struct Machine
devices::Vector{AbstractDevice}
transferRates::Matrix{Float64}
end
"""
CacheStrategy
Abstract base type for caching strategies.
See also: [`strategies`](@ref)
"""
abstract type CacheStrategy end
"""
LocalVariables <: CacheStrategy
A caching strategy relying solely on local variables for every input and output.
Implements the [`CacheStrategy`](@ref) interface.
"""
struct LocalVariables <: CacheStrategy end
"""
Dictionary <: CacheStrategy
A caching strategy relying on a dictionary of Symbols to store every input and output.
Implements the [`CacheStrategy`](@ref) interface.
"""
struct Dictionary <: CacheStrategy end
"""
DEVICE_TYPES::Vector{Type}
Global vector of available and implemented device types. Each implementation of a [`AbstractDevice`](@ref) should add its concrete type to this vector.
See also: [`device_types`](@ref), [`get_devices`](@ref)
"""
DEVICE_TYPES = Vector{Type}()
"""
CACHE_STRATEGIES::Dict{Type{AbstractDevice}, Symbol}
Global dictionary of available caching strategies per device. Each implementation of [`AbstractDevice`](@ref) should add its available strategies to the dictionary.
See also: [`strategies`](@ref)
"""
CACHE_STRATEGIES = Dict{Type,Vector{CacheStrategy}}()
"""
default_strategy(deviceType::Type{T}) where {T <: AbstractDevice}
Interface function that must be implemented for every subtype of [`AbstractDevice`](@ref). Returns the default [`CacheStrategy`](@ref) to use on the given device type.
See also: [`cache_strategy`](@ref), [`set_cache_strategy`](@ref)
"""
function default_strategy end
"""
get_devices(t::Type{T}; verbose::Bool) where {T <: AbstractDevice}
Interface function that must be implemented for every subtype of [`AbstractDevice`](@ref). Returns a `Vector{Type}` of the devices for the given [`AbstractDevice`](@ref) Type available on the current machine.
"""
function get_devices end
"""
measure_device!(device::AbstractDevice; verbose::Bool)
Interface function that must be implemented for every subtype of [`AbstractDevice`](@ref). Measures the compute speed of the given device and writes into it.
"""
function measure_device! end
"""
gen_cache_init_code(device::AbstractDevice)
Interface function that must be implemented for every subtype of [`AbstractDevice`](@ref) and at least one [`CacheStrategy`](@ref). Returns an `Expr` initializing this device's variable cache.
The strategy is a symbol
"""
function gen_cache_init_code end
"""
gen_access_expr(device::AbstractDevice, symbol::Symbol)
Interface function that must be implemented for every subtype of [`AbstractDevice`](@ref) and at least one [`CacheStrategy`](@ref).
Return an `Expr` or `QuoteNode` accessing the variable identified by [`symbol`].
"""
function gen_access_expr end
"""
kernel(gpu_type::Type{<:AbstractGPU}, graph::DAG, instance)
For a GPU type, a [`DAG`](@ref), and a problem instance, return an `Expr` containing a function of signature `compute_<id>(input::<GPU>Vector, output::<GPU>Vector, n::Int64)`, which will return the result of the DAG computation of the input on the given output vector, intended for computation on GPUs. Currently, `CUDAGPU` and `ROCmGPU` are available if their respective package extensions are loaded.
The generated kernel function accepts its thread ID in only the x-dimension, and only as thread ID, not as block ID. The input and output should therefore be 1-dimensional vectors. For detailed information on GPU programming and the Julia packages, please refer to their respective documentations.
A simple example call for a CUDA kernel might look like the following:
```Julia
@cuda threads = (32,) always_inline = true cuda_kernel!(cu_inputs, outputs, length(cu_inputs))
```
!!! note
Unlike the standard [`get_compute_function`](@ref) to generate a callable function which returns a `RuntimeGeneratedFunction`, this returns an `Expr` that needs to be `eval`'d. This is a current limitation of `RuntimeGeneratedFunctions.jl` which currently cannot wrap GPU kernels. This might change in the future.
### Size limitation
The generated kernel does not use any internal parallelization, i.e., the DAG is compiled into a serialized function, processing each input in a single thread of the GPU. This means it can be heavily parallelized and use the GPU at 100% for sufficiently large input vectors (and assuming the function does not become IO limited etc.). However, it also means that there is a limit to how large the compiled function can be. If it gets too large, the compilation might fail, take too long to complete, the kernel might fail during execution if too much stack memory is required, or other similar problems. If this happens, your problem is likely too large to be compiled to a GPU kernel like this.
### Compute Requirements
A GPU function has more restrictions on what can be computed than general functions running on the CPU. In Julia, there are mainly two important restrictions to consider:
1. Used data types must be stack allocatable, i.e., `isbits(x)` must be `true` for arguments and local variables used in `ComputeTasks`.
2. Function calls must not be dynamic. This means that type stability is required and the compiler must know in advance which method of a generic function to call. What this specifically entails may change with time and also differs between the different target GPU libraries. From experience, using the `always_inline = true` argument for `@cuda` calls can help with this.
!!! warning
This feature is currently experimental. There are still some unresolved issues with the generated kernels.
"""
function kernel end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 632 | """
measure_devices(machine::Machine; verbose::Bool)
Measure FLOPS, RAM, cache sizes and what other properties can be extracted for the devices in the given machine.
"""
function measure_devices!(machine::Machine; verbose::Bool=Base.is_interactive())
for device in machine.devices
measure_device!(device; verbose=verbose)
end
return nothing
end
"""
measure_transfer_rates(machine::Machine; verbose::Bool)
Measure the transfer rates between devices in the machine.
"""
function measure_transfer_rates!(machine::Machine; verbose::Bool=Base.is_interactive())
# TODO implement
return nothing
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 2818 | using NumaAllocators
"""
NumaNode <: AbstractCPU
Representation of a specific CPU that code can run on. Implements the [`AbstractDevice`](@ref) interface.
"""
mutable struct NumaNode <: AbstractCPU
numaId::UInt16
threads::UInt16
cacheStrategy::CacheStrategy
FLOPS::Float64
id::UUID
end
push!(DEVICE_TYPES, NumaNode)
CACHE_STRATEGIES[NumaNode] = [LocalVariables()]
default_strategy(::Type{T}) where {T<:NumaNode} = LocalVariables()
function measure_device!(device::NumaNode; verbose::Bool)
verbose && @info "Measuring Numa Node $(device.numaId)"
# TODO implement
return nothing
end
"""
get_devices(deviceType::Type{T}; verbose::Bool) where {T <: NumaNode}
Return a Vector of [`NumaNode`](@ref)s available on the current machine. If `verbose` is true, print some additional information.
"""
function get_devices(deviceType::Type{T}; verbose::Bool=false) where {T<:NumaNode}
devices = Vector{AbstractDevice}()
noNumaNodes = highest_numa_node()
verbose && @info "Found $(noNumaNodes + 1) NUMA nodes"
for i in 0:noNumaNodes
push!(devices, NumaNode(i, 1, default_strategy(NumaNode), -1, UUIDs.uuid1(rng[1])))
end
return devices
end
"""
gen_cache_init_code(device::NumaNode)
Generate code for initializing the [`LocalVariables`](@ref) strategy on a [`NumaNode`](@ref).
"""
function gen_cache_init_code(device::NumaNode)
if typeof(device.cacheStrategy) <: LocalVariables
# don't need to initialize anything
return Expr(:block)
elseif typeof(device.cacheStrategy) <: Dictionary
return Meta.parse("cache_$(to_var_name(device.id)) = Dict{Symbol, Any}()")
# TODO: sizehint?
end
return error(
"Unimplemented cache strategy \"$(device.cacheStrategy)\" for device \"$(device)\""
)
end
"""
gen_access_expr(device::NumaNode, symbol::Symbol)
Generate code to access the variable designated by `symbol` on a [`NumaNode`](@ref), using the [`CacheStrategy`](@ref) set in the device.
"""
function gen_access_expr(device::NumaNode, symbol::Symbol)
return _gen_access_expr(device, device.cacheStrategy, symbol)
end
"""
_gen_access_expr(device::NumaNode, ::LocalVariables, symbol::Symbol)
Internal function for dispatch, used in [`gen_access_expr`](@ref).
"""
function _gen_access_expr(device::NumaNode, ::LocalVariables, symbol::Symbol)
s = Symbol("data_$symbol")
quoteNode = Meta.parse(":($s)")
return quoteNode
end
"""
_gen_access_expr(device::NumaNode, ::Dictionary, symbol::Symbol)
Internal function for dispatch, used in [`gen_access_expr`](@ref).
"""
function _gen_access_expr(device::NumaNode, ::Dictionary, symbol::Symbol)
accessStr = ":(cache_$(to_var_name(device.id))[:$symbol])"
quoteNode = Meta.parse(accessStr)
return quoteNode
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 339 | """
show(io::IO, diff::Diff)
Pretty-print a [`Diff`](@ref). Called via print, println and co.
"""
function Base.show(io::IO, diff::Diff)
print(io, "Nodes: ")
print(io, length(diff.addedNodes) + length(diff.removedNodes))
print(io, ", Edges: ")
return print(io, length(diff.addedEdges) + length(diff.removedEdges))
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 428 | """
length(diff::Diff)
Return a named tuple of the lengths of the added/removed nodes/edges.
The fields are `.addedNodes`, `.addedEdges`, `.removedNodes` and `.removedEdges`.
"""
function Base.length(diff::Diff)
return (
addedNodes=length(diff.addedNodes),
removedNodes=length(diff.removedNodes),
addedEdges=length(diff.addedEdges),
removedEdges=length(diff.removedEdges),
)
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 681 | """
Diff
A named tuple representing a difference of added and removed nodes and edges on a [`DAG`](@ref).
"""
const Diff = NamedTuple{
(:addedNodes, :removedNodes, :addedEdges, :removedEdges, :updatedChildren),
Tuple{
Vector{Node},Vector{Node},Vector{Edge},Vector{Edge},Vector{Tuple{Node,AbstractTask}}
},
}
function Diff()
return (
addedNodes=Vector{Node}(),
removedNodes=Vector{Node}(),
addedEdges=Vector{Edge}(),
removedEdges=Vector{Edge}(),
# children were updated in the task, updatedChildren[x][2] is the task before the update
updatedChildren=Vector{Tuple{Node,AbstractTask}}(),
)::Diff
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 2790 | """
CDCost
Representation of a [`DAG`](@ref)'s cost as estimated by the [`GlobalMetricEstimator`](@ref).
# Fields:
`.data`: The total data transfer.\\
`.computeEffort`: The total compute effort.\\
`.computeIntensity`: The compute intensity, will always equal `.computeEffort / .data`.
!!! note
Note that the `computeIntensity` doesn't necessarily make sense in the context of only operation costs.
It will still work as intended when adding/subtracting to/from a `graph_cost` estimate.
"""
const CDCost = NamedTuple{
(:data, :computeEffort, :computeIntensity),Tuple{Float64,Float64,Float64}
}
function Base.:+(cost1::CDCost, cost2::CDCost)::CDCost
d = cost1.data + cost2.data
ce = computeEffort = cost1.computeEffort + cost2.computeEffort
return (data=d, computeEffort=ce, computeIntensity=ce / d)::CDCost
end
function Base.:-(cost1::CDCost, cost2::CDCost)::CDCost
d = cost1.data - cost2.data
ce = computeEffort = cost1.computeEffort - cost2.computeEffort
return (data=d, computeEffort=ce, computeIntensity=ce / d)::CDCost
end
function Base.isless(cost1::CDCost, cost2::CDCost)::Bool
return cost1.data + cost1.computeEffort < cost2.data + cost2.computeEffort
end
function Base.zero(type::Type{CDCost})
return (data=0.0, computeEffort=0.0, computeIntensity=0.0)::CDCost
end
function Base.typemax(type::Type{CDCost})
return (data=Inf, computeEffort=Inf, computeIntensity=0.0)::CDCost
end
"""
GlobalMetricEstimator <: AbstractEstimator
A simple estimator that adds up each node's set [`compute_effort`](@ref) and [`data`](@ref).
"""
struct GlobalMetricEstimator <: AbstractEstimator end
function cost_type(estimator::GlobalMetricEstimator)::Type{CDCost}
return CDCost
end
function graph_cost(estimator::GlobalMetricEstimator, graph::DAG)
properties = get_properties(graph)
return (
data=properties.data,
computeEffort=properties.computeEffort,
computeIntensity=properties.computeIntensity,
)::CDCost
end
function operation_effect(
estimator::GlobalMetricEstimator, graph::DAG, operation::NodeReduction
)
s = length(operation.input) - 1
return (
data=s * -data(task(operation.input[1])),
computeEffort=s * -compute_effort(task(operation.input[1])),
computeIntensity=typeof(operation.input) <: DataTaskNode ? 0.0 : Inf,
)::CDCost
end
function operation_effect(
estimator::GlobalMetricEstimator, graph::DAG, operation::NodeSplit
)
s::Float64 = length(parents(operation.input)) - 1
d::Float64 = s * data(task(operation.input))
ce::Float64 = s * compute_effort(task(operation.input))
return (data=d, computeEffort=ce, computeIntensity=ce / d)::CDCost
end
function String(::GlobalMetricEstimator)
return "global_metric"
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1905 |
"""
AbstractEstimator
Abstract base type for an estimator. An estimator estimates the cost of a graph or the difference an operation applied to a graph will make to its cost.
Interface functions are
- [`graph_cost`](@ref)
- [`operation_effect`](@ref)
"""
abstract type AbstractEstimator end
"""
cost_type(estimator::AbstractEstimator)
Interface function returning a specific estimator's cost type, i.e., the type returned by its implementation of [`graph_cost`](@ref) and [`operation_effect`](@ref).
"""
function cost_type end
"""
graph_cost(estimator::AbstractEstimator, graph::DAG)
Get the total estimated cost of the graph. The cost's data type can be chosen by the implementation, but must have a usable lessthan comparison operator (<), basic math operators (+, -) and an implementation of `zero()` and `typemax()`.
"""
function graph_cost end
"""
operation_effect(estimator::AbstractEstimator, graph::DAG, operation::Operation)
Get the estimated effect on the cost of the graph, such that `graph_cost(estimator, graph) + operation_effect(estimator, graph, operation) ~= graph_cost(estimator, graph_with_operation_applied)`. There is no hard requirement for this, but the better the estimate, the better an optimization algorithm will be.
!!! note
There is a default implementation of this function, applying the operation, calling [`graph_cost`](@ref), then popping the operation again.
It can be much faster to overload this function for a specific estimator and directly compute the effects from the operation if possible.
"""
function operation_effect(estimator::AbstractEstimator, graph::DAG, operation::Operation)
# This is currently not stably working, see issue #16
cost = graph_cost(estimator, graph)
push_operation!(graph, operation)
cost_after = graph_cost(estimator, graph)
pop_operation!(graph)
return cost_after - cost
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 428 | """
in(node::Node, graph::DAG)
Check whether the node is part of the graph.
"""
Base.in(node::Node, graph::DAG) = node in graph.nodes
"""
in(edge::Edge, graph::DAG)
Check whether the edge is part of the graph.
"""
function Base.in(edge::Edge, graph::DAG)
n1 = edge.edge[1]
n2 = edge.edge[2]
if !(n1 in graph) || !(n2 in graph)
return false
end
return n1 in getindex.(children(n2), 1)
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 1292 | """
push_operation!(graph::DAG, operation::Operation)
Apply a new operation to the graph.
See also: [`DAG`](@ref), [`pop_operation!`](@ref)
"""
function push_operation!(graph::DAG, operation::Operation)
# 1.: Add the operation to the DAG
push!(graph.operationsToApply, operation)
return nothing
end
"""
pop_operation!(graph::DAG)
Revert the latest applied operation on the graph.
See also: [`DAG`](@ref), [`push_operation!`](@ref)
"""
function pop_operation!(graph::DAG)
# 1.: Remove the operation from the appliedChain of the DAG
if !isempty(graph.operationsToApply)
pop!(graph.operationsToApply)
elseif !isempty(graph.appliedOperations)
appliedOp = pop!(graph.appliedOperations)
revert_operation!(graph, appliedOp)
else
error("No more operations to pop!")
end
return nothing
end
"""
can_pop(graph::DAG)
Return `true` if [`pop_operation!`](@ref) is possible, `false` otherwise.
"""
can_pop(graph::DAG) = !isempty(graph.operationsToApply) || !isempty(graph.appliedOperations)
"""
reset_graph!(graph::DAG)
Reset the graph to its initial state with no operations applied.
"""
function reset_graph!(graph::DAG)
while (can_pop(graph))
pop_operation!(graph)
end
return nothing
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
|
[
"MIT"
] | 0.1.1 | 30cc181d3443bdf6e274199b938e3354f6ad87fb | code | 9158 | # for graph mutating functions we need to do a few things
# 1: mute the graph (duh)
# 2: keep track of what was changed for the diff (if track == true)
# 3: invalidate operation caches
"""
insert_node!(graph::DAG, node::Node)
insert_node!(graph::DAG, task::AbstractTask, name::String="")
Insert the node into the graph or alternatively construct a node from the given task and insert it.
"""
function insert_node!(graph::DAG, node::Node)
return _insert_node!(graph, node; track=false, invalidate_cache=false)
end
function insert_node!(graph::DAG, task::AbstractDataTask, name::String="")
return _insert_node!(graph, make_node(task, name); track=false, invalidate_cache=false)
end
function insert_node!(graph::DAG, task::AbstractComputeTask)
return _insert_node!(graph, make_node(task); track=false, invalidate_cache=false)
end
"""
insert_edge!(graph::DAG, node1::Node, node2::Node)
Insert the edge between node1 (child) and node2 (parent) into the graph.
"""
function insert_edge!(graph::DAG, node1::Node, node2::Node, index::Int=0)
return _insert_edge!(graph, node1, node2, index; track=false, invalidate_cache=false)
end
"""
_insert_node!(graph::DAG, node::Node; track = true, invalidate_cache = true)
Insert the node into the graph.
!!! warning
For creating new graphs, use the public version [`insert_node!`](@ref) instead which uses the defaults false for the keywords.
## Keyword Arguments
`track::Bool`: Whether to add the changes to the [`DAG`](@ref)'s [`Diff`](@ref). Should be set `false` in parsing or graph creation functions for performance.
`invalidate_cache::Bool`: Whether to invalidate caches associated with the changes. Should also be turned off for graph creation or parsing.
See also: [`_remove_node!`](@ref), [`_insert_edge!`](@ref), [`_remove_edge!`](@ref)
"""
function _insert_node!(graph::DAG, node::Node; track=true, invalidate_cache=true)
# 1: mute
push!(graph.nodes, node)
# 2: keep track
if (track)
push!(graph.diff.addedNodes, node)
end
# 3: invalidate caches
if (!invalidate_cache)
return node
end
push!(graph.dirtyNodes, node)
return node
end
"""
_insert_edge!(graph::DAG, node1::Node, node2::Node, index::Int=0; track = true, invalidate_cache = true)
Insert the edge between `node1` (child) and `node2` (parent) into the graph. An optional integer index can be given. The arguments of the function call that this node compiles to will then be ordered by these indices.
!!! warning
For creating new graphs, use the public version [`insert_edge!`](@ref) instead which uses the defaults false for the keywords.
## Keyword Arguments
- `track::Bool`: Whether to add the changes to the [`DAG`](@ref)'s [`Diff`](@ref). Should be set `false` in parsing or graph creation functions for performance.
- `invalidate_cache::Bool`: Whether to invalidate caches associated with the changes. Should also be turned off for graph creation or parsing.
See also: [`_insert_node!`](@ref), [`_remove_node!`](@ref), [`_remove_edge!`](@ref)
"""
function _insert_edge!(
graph::DAG, node1::Node, node2::Node, index::Int=0; track=true, invalidate_cache=true
)
#@assert (node2 ∉ parents(node1)) && (node1 ∉ children(node2)) "Edge to insert already exists"
# 1: mute
# edge points from child to parent
push!(node1.parents, node2)
push!(node2.children, (node1, index))
# 2: keep track
if (track)
push!(graph.diff.addedEdges, make_edge(node1, node2, index))
end
# 3: invalidate caches
if (!invalidate_cache)
return nothing
end
invalidate_operation_caches!(graph, node1)
invalidate_operation_caches!(graph, node2)
push!(graph.dirtyNodes, node1)
push!(graph.dirtyNodes, node2)
return nothing
end
"""
_remove_node!(graph::DAG, node::Node; track = true, invalidate_cache = true)
Remove the node from the graph.
## Keyword Arguments
`track::Bool`: Whether to add the changes to the [`DAG`](@ref)'s [`Diff`](@ref). Should be set `false` in parsing or graph creation functions for performance.
`invalidate_cache::Bool`: Whether to invalidate caches associated with the changes. Should also be turned off for graph creation or parsing.
See also: [`_insert_node!`](@ref), [`_insert_edge!`](@ref), [`_remove_edge!`](@ref)
"""
function _remove_node!(graph::DAG, node::Node; track=true, invalidate_cache=true)
#@assert node in graph.nodes "Trying to remove a node that's not in the graph"
# 1: mute
delete!(graph.nodes, node)
# 2: keep track
if (track)
push!(graph.diff.removedNodes, node)
end
# 3: invalidate caches
if (!invalidate_cache)
return nothing
end
invalidate_operation_caches!(graph, node)
delete!(graph.dirtyNodes, node)
return nothing
end
"""
_remove_edge!(graph::DAG, node1::Node, node2::Node; track = true, invalidate_cache = true)
Remove the edge between node1 (child) and node2 (parent) into the graph. Returns the integer index of the removed edge.
## Keyword Arguments
- `track::Bool`: Whether to add the changes to the [`DAG`](@ref)'s [`Diff`](@ref). Should be set `false` in parsing or graph creation functions for performance.
- `invalidate_cache::Bool`: Whether to invalidate caches associated with the changes. Should also be turned off for graph creation or parsing.
See also: [`_insert_node!`](@ref), [`_remove_node!`](@ref), [`_insert_edge!`](@ref)
"""
function _remove_edge!(
graph::DAG, node1::Node, node2::Node; track=true, invalidate_cache=true
)
# 1: mute
pre_length1 = length(node1.parents)
pre_length2 = length(node2.children)
for i in eachindex(node1.parents)
if (node1.parents[i] == node2)
splice!(node1.parents, i)
break
end
end
removed_node_index = 0
for i in eachindex(node2.children)
if (node2.children[i][1] == node1)
removed_node_index = node2.children[i][2]
splice!(node2.children, i)
break
end
end
#=@assert begin
removed = pre_length1 - length(node1.parents)
removed <= 1
end "removed more than one node from node1's parents"=#
#=@assert begin
removed = pre_length2 - length(children(node2))
removed <= 1
end "removed more than one node from node2's children"=#
# 2: keep track
if (track)
push!(graph.diff.removedEdges, make_edge(node1, node2, removed_node_index))
end
# 3: invalidate caches
if (!invalidate_cache)
return removed_node_index
end
invalidate_operation_caches!(graph, node1)
invalidate_operation_caches!(graph, node2)
if (node1 in graph)
push!(graph.dirtyNodes, node1)
end
if (node2 in graph)
push!(graph.dirtyNodes, node2)
end
return removed_node_index
end
"""
get_snapshot_diff(graph::DAG)
Return the graph's [`Diff`](@ref) since last time this function was called.
See also: [`revert_diff!`](@ref), [`AppliedOperation`](@ref) and [`revert_operation!`](@ref)
"""
function get_snapshot_diff(graph::DAG)
return swapfield!(graph, :diff, Diff())
end
"""
invalidate_caches!(graph::DAG, operation::NodeReduction)
Invalidate the operation caches for a given [`NodeReduction`](@ref).
This deletes the operation from the graph's possible operations and from the involved nodes' own operation caches.
"""
function invalidate_caches!(graph::DAG, operation::NodeReduction)
delete!(graph.possibleOperations, operation)
for node in operation.input
node.nodeReduction = missing
end
return nothing
end
"""
invalidate_caches!(graph::DAG, operation::NodeSplit)
Invalidate the operation caches for a given [`NodeSplit`](@ref).
This deletes the operation from the graph's possible operations and from the involved nodes' own operation caches.
"""
function invalidate_caches!(graph::DAG, operation::NodeSplit)
delete!(graph.possibleOperations, operation)
# delete the operation from all caches of nodes involved in the operation
# for node split there is only one node
operation.input.nodeSplit = missing
return nothing
end
"""
invalidate_operation_caches!(graph::DAG, node::ComputeTaskNode)
Invalidate the operation caches of the given node through calls to the respective [`invalidate_caches!`](@ref) functions.
"""
function invalidate_operation_caches!(graph::DAG, node::ComputeTaskNode)
if !ismissing(node.nodeReduction)
invalidate_caches!(graph, node.nodeReduction)
end
if !ismissing(node.nodeSplit)
invalidate_caches!(graph, node.nodeSplit)
end
return nothing
end
"""
invalidate_operation_caches!(graph::DAG, node::DataTaskNode)
Invalidate the operation caches of the given node through calls to the respective [`invalidate_caches!`](@ref) functions.
"""
function invalidate_operation_caches!(graph::DAG, node::DataTaskNode)
if !ismissing(node.nodeReduction)
invalidate_caches!(graph, node.nodeReduction)
end
if !ismissing(node.nodeSplit)
invalidate_caches!(graph, node.nodeSplit)
end
return nothing
end
| ComputableDAGs | https://github.com/ComputableDAGs/ComputableDAGs.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.