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" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
3166
""" add_direction_position!(frames, name::Symbol, origin, target, axes) Add a direction based on the position vector from `origin` to `target` in the specified `axes`. """ function add_direction_position!( frames::FrameSystem{O,T}, name::Symbol, from, to, axes ) where {O,T} fromid, toid = point_id(frames, from), point_id(frames, to) axid = axes_id(frames, axes) for id in (fromid, toid) !has_point(frames, id) && throw( ArgumentError( "no points with id $id registered in the given frame system." ) ) end !has_axes(frames, axid) && throw( ArgumentError( "no axes with id $axes registered in the given frame system" ) ) fun = t -> unitvec(vector3(frames, fromid, toid, axid, t)) return add_direction!(frames, name, axid, fun) end """ add_direction_velocity!(frames, name::Symbol, origin, target, axes) Add a direction based on the velocity vector from `origin` to `target` in the specified `axes`. """ function add_direction_velocity!( frames::FrameSystem{O,T}, name::Symbol, from, to, axes ) where {O,T} fid, tid = point_id(frames, from), point_id(frames, to) axid = axes_id(frames, axes) for id in (fid, tid) !has_point(frames, id) && throw( ArgumentError( "no points with id $id registered in the given frame system." ) ) end !has_axes(frames, axid) && throw( ArgumentError( "no axes with name $axes registered in the given frame system" ) ) fun = t -> @views(unitvec(vector6(frames, fid, tid, axid, t)[4:end])) return add_direction!(frames, name, axid, fun) end """ add_direction_orthogonal!(frames, name::Symbol, dir1, dir2) Add a direction as the cross product between two existing directions (i.e. `dir1` and `dir2`). """ function add_direction_orthogonal!( frames::FrameSystem{O,T}, name::Symbol, dir1::Symbol, dir2::Symbol, axes ) where {O,T} for d in (dir1, dir2) if !(d in keys(directions(frames))) throw( ArgumentError( "no direction with name $d registered in the given frame system" ) ) end end axid = axes_id(frames, axes) !has_axes(frames, axid) && throw( ArgumentError( "no axes with name $axes registered in the given frame system" ) ) fun = t -> unitvec(cross3(direction3(frames, dir1, axid, t), direction3(frames, dir2, axid, t))) return add_direction!(frames, name, axid, fun) end """ add_direction_fixed!(frames, name, axes, offset::AbstractVector) Add a fixed direction to `frames`. """ function add_direction_fixed!( frames::FrameSystem{O,N}, name::Symbol, axes, offset::AbstractVector{T} ) where {O,N,T} if length(offset) != 3 throw( DimensionMismatch( "The offset vector should have length 3, but has $(length(offset))." ), ) end voffset = SVector{3,N}(offset) fun = t -> voffset return add_direction!(frames, name, axes, fun) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1902
""" add_axes_ecl2000!(frames, name::Symbol=:ECL2000, parentid::Int, id::Int = AXESID_ECL2000; model::IERSModel=iers1996) Add Ecliptic Equinox of J2000 (ECL2000) axes to `frames`. Custom `id`, `name` and `parentid` can be assigned by the user. The admissible parent axes are the following: - *ICRF*: for the International Celestial Reference Frame, with ID = $(AXESID_ICRF) - *GCRF*: for the Geocentric Celestial Reference Frame, with ID = $(AXESID_GCRF) - *EME2000*: the Mean Earth/Moon Ephemeris of J2000, with ID = $(AXESID_EME2000) !!! note The obliquity of the ecliptic is computed using the IERS convention `model`. To retrieve the same orientation of the ECLIPJ2000 axes avaialble in the SPICE Toolkit, the `iers1996` model must be used. """ function add_axes_ecl2000!( frames::FrameSystem, name::Symbol=:ECL2000, parentid::Int=AXESID_ICRF, id::Int=AXESID_ECL2000; model::IERSModel=iers1996, ) # Compute the J2000 to ECLIPJ2000 rotation according to the desired IERS model DCM_EME2000_TO_ECLJ2000 = angle_to_dcm(iers_obliquity(model, 0), :X) if parentid == AXESID_ICRF || parentid == AXESID_GCRF dcm = DCM_EME2000_TO_ECLJ2000 * DCM_ICRF_TO_EME2000 elseif parentid == AXESID_EME2000 dcm = DCM_EME2000_TO_ECLJ2000 else throw( ArgumentError( "Ecliptic Equinox of J2000 (ECL2000) axes cannot be defined" * " w.r.t. $parentid axes. Only the ICRF (ID = $(AXESID_ICRF)), the GCRF" * " (ID = $(AXESID_GCRF)) or the EME2000 (ID = $(AXESID_EME2000)) are" * " accepted as parent axes.", ), ) end if id != AXESID_ECL2000 @warn "$name is aliasing an ID that is not the standard ECL2000 ID" * " ($(AXESID_ECL2000))." end return add_axes_fixedoffset!(frames, name, id, parentid, dcm) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
7082
""" add_point_ephemeris!(fr::FrameSystem{O, T}, eph::AbstractEphemerisProvider, name::Symbol, id::Int) where {O, T} Add a point coming from an `AbstractEphemerisProvider` subtype. The point is identifies by the `id` and a have a user defined `name`. !!! warning This is an interface only, concrete subtypes of `AbstractEphemerisProvider` requires an proper implementation. """ @interface function add_point_ephemeris!( ::FrameSystem{O,T}, ::AbstractEphemerisProvider, ::Symbol, ::Int ) where {O,T} end """ add_axes_ephemeris!(frames::FrameSystem{O, T}, eph::AbstractEphemerisProvider, name::Symbol, id::Int, seq::Symbol) where {O, T} Add axes coming from an `AbstractEphemerisProvider` subtype to `frames`. The axes are identifies by the `id` and a have a user defined `name`. The rotation matrix is build using the rotation sequence specified in `seq`. The axes type is specified by `class`. !!! warning This is an interface only, concrete subtypes of `AbstractEphemerisProvider` requires an proper implementation. """ @interface function add_axes_ephemeris!( ::FrameSystem{O,T}, ::AbstractEphemerisProvider, ::Symbol, ::Int, ::Symbol ) where {O,T} end """ add_point_ephemeris!(fr, eph::AbstractEphemerisProvider, book::Dict{Int, Symbol}) Add all points found in the `eph` and using id-names relationships specified in `book`. """ function add_point_ephemeris!( fr::FrameSystem{O,T}, eph::AbstractEphemerisProvider, book::Dict{Int,Symbol} ) where {O,T} records = ephem_position_records(eph) for id in sort(ephem_available_points(eph)) !haskey(book, id) && @warn "Cannot find point with ID $id in the names book" continue if id == 0 if length(points_graph(fr).nodes) == 0 # No point registered in the frame system add_point!(fr, book[id], id, AXESID_ICRF) end else # Assume that the SSB is registered in the frame system it = findfirst(rec -> rec.target == id, records) rec = records[it] add_point_ephemeris!(fr, eph, book[id], id) end end nothing end function check_point_ephemeris( fr::FrameSystem{O,T}, eph::AbstractEphemerisProvider, id::Int ) where {O,T} # Check that the kernels contain the ephemeris data for the given naifid if !(id in ephem_available_points(eph)) throw( ErrorException( "Ephemeris data for ID $naifid is not available in the kernels.", ), ) end # Retrieve the ephemerides position records (i.e., the segment descriptors) pos_records = ephem_position_records(eph) # Retrieve the parent point and the point axes from the ephemeris data parentid, parent_found = 0, false axesid, axes_found = 0, false for pr in pos_records if pr.target == id # Update the parent point ID if !parent_found parentid = pr.center parent_found = true elseif parentid != pr.center throw( ErrorException( "UnambiguityError: at least two set of data with different" * " centers are available for point with ID $id.", ), ) end # Update the reference axes ID if !axes_found axesid = pr.axes axes_found = true elseif axesid != pr.axes throw( ErrorException( "UnambiguityError: at least two set of data with different axes" * " are available for point with ID $id.", ), ) end end end # Check that the default parent is available in the FrameSystem if !has_point(fr, parentid) throw( ErrorException( "Ephemeris data for point with ID $id is available with respect" * " to point with ID $parentid, which has not yet been defined" * " in the input frame system.", ), ) end # The parent point is automatically inferred from the ephemeris kernels so it will # always have available ephemeris data # Checks if the axes are known to the frame system. # This check is also performed by add_point!, but it is reported here because # it provides more specific information for ephemeris points if !has_axes(fr, axesid) throw( ErrorException( "Ephemeris data for point with ID $naifid is expressed in a set" * " of axes with ID $axesid, which are yet to be defined in the" * " input frame system.", ), ) end return parentid, axesid end function check_axes_ephemeris( frames::FrameSystem{O,N}, eph::AbstractEphemerisProvider, id::Int ) where {O,N} # Check that the kernels contain orientation data for the given axes ID if !(id in ephem_available_axes(eph)) throw( ArgumentError( "Orientation data for AXESID $id is not available " * "in the kernels loaded in the given FrameSystem.", ), ) end # Retrieve the parent from the ephemeris data orient_records = ephem_orient_records(eph) parentid = nothing for or in orient_records if or.target == id if isnothing(parentid) parentid = or.axes elseif parentid != or.axes throw( ErrorException( "UnambiguityError: at least two set of orientation data " * "with different centers are available for axes with ID $id.", ), ) end end end # Check that the default parent is available in the FrameSystem! if !has_axes(frames, parentid) throw( ArgumentError( "Orientation data for axes with ID $id is available " * "with respect to axes with ID $parentid, which has not yet been defined " * "in the given FrameSystem.", ), ) end return parentid end # Functions for an easier definition\handling of ephemeris axes @inline function angles_to_rot3(θ, seq::Symbol) @inbounds angle_to_dcm(θ[1], θ[2], θ[3], seq) end @inline function angles_to_rot6(θ, seq::Symbol) return ( angle_to_dcm(θ[1], θ[2], θ[3], seq), _3angles_to_δdcm(θ, seq) ) end @inline function angles_to_rot9(θ, seq::Symbol) return ( angle_to_dcm(θ[1], θ[2], θ[3], seq), _3angles_to_δdcm(θ, seq), _3angles_to_δ²dcm(θ, seq) ) end @inline function angles_to_rot12(θ, seq::Symbol) return ( angle_to_dcm(θ[1], θ[2], θ[3], seq), _3angles_to_δdcm(θ, seq), _3angles_to_δ²dcm(θ, seq), _3angles_to_δ³dcm(θ, seq) ) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
902
""" add_axes_frozen!(fr, name, id, frozen, e) Create a frozen axes version of `frozen` at epoch `e`, with `name` and `id` and add it to `frames`. !!! warning The parent axes are automatically assigned to the `frozen` parent. """ function add_axes_frozen!( fr::FrameSystem{O,T,S}, name::Symbol, id::Int, frozen, epoch::Epoch{S2} ) where {O,T,S,S2} eS = convert(S(), epoch) fixid = axes_id(fr, frozen) if !(has_axes(fr, fixid)) throw( ErrorException( "no axes with ID $frozen is registered in the given frame system" ) ) end mid = get_mappedid(axes_graph(fr), fixid) @show node = get_mappednode(axes_graph(fr), mid) parid = node.parentid # Compute rotation dcm = rotation3(fr, parid, fixid, j2000s(eS))[1] # Create new axes return add_axes_fixedoffset!(fr, name, id, parid, dcm) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1421
""" AXESID_ICRF NAIF Axes ID for the International Celestial Reference Frame (ICRF). """ const AXESID_ICRF = 1 """ AXESID_GCRF Axes ID for the Geocentric Celestial Reference Frame (GCRFF) !!! note Although the ICRF and GCRF axes are identical, they are based upon a different timescale. A different ID is here assigned to provide a robust way of distinguishing between the two. 23 has been chosen because it is one of the unassigned axes ID among the built-in SPICE frames. """ const AXESID_GCRF = 23 """ AXESID_ECL2000 NAIF Axes ID for the Mean Ecliptic Equinox of J2000 (ECL2000). """ const AXESID_ECL2000 = 17 """ AXESID_EME2000 Axes ID for the Mean Dynamical Equator and Equinox of J2000.0. !!! note In SPICE the J2000 (EME2000) and ICRF axes are considered equal, thus there exist no specific NAIF ID for the EME2000 axes. 22 has been chosen because it is the first unassigned axes ID among the built-in SPICE frames. """ const AXESID_EME2000 = 22 """ AXESID_MOONPA_DE421 NAIF axes id for the DE421 Moon Principal Axes (PA421). """ const AXESID_MOONPA_DE421 = 31006 """ AXESID_MOONME_DE421 NAIF axes id for the DE421 Moon Mean Earth/Mean Rotation axes (ME421). """ const AXESID_MOONME_DE421 = 31007 """ AXESID_MOONPA_DE440 NAIF Axes id for the DE440 Moon Principal Axes (PA440). """ const AXESID_MOONPA_DE440 = 31008
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
6561
""" DCM_MOON_PA440_TO_ME421 DCM for the rotation from the Moon Principal Axis 440 (PA440) to the Moon Mean Earth/Mean Rotation DE421 (ME421) axes. ### References - Park, S. R. et al. (2021), _The JPL Planetary and Lunar Ephemerides DE440 and DE441_, [DOI: 10.3847/1538-3881/abd414](https://doi.org/10.3847/1538-3881/abd414) """ const DCM_MOON_PA440_TO_ME421 = angle_to_dcm( arcsec2rad(-67.8526), arcsec2rad(-78.6944), arcsec2rad(-0.2785), :ZYX ) """ DCM_MOON_PA430_TO_ME430 DCM for the rotation from the Moon Principal Axis 430 (PA430) to the Moon Mean Earth/Mean Rotation DE430 (ME430) axes. ### References - Folkner M. William et al. (2014), _The Planetary and Lunar EphemeridesDE430 and DE431_ - J. G. Williams et al. (2013), _DE430 Lunar Orbit, Physical Librations, and Surface Coordinates_, [DE430 Lunar Ephemeris and Orientation](https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de430_moon_coord.pdf) """ const DCM_MOON_PA430_TO_ME430 = angle_to_dcm( arcsec2rad(-67.573), arcsec2rad(-78.58), arcsec2rad(-0.285), :ZYX ) """ DCM_MOON_PA430_TO_ME421 DCM for the rotation from the Moon Principal Axis 430 (PA430) to the Moon Mean Earth/Mean Rotation DE421 (ME421) axes. ### References - Folkner M. William et al. (2014), _The Planetary and Lunar EphemeridesDE430 and DE431_ - J. G. Williams et al. (2013), _DE430 Lunar Orbit, Physical Librations, and Surface Coordinates_, [DE430 Lunar Ephemeris and Orientation](https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de430_moon_coord.pdf) """ const DCM_MOON_PA430_TO_ME421 = angle_to_dcm( arcsec2rad(-67.737), arcsec2rad(-78.627), arcsec2rad(-0.295), :ZYX ) """ DCM_MOON_PA421_TO_ME421 DCM for the rotation from the Moon Principal Axis 421 (PA421) to the Moon Mean Earth/Mean Rotation DE421 (ME421) axes. ### References - J. G. Williams et al. (2008), _DE421 Lunar Orbit, Physical Librations, and Surface Coordinates_, [DE421 Lunar Ephemeris and Orientation](https://naif.jpl.nasa.gov/pub/naif/generic_kernels/fk/satellites/de421_lunar_ephemeris_and_orientation.pdf) """ const DCM_MOON_PA421_TO_ME421 = angle_to_dcm( arcsec2rad(-67.92), arcsec2rad(-78.56), arcsec2rad(-0.3), :ZYX ) """ add_axes_pa440!(frames, eph::AbstractEphemerisProvider, name::Symbol, id::Int=AXESID_MOONPA_DE440) Add DE440 Moon's Principal Axes (PA) axes to `frames`. The libration angles are extracted from the `eph` ephemeris kernels, an error is thrown if such orientation data is not available. !!! warning The parent axes are automatically set to the ICRF (ID = $(AXESID_ICRF)). If such axes are not registered in the frame system, an error is thrown. !!! warning To properly read the ephemeris kernels, the ID associated to the input `axes` must match NAIF's FRAME ID for the Moon PA DE440 axes ($(AXESID_MOONPA_DE440)). """ function add_axes_pa440!( frames::FrameSystem, eph::AbstractEphemerisProvider, name::Symbol, id::Int=AXESID_MOONPA_DE440 ) if !(has_axes(frames, AXESID_ICRF)) throw( ErrorException( "The DE440 Moon Principal Axes (PA) can only be defined w.r.t. the" * " ICRF (ID = $(AXESID_ICRF)), which is not defined" * " in the current frames graph." ) ) end # Throw a warning if the ID does not match the standard one. if id != AXESID_MOONPA_DE440 throw( ArgumentError( "$name is aliasing an ID that is not the standard PA440" * " ID ($(AXESID_MOONPA_DE440))." ) ) end return add_axes_ephemeris!(frames, eph, name, id, :ZXZ) end """ add_axes_pa421!(frames, eph::AbstractEphemerisProvider, name::Symbol, id::Int=AXESID_MOONPA_DE421) Add DE421 Moon's Principal Axes (PA) axes to `frames`. The libration angles are extracted from the `eph` ephemeris kernels, an error is thrown if such orientation data is not available. !!! warning The parent axes are automatically set to the ICRF (ID = $(AXESID_ICRF)). If such axes are not registered in the frame system, an error is thrown. !!! warning To properly read the ephemeris kernels, the ID associated to the input `axes` must match NAIF's FRAME ID for the Moon PA DE421 axes ($(AXESID_MOONPA_DE421)). """ function add_axes_pa421!( frames::FrameSystem, eph::AbstractEphemerisProvider, name::Symbol, id::Int=AXESID_MOONPA_DE421 ) if !(has_axes(frames, AXESID_ICRF)) throw( ErrorException( "The DE421 Moon Principal Axes (PA) can only be defined w.r.t. the" * " ICRF (ID = $(AXESID_ICRF)), which is not defined" * " in the current frames graph." ) ) end # Throw a warning if the ID does not match the standard one. if id != AXESID_MOONPA_DE421 throw( ArgumentError( "$name is aliasing an ID that is not the standard PA421" * " ID ($(AXESID_MOONPA_DE421))." ) ) end return add_axes_ephemeris!(frames, eph, name, id, :ZXZ) end """ add_axes_me421!(frames, name::Symbol, parentid::Int, axesid::Int=AXESID_MOONME_DE421) Add DE421 Moon's Mean Earth/Mean Rotation (ME) axes to `frames`. !!! warning The `parent` set of axes must either the DE440 Principal Axes (PA440, ID = $(AXESID_MOONPA_DE440)) or the DE421 Principal Axes (PA421, ID = $(AXESID_MOONPA_DE421)), otherwise an error is thrown. Depending on that, the relative axes orientation will be automatically selected by this function. """ function add_axes_me421!( frames::FrameSystem, name::Symbol, parent, id::Int=AXESID_MOONME_DE421 ) pid = axes_id(frames, parent) if pid == AXESID_MOONPA_DE421 dcm = DCM_MOON_PA421_TO_ME421 elseif pid == AXESID_MOONPA_DE440 dcm = DCM_MOON_PA440_TO_ME421 else throw( ArgumentError( "The DE421 Mean Earth/Mean Rotation (ME) axes cannot be defined w.r.t." * " axes with ID $pid. Only the DE440 (ID = $(AXESID_MOONPA_DE440))" * " or DE421 (ID = $(AXESID_MOONPA_DE421)) Moon Principal Axes are" * " accepted as parent axes.", ), ) end if id != AXESID_MOONME_DE421 @warn "$(name) is aliasing an ID that is not the standard ME421" * "ID ($(AXESID_MOONME_DE421))." end return add_axes_fixedoffset!(frames, name, id, pid, dcm) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
4537
""" add_axes_bcrtod!(fr, name, id, center; deriv=true) Add Body-Centered Rotating (BCR), True-of-Date (TOD) axes with `name` and `id` to `fr`. The center point (i.e., the reference body) is `center`. These axes are the equivalent of SPICE's `IAU_<BODY_NAME>` frames. !!! warning The parent axes are automatically set to the ICRF (ID = $(AXESID_ICRF)). If the ICRF is not defined in `fr`, an error is thrown. ### See also See also [`add_axes_rotating!`](@ref), [`add_axes_bci2000!`](@ref). """ function add_axes_bcrtod!( fr::FrameSystem, name::Symbol, id::Int, center; deriv::Bool=false ) # create val dispatch cid = point_id(fr, center) vid = Val(cid) if length(methods(body_rotational_elements, [Number, Val{cid}])) != 1 throw( MethodError( body_rotational_elements, "there must be a unique method defined for $cid" ) ) end if !(has_axes(fr, AXESID_ICRF)) throw( ErrorException( "Body-Centered Inertial (BCI) at J2000 axes can only be defined" * " w.r.t. the ICRF (ID = $(AXESID_ICRF)), which is not defined in" * " the current frames graph." ) ) end if !deriv add_axes_rotating!(fr, name, id, AXESID_ICRF, t -> _bcrtod(t, vid)) else add_axes_rotating!( fr, name, id, AXESID_ICRF, t -> _bcrtod(t, vid), t -> _∂bcrtod(t, vid), t -> _∂²bcrtod(t, vid), t -> _∂³bcrtod(t, vid) ) end end """ add_axes_bci2000!(fr, axes::AbstractFrameAxes, center, data) Add Body-Centered Inertial (BCI) axes at J2000 with `name` and `id` to `fr`. The center point (i.e., the reference body) is `center`. !!! warning The parent axes are automatically set to the ICRF (ID = $(AXESID_ICRF)). If the ICRF is not defined in `fr`, an error is thrown. ### See also See also [`add_axes_fixedoffset!`](@ref), [`add_axes_bcrtod!`](@ref). """ function add_axes_bci2000!(fr::FrameSystem, name::Symbol, id::Int, center) # create val dispatch cid = point_id(fr, center) vid = Val(cid) if length(methods(body_rotational_elements, [Number, Val{cid}])) != 1 throw( ErrorException( "there must be a unique method defined for $cid" ) ) end if !(has_axes(fr, AXESID_ICRF)) throw( ErrorException( "Body-Centered Inertial (BCI) at J2000 axes can only be defined" * " w.r.t. the ICRF (ID = $(AXESID_ICRF)), which is not defined in" * " the current frames graph." ) ) end # evaluate rotational elements and build the DCM α2000, δ2000, _ = body_rotational_elements(0, vid) dcm = angle_to_dcm(π / 2 + α2000, π / 2 - δ2000, :ZX) # insert the new axes return add_axes_fixedoffset!(fr, name, id, AXESID_ICRF, dcm) end function _bcrtod(seconds, val) α, δ, w = body_rotational_elements(seconds / CENTURY2SEC, val) return angle_to_dcm(π / 2 + α, π / 2 - δ, w, :ZXZ) end function _∂bcrtod(seconds, val) T = seconds / Tempo.CENTURY2SEC α, δ, w = body_rotational_elements(T, val) dα, dδ, dw = ∂body_rotational_elements(T, val) R = angle_to_dcm(π / 2 + α, π / 2 - δ, w, :ZXZ) dR = angle_to_δdcm((π / 2 + α, dα), (π / 2 - δ, -dδ), (w, dw), :ZXZ) return R, dR end function _∂²bcrtod(seconds, val) T = seconds / Tempo.CENTURY2SEC α, δ, w = body_rotational_elements(T, val) dα, dδ, dw = ∂body_rotational_elements(T, val) d²α, d²δ, d²w = ∂²body_rotational_elements(T, val) R = angle_to_dcm(π / 2 + α, π / 2 - δ, w, :ZXZ) dR = angle_to_δdcm((π / 2 + α, dα), (π / 2 - δ, -dδ), (w, dw), :ZXZ) d²R = angle_to_δ²dcm((π / 2 + α, dα, d²α), (π / 2 - δ, -dδ, -d²δ), (w, dw, d²w), :ZXZ) return R, dR, d²R end function _∂³bcrtod(seconds, val) T = seconds / Tempo.CENTURY2SEC α, δ, w = body_rotational_elements(T, val) dα, dδ, dw = ∂body_rotational_elements(T, val) d²α, d²δ, d²w = ∂²body_rotational_elements(T, val) d³α, d³δ, d³w = ∂³body_rotational_elements(T, val) R = angle_to_dcm(π / 2 + α, π / 2 - δ, w, :ZXZ) dR = angle_to_δdcm((π / 2 + α, dα), (π / 2 - δ, -dδ), (w, dw), :ZXZ) d²R = angle_to_δ²dcm((π / 2 + α, dα, d²α), (π / 2 - δ, -dδ, -d²δ), (w, dw, d²w), :ZXZ) d³R = angle_to_δ³dcm((π / 2 + α, dα, d²α, d³α), (π / 2 - δ, -dδ, -d²δ, -d³δ), (w, dw, d²w, d³w), :ZXZ) return R, dR, d²R, d³R end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
9222
""" add_axes_itrf!(fr::FrameSystem, name::Symbol, parentid::Int=AXESID_ICRF, id::Int=AXESID_ITRF, model::IERSModel=iers2010b) Add International Terrestrial Reference Frame (ITRF) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! warning If the ID of the parent set of `axes` is neither the ICRF (ID = $(AXESID_ICRF)) nor the GCRF (ID = $(AXESID_GCRF)), an error is thrown. """ function add_axes_itrf!( fr::FrameSystem, name::Symbol, parentid::Int=AXESID_ICRF, id::Int=AXESID_ITRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "International Terrestrial Reference Frame (ITRF) axes cannot be defined" * "with respect to axes $parentid. Only the `ICRF` (ID = $(AXESID_ICRF)) " * "or the `GCRF` (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end return add_axes_rotating!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_itrf(t, model), t -> iers_rot6_gcrf_to_itrf(t, model), t -> iers_rot9_gcrf_to_itrf(t, model), t -> iers_rot12_gcrf_to_itrf(t, model) ) end # ------------------------------------------------------------------------------------------ # Equinox-based transformations from ICRF/GCRF # ------------------------------------------------------------------------------------------ """ add_axes_mod!(fr, name::Symbol, axesid::Int, parentid::Int, model::IERSConventions.IERSModel=iers2010b) Add Mean Equator and Equinox of Date (MOD) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! note The Mean-of-Date axes are obtained by applying the frame bias and precession matrix. For this reason, if the IERS 1996 conventions are used, the rotation is actually computed starting from the EME2000 rather than the GCRF. !!! note Despite this class of axes has a rotation matrix that depends on time, its derivatives are assumed null. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_mod!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "Mean-of-Date (MOD) axes cannot be defined with respect to axes $parentid." * " Only the ICRF (ID = $(AXESID_ICRF)) or the GCRF" * " (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end return add_axes_projected!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_mod(t, model) ) end """ add_axes_tod!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b) Add True Equator of Date (TOD) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! note The True-of-Date axes are obtained by applying the frame bias, precession and nutation matrix. For this reason, if the IERS 1996 conventions are used, the rotation is actually computed starting from the EME2000 rather than the GCRF. !!! note Despite this class of axes has a rotation matrix that depends on time, its derivatives are assumed null. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_tod!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "True-of-Date (TOD) axes cannot be defined with respect to axes $parentid." * " Only the ICRF (ID = $(AXESID_ICRF)) or the GCRF" * " (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end return add_axes_projected!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_tod(t, model) ) end """ add_axes_gtod!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b) Add Greenwich True-of-Date (GTOD) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! note Despite this class of axes has a rotation matrix that depends on time, its derivatives are assumed null. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_gtod!( fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "Greenwich True-of-Date (GTOD) axes cannot be defined with respect to axes" * " $parentid. Only the ICRF (ID = $(AXESID_ICRF)) or the GCRF" * " (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end # TODO: check if inertial is right return add_axes_projected!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_gtod(t, model) ) end """ add_axes_pef!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b) Add Pseudo-Earth Fixed (PEF) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_pef!( fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "Pseudo-Earth Fixed (PEF) axes cannot be defined with respect to" * " axes $parentid. Only the ICRF (ID = $(AXESID_ICRF)) or the GCRF" * " (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end # TODO: PEF axes use AD for higher-order derivatives return add_axes_rotating!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_pef(model, t) ) end # ------------------------------------------------------------------------------------------ # CIO-based transformations from ICRF/GCRF # ------------------------------------------------------------------------------------------ """ add_axes_cirf!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b) Add Celestial Intermediate Reference Frame (CIRF) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! note Despite this class of axes has a rotation matrix that depends on time, its derivatives are assumed null. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_cirf!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "The Celestial Intermediate Reference Frame (CIRF) axes cannot be defined" * " with respect to axes $parentid. Only the ICRF (ID = $(AXESID_ICRF)) or" * " the GCRF (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end # TODO: check if inertial is right return add_axes_projected!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_cirf(t, model) ) end """ add_axes_tirf!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b) Add Terrestrial Intermediate Reference Frame (TIRF) axes to `fr`. Use the `model` argument to specify which IERS convention should be used for the computations. !!! note Despite this class of axes has a rotation matrix that depends on time, its derivatives are assumed null. !!! warning The ID of the `parent` set of axes must be $(AXESID_ICRF) (ICRF) or $(AXESID_GCRF) (GCRF) otherwise an error is thrown. """ function add_axes_tirf!(fr::FrameSystem, name::Symbol, id::Int, parentid::Int=AXESID_ICRF, model::IERSModel=iers2010b ) if !(parentid in (AXESID_ICRF, AXESID_GCRF)) throw( ArgumentError( "The Terrestrial Intermediate Reference Frame (TIRF) axes cannot be defined" * " with respect to axes $parentid. Only the ICRF (ID = $(AXESID_ICRF)) or" * " the GCRF (ID = $(AXESID_GCRF)) are accepted as parent axes.", ), ) end # TODO: check if inertial is right return add_axes_projected!( fr, name, id, parentid, t -> iers_rot3_gcrf_to_tirf(t, model) ) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
2703
""" add_axes_topocentric!(frames, name::Symbol, id::Int, parent, λ, ϕ, mount) Add topocentric axes to `frames` at a specified location and mounting. The orientation relative to the parent axes `parent` is defined throuh the longitude `λ`, the geodetic latitude `ϕ` and the mounting type `mount`, which may be any of the following: - `:NED` (North, East, Down): the X-axis points North, the Y-axis is directed eastward and the Z-axis points inwards towards the nadir. - `:SEZ` (South, East, Zenith): the X-axis points South, the Y-axis is directed East, and the Z-axis points outwards towards the zenith. - `:ENU` (East, North, Up): the X-axis points East, the Y-axis is directed North and the Z-axis points outwards towards the zenith. !!! warning The parent axes must be a set of body-fixed reference axes. This is under user resposibility. """ function add_axes_topocentric!( frames::FrameSystem, name::Symbol, id::Int, parent, λ::Number, ϕ::Number, mount::Symbol ) if mount == :NED dcm = angle_to_dcm(λ, -ϕ - π / 2, :ZY) elseif mount == :SEZ dcm = angle_to_dcm(λ, π / 2 - ϕ, :ZY) elseif mount == :ENU dcm = angle_to_dcm(λ + π / 2, π / 2 - ϕ, :ZX) else throw(ArgumentError("$mount is not a supported topocentric mounting type.")) end pid = axes_id(frames, parent) return add_axes_fixedoffset!(frames, name, id, pid, dcm) end @fastmath function _geod2pos(h::Number, λ::Number, ϕ::Number, R::Number, f::Number) # Get eccentricity from flattening e² = (2 - f) * f sϕ, cϕ = sincos(ϕ) sλ, cλ = sincos(λ) d = R / sqrt(1 - e² * sϕ^2) c = (d + h) * cϕ s = (1 - e²) * d return SA[c*cλ, c*sλ, (s+h)*sϕ] end """ add_point_surface!(frames, name::Symbol, pointid::Int, parent, axes, λ::Number, ϕ::Number, R::Number, f::Number=0.0, h::Number=0.0) Add `point` to `frames` as a fixed point on the surface of the `parent` point body. The relative position is specified by the longitude `λ`, the geodetic latitude `ϕ`, the reference radius of the ellipsoid `R` and its flattening `f`. The altitude over the reference surface of the ellipsoid `h` defaults to 0. !!! warning Axes used here must be a set of body-fixed reference axes for the body represented by `parentid`. This is under user resposibility. """ function add_point_surface!( frames::FrameSystem, name::Symbol, id::Int, parent, axes, λ::Number, ϕ::Number, R::Number, f::Number=0.0, h::Number=0.0, ) pos = _geod2pos(h, λ, ϕ, R, f) pid = point_id(frames, parent) axid = axes_id(frames, axes) return add_point_fixedoffset!(frames, name, id, pid, axid, pos) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
241
const GROUP = get(ENV, "GROUP", "All") @time begin if GROUP == "All" || GROUP == "Core" include("Core/Core.jl") end if GROUP == "All" || GROUP == "Definitions/" include("Definitions/Definitions.jl") end end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
329
using Test using SafeTestsets @testset "Core" verbose=true begin @safetestset "Translation" begin include("translation.jl") end @safetestset "Rotation" begin include("rotation.jl") end @safetestset "Graph" begin include("graph.jl") end @safetestset "Transform (generic)" begin include("transform.jl") end end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1479
using FrameTransformations using Tempo using StaticArrays using Test @testset "Point node" begin begin fps = FrameTransformations.FramePointFunctions{1, Float64}() fp = FrameTransformations.FramePointNode{1, Float64}(:P0, 1, 0, 1, fps) @test fp.name == :P0 @test fp.id == 1 @test fp.parentid == 0 @test fp.axesid == 1 @test fp.f === fps end begin f1(t) = Translation{2}(SA[cos(t), sin(t), 1.0]) f2(t) = Translation{2}(SA[cos(t), sin(t), 1.0, -sin(t), cos(t), 0.0]) fps = FrameTransformations.FramePointFunctions{2, Float64}(f1, f2) @test f1(π/3) == fps[1].fw[1](π/3) @test f2(π/3) == fps[2].fw[1](π/3) @test f1(0)[2] == zeros(3) end end; @testset "Axes node" begin begin faxs = FrameTransformations.FrameAxesFunctions{1, Float64}() fax = FrameTransformations.FrameAxesNode{1, Float64}(:Ax0, 1, 1, faxs) @test fax.name == :Ax0 @test fax.id == 1 @test fax.parentid == 1 @test fax.f === faxs end end; @testset "FrameSystem" begin g = FrameSystem{2, Float64}() @test order(g) == 2 @test FrameTransformations.timescale(g) == BarycentricDynamicalTime @test points_graph(g) === g.points.graph @test axes_graph(g) === g.axes.graph @test points_alias(g) === g.points.alias @test axes_alias(g) === g.axes.alias @test !has_point(g, 1) @test !has_axes(g, 1) end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
4191
using FrameTransformations using ReferenceFrameRotations using LinearAlgebra using StaticArrays using Test @test FrameTransformations.dcm_eltype(DCM{Float64}) == Float64 @test FrameTransformations.promote_dcm_eltype(Tuple{DCM{Int64}, DCM{Float64}}) == Float64 dcm = angle_to_dcm(π/3, :Z) δdcm = DCM(ddcm(dcm, [0, 0, 1])) δ²dcm = DCM(ddcm(δdcm, [0, 0, 1])) r1 = Rotation(dcm, δdcm, δ²dcm) @test order(r1) == 3 @test size(r1) == (3,) @test length(r1) == 3 @test r1[1] == dcm @test r1[2] == δdcm @test r1[3] == δ²dcm @test r1 == Rotation((dcm, δdcm, δ²dcm)) r2 = Rotation{1}(dcm, δdcm, δ²dcm) @test length(r2) == 1 @test r2[1] == dcm r3 = Rotation{1}((dcm, δdcm, δ²dcm)) @test length(r3) == 1 @test r3[1] == dcm @test r2 == r3 r4 = Rotation{2}(1.0I) @test length(r4) == 2 @test r4[1] == I @test r4[2] == 0I r5 = Rotation{3, Float64}(I) @test length(r5) == 3 @test r5[1] == I @test r5[2] == 0I @test r5[3] == 0I r6 = Rotation{1}(r1) @test length(r6) == 1 @test r6[1] == dcm r7 = Rotation{2}(r6) @test length(r7) == 2 @test r7[1] == dcm @test r7[2] == 0I r8 = Rotation{1, Float32}(r5) @test length(r8) == 1 @test r8[1] == I r9 = Rotation{1, Float64}(I) @test Tuple(r9) == (1, 0, 0, 0, 1, 0, 0, 0, 1) @test SVector(r9) == [1, 0, 0, 0, 1, 0, 0, 0, 1] @test inv(r9) == r9 @test inv(r6)[1] == adjoint(dcm) @test_throws DimensionMismatch r6*r7 r10 = r9*r6 @test r10 == r6 @testset "Constructors" begin # Default constructor R = Rotation((DCM(1I), DCM(0.0I))) @test R[1] == DCM(1I) @test R.m[2] == DCM(0I) @test typeof(R) == Rotation{2,Float64} # dcms constructor A = angle_to_dcm(π / 3, :Z) B = DCM(0.0I) C = DCM(1.0I) R = Rotation(A, B, C) @test length(R) == 3 @test typeof(R) == Rotation{3,Float64} for (i, M) in enumerate([A, B, C]) @test R[i] == M end # filter constructor R = Rotation{2}(A, B, C) @test typeof(R) == Rotation{2,Float64} @test R[1] == A @test R[2] == B @test length(R) == 2 R = Rotation{5}(A, B, C) @test typeof(R) == Rotation{5,Float64} @test length(R) == 5 for (i, M) in enumerate([A, B, C, DCM(0.0I), DCM(0.0I)]) @test R[i] == M end # UniformScaling R = Rotation{1}(1.0I) @test R[1] == C @test typeof(R) == Rotation{1,Float64} R = Rotation{3,Int64}(I) @test typeof(R) == Rotation{3,Int64} R[1] == DCM(1I) R[2] == DCM(0I) R[3] == DCM(0I) # Rotation conversion R = Rotation(A, B, C) R2 = Rotation{1}(R) @test R2[1] == A # DCM + omega R = Rotation(A, SA[0.0, 0.0, 1.0]) @test DCM(ddcm(A, SA[0.0, 0.0, 1.0])) == R[2] end @testset "Operations" begin θ = rand(0:(π / 100):(2π)) A = angle_to_dcm(θ, :Z) R = Rotation(A) Ri = Rotation(A') R₂ = Rotation(A, DCM(0.0I)) # Compose rotation @test_throws DimensionMismatch R * R₂ @test (R * Ri)[1] ≈ Rotation{1}(1.0I)[1] @test FrameTransformations._compose_rotation(R, Ri)[1] ≈ (R * Ri)[1] # Apply rotation @testset "apply_rotation" begin t = Translation(1., 0., 0., 0., 1., 0., -1., 0., 0.) r1 = Rotation{1, Float64}(I) @test_throws DimensionMismatch r1 * t r2 = Rotation{3}(r1) @test r2 * t == t v = SA[1., 0., 0., 0., 1., 0., -1., 0., 0.] @test r2 * v == v @test_throws DimensionMismatch r2 * (@SVector zeros(12)) dcm = angle_to_dcm(π/3, :Z) r = Rotation(dcm, dcm, dcm) rt = r * t v1 = r[1] * t[1] v2 = r[2] * t[1] + r[1] * t[2] v3 = r[3] * t[1] + 2 * r[2] * t[2] + r[1] * t[3] @test rt[1] == v1 @test rt[2] == v2 @test rt[3] == v3 end @test FrameTransformations._apply_rotation(R, SA[1.0, 0.0, 0.0]) ≈ R * SA[1.0, 0.0, 0.0] # 2nd order rotations A = angle_to_dcm(rand(), :Z) B = angle_to_dcm(rand(), rand(), rand(), :XYZ) C = angle_to_dcm(rand(), rand(), :YX) D = angle_to_dcm(rand(), :X) RA = Rotation(A, B) RC = Rotation(C, D) RO = RA * RC @test RO[1] ≈ A * C atol = 1e-12 @test RO[2] ≈ A * D + B * C atol = 1e-12 @test typeof(RO) == Rotation{2,Float64} end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1106
using FrameTransformations using ReferenceFrameRotations using StaticArrays using ForwardDiff using Test @testset "FrameSystem" begin fr = FrameSystem{4, Float64}() add_axes!(fr, :ICRF, 1) r(t) = angle_to_dcm(t, :Z) dr(t) = ForwardDiff.derivative(r, t) d2r(t) = ForwardDiff.derivative(dr, t) d3r(t) = ForwardDiff.derivative(d2r, t) add_axes_rotating!(fr, :Test, 2, 1, r) f(t) = SVector(cos(t), sin(t), 1.0) df(t) = ForwardDiff.derivative(f, t) d2f(t) = ForwardDiff.derivative(df, t) d3f(t) = ForwardDiff.derivative(d2f, t) add_point!(fr, :ROOT, 1, 1) add_point_dynamical!(fr, :Test, 2, 1, 1, f) x = π/3 @test vector3(fr, 1, 2, 1, x) == f(x) @test vector6(fr, 1, 2, 1, x) == vcat( f(x), df(x) ) @test vector9(fr, 1, 2, 1, x) == vcat( f(x), df(x), d2f(x) ) @test vector12(fr, 1, 2, 1, x) == vcat( f(x), df(x), d2f(x), d3f(x) ) x = π/3 @test rotation3(fr, 1, 2, x)[1] == r(x) @test rotation6(fr, 1, 2, x)[2] == dr(x) @test rotation9(fr, 1, 2, x)[3] == d2r(x) @test rotation12(fr, 1, 2, x)[4] == d3r(x) end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1765
using FrameTransformations using StaticArrays using Test # SVector3 @test FrameTransformations.svector3_eltype(FrameTransformations.SVector3{Float64}) == Float64 vft1 = FrameTransformations.SVector3(1.,2.,3.) vit1 = FrameTransformations.SVector3(4, 5, 6) @test FrameTransformations.svector3_eltype(vft1) == Float64 @test FrameTransformations.svector3_eltype(vit1) == Int64 @test FrameTransformations.promote_svector3_eltype((vft1, vit1)) == Float64 # Basic ctor t = Translation((vft1, vit1)) @test t[1] == vft1 @test t[2] == vit1 @test size(t) == (2,) @test length(t) == 2 @test keys(t) == Base.OneTo(2) @test order(t) == 2 # Varargs constructor @test t == Translation(1,2,3,4,5,6.) @test_throws DimensionMismatch Translation(1,2.) # Convert to Tuple @test Tuple(t) == (1,2,3,4,5,6) # Convert to SVector @test SVector(t) == SA[1,2,3,4,5,6] @test_throws DimensionMismatch Translation{1}(SA[1,2]) # Empty constructor t0 = Translation{3, Float64}() @test t0[1] == zeros(3) @test t0[2] == zeros(3) @test t0[3] == zeros(3) # Convert to a different order auto-fill of missing SVector3 t2 = Translation{1}(t) @test length(t2) == 1 @test t2[1] == vft1 t3 = Translation{3}(t2) @test length(t3) == 3 @test_throws DimensionMismatch t3 == t2 @test t3[2] == zeros(3) @test t3[3] == zeros(3) t4 = Translation{1}(SA[1,2,3]) @test length(t4) == 1 @test t4[1] == [1,2,3] t5 = Translation{2}(SA[1,2,3]) @test length(t5) == 2 @test t5[2] == zeros(3) t6 = t4 - t4 @test t6[1] == zeros(3) t7 = t5 - t4 @test length(t7) == 2 @test t7[1] == zeros(3) @test t7[2] == zeros(3) @test t4 - t5 == t5 - t4 t8 = t2 + t0 @test length(t8) == 3 @test t8[1] == [1,2,3] @test t8[2] == zeros(3) @test t8[3] == zeros(3) t9 = t0 + t2 @test t8 == t9 t10 = -t2 @test t10[1] == [-1, -2, -3]
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1546
using RemoteFiles using Test using SafeTestsets @RemoteFileSet KERNELS "Spice Kernels Set" begin LEAP = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" dir = joinpath( @__DIR__, "..", "assets" ) DE432 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de432s.bsp" dir = joinpath( @__DIR__, "..", "assets" ) PA440 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/moon_pa_de440_200625.bpc" dir = joinpath( @__DIR__, "..", "assets" ) PA421 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/moon_pa_de421_1900-2050.bpc" dir = joinpath( @__DIR__, "..", "assets" ) FK_DE440 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/fk/satellites/moon_de440_220930.tf" dir = joinpath( @__DIR__, "..", "assets" ) end; download(KERNELS; verbose=true, force=false) @testset "Definitions" verbose = true begin @safetestset "Celestial" begin include("celestial.jl") end @safetestset "Ecliptic" begin include("ecliptic.jl") end @safetestset "Frozen" begin include("frozen.jl") end @safetestset "Ephemeris" begin include("ephemeris.jl") end @safetestset "Planetary" begin include("planetary.jl") end @safetestset "Lunar" begin include("lunar.jl") end @safetestset "Directions" begin include("directions.jl") include("twodir.jl") end end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
1274
using Test using LinearAlgebra using FrameTransformations using ReferenceFrameRotations frames = FrameSystem{3,Float64}() # Add ICRF axes @test_nowarn add_axes!(frames, :Root, 12) # test that GCRF can be defined only as child of ICRF @test_throws ArgumentError add_axes_gcrf!(frames) frames = FrameSystem{3,Float64}() # Add ICRF axes @test_nowarn add_axes!(frames, :ICRF, 1) # test that ICRF can only be added as a root axes @test_throws ArgumentError add_axes_icrf!(frames) # Test GCRF can be added as child of ICRF @test_nowarn add_axes_gcrf!(frames) frames = FrameSystem{3, Float64}() add_axes_icrf!(frames) node = axes_graph(frames).nodes[1] @test node.id == AXESID_ICRF @test node.name == :ICRF add_axes_gcrf!(frames) node = axes_graph(frames).nodes[2] @test node.id == AXESID_GCRF @test node.name == :GCRF # Test they have an identity rotation R = rotation6(frames, 1, 23, 0.0) @test R[1] ≈ DCM(1.0I) atol=1e-12 rtol=1e-12 @test R[2] ≈ DCM(0.0I) atol=1e-12 rtol=1e-12 # Test GCRF as root axes frames = FrameSystem{3, Float64}() add_axes_gcrf!(frames) node = axes_graph(frames).nodes[1] @test node.id == AXESID_GCRF @test node.name == :GCRF # Test EME frames = FrameSystem{3, Float64}() add_axes_icrf!(frames) add_axes_eme2000!(frames, :EME, 1, 4)
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
2196
using FrameTransformations using Ephemerides using RemoteFiles using Test using LinearAlgebra @RemoteFileSet KERNELS "Spice Kernels Set" begin LEAP = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" dir = joinpath( @__DIR__, "..", "assets" ) DE432 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de432s.bsp" dir = joinpath( @__DIR__, "..", "assets" ) end; download(KERNELS; verbose=true, force=false) frames = FrameSystem{4,Float64}() add_axes_icrf!(frames) eph = EphemerisProvider(path(KERNELS[:DE432])) add_point!(frames, :SSB, 0, 1) add_point_alias!(frames, :SSB, :SolarSystemB) add_point_ephemeris!(frames, eph, :Sun, 10) add_point_ephemeris!(frames, eph, :EarthB, 3) add_point_ephemeris!(frames, eph, :Earth, 399) @testset "Position" verbose = false begin add_direction_position!(frames, :SunEarth, :Sun, :Earth, :ICRF) for _ = 1:100 e = rand(0:1e8) ref = vector3(frames, :Sun, :Earth, :ICRF, e) ref /= norm(ref) val = direction3(frames, :SunEarth, :ICRF, e) @test dot(val, ref) ≈ 1.0 end end @testset "Velocity" verbose = false begin add_direction_velocity!(frames, :SunEarthVel, :Sun, :Earth, :ICRF) for _ = 1:100 e = rand(0:1e8) @views ref = vector6(frames, :Sun, :Earth, :ICRF, e)[4:end] ref /= norm(ref) val = direction3(frames, :SunEarthVel, :ICRF, e) @test dot(val, ref) ≈ 1.0 end end @testset "Orthogonal" verbose = false begin add_direction_orthogonal!(frames, :SunEarthMom, :SunEarth, :SunEarthVel, :ICRF) for _ = 1:100 e = rand(0:1e8) p, v = Translation(vector6(frames, :Sun, :Earth, :ICRF, e)...) p /= norm(p) v /= norm(v) ref = cross(p, v) ref /= norm(ref) val = direction3(frames, :SunEarthMom, :ICRF, e) @test dot(val, ref) ≈ 1.0 end end @testset "Fixed" verbose = false begin add_direction_fixed!(frames, :Fix, :ICRF, [1.0, 0.0, 0.0]) for _ = 1:100 e = rand(0:1e8) val = direction3(frames, :Fix, :ICRF, e) @test val[1] ≈ 1.0 end end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
2073
using Test using SPICE using LinearAlgebra using FrameTransformations using ReferenceFrameRotations v2as = (x, y) -> acosd(max(-1, min(1, dot(x / norm(x), y / norm(y))))) * 3600 ICRF = 1 EME2000 = 22 ECL2000 = 17 ICRF_TEST = 1 EME_TEST = -10000000 @testset "EME 2000" verbose = false begin frames = FrameSystem{3, Float64}() add_axes!(frames, :Test, EME_TEST) # Check that you can't add meme2000 to a random axes @test_throws ArgumentError add_axes_eme2000!(frames, :EME, EME_TEST) # Test rotation matrix from ICRF to EME2000 frames = FrameSystem{3,Float64}() add_axes_icrf!(frames) add_axes_eme2000!(frames, :EME) R = rotation9(frames, ICRF, EME2000, rand()) v = rand(BigFloat, 3) v /= norm(v) @test v2as(R[1] * v, FrameTransformations.DCM_ICRF_TO_EME2000 * v) ≈ 0.0 atol = 1e-14 rtol = 1e-14 @test maximum(abs.(R[2])) ≈ 0.0 atol = 1e-14 rtol = 1e-14 @test maximum(abs.(R[3])) ≈ 0.0 atol = 1e-14 rtol = 1e-14 end @testset "ECL 2000" verbose = false begin frames = FrameSystem{3, Float64}() add_axes!(frames, :Test, EME_TEST) # Check that you can't add eclipj2000 to a random axes @test_throws ArgumentError add_axes_ecl2000!(frames, :ECL, EME_TEST) f1 = FrameSystem{3,Float64}() f2 = FrameSystem{3,Float64}() # Test Rotation from EME2000 to ECL2000 # Note: SPICE defines this rotation using the obliquity of # the ecliptic taken from the IAU 1976/1980 Theory of Nutation add_axes_icrf!(f1) add_axes_eme2000!(f1, :EME) add_axes_ecl2000!(f1, :ECL) add_axes!(f2, :EME, EME2000) add_axes_ecl2000!(f2, :ECL, EME2000, ECL2000) # Test that ECL2000 is defined correctly with both ICRF and # EME2000 as parents! for frames in (f1, f2) ep = rand(0.0:1e7) R = sxform("J2000", "ECLIPJ2000", ep) R_ = rotation6(frames, EME2000, ECL2000, ep) v = rand(BigFloat, 3) v /= norm(v) @test v2as(R[1:3, 1:3] * v, R_[1] * v) ≈ 0.0 atol = 1e-6 @test R_[2] ≈ zeros(3, 3) atol = 1e-14 end end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
2746
using FrameTransformations using StaticArrays using LinearAlgebra using SPICE using RemoteFiles using Test using Tempo using JSMDInterfaces.Ephemeris using Ephemerides @RemoteFileSet KERNELS "Spice Kernels Set" begin LEAP = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" dir = joinpath( @__DIR__, "..", "assets" ) DE432 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de432s.bsp" dir = joinpath( @__DIR__, "..", "assets" ) end; download(KERNELS; verbose=true, force=false) @testset "Interface" verbose = false begin frames = FrameSystem{2,Float64}() add_axes_icrf!(frames) @test_throws Exception add_point_ephemeris!(frames, eph, :Sun, 10) @test_throws Exception add_axes_ephemeris!(frames, eph, :Sun, 10, :XYZ, 1) eph = EphemerisProvider(path(KERNELS[:DE432])) add_point!(frames, :SolarSystemBarycenter, 0, 1) add_point_ephemeris!(frames, eph, :Sun, 10) add_point_ephemeris!(frames, eph, :EarthB, 3) add_point_ephemeris!(frames, eph, :Earth, 399) frames2 = FrameSystem{2,Float64}() add_axes_icrf!(frames2) book = Dict( 0 => :SolarSystemBarycenter, 10 => :Sun, 3 => :EarthB, 399 => :Earth ) @test_nowarn add_point_ephemeris!(frames2, eph, book) @test points_alias(frames) == points_alias(frames2) @test_throws Exception FrameTransformations.check_point_ephemeris(frames, eph, -1) frames = FrameSystem{2,Float64}() add_axes_icrf!(frames) @test_throws Exception FrameTransformations.check_point_ephemeris(frames, eph, 10) frames = FrameSystem{2,Float64}() @test_throws Exception FrameTransformations.check_point_ephemeris(frames, eph, 0) frames = FrameSystem{2,Float64}() @test_throws Exception FrameTransformations.check_axes_ephemeris(frames, eph, -1) end; @testset "EphemeridesExt" verbose = false begin kclear() frames = FrameSystem{4,Float64}() add_axes_icrf!(frames) eph = EphemerisProvider(path(KERNELS[:DE432])) add_point!(frames, :SolarSystemBarycenter, 0, 1) add_point_ephemeris!(frames, eph, :Sun, 10) add_point_ephemeris!(frames, eph, :EarthB, 3) add_point_ephemeris!(frames, eph, :Earth, 399) furnsh(path(KERNELS[:DE432])) for _ in 1:100 e = rand(0:1e9) pv_, lt_ = spkezr("EARTH", e, "J2000", "NONE", "SUN") pv = vector6(frames, 10, 399, 1, e) @test norm(pv[1:3] - pv_[1:3]) ≈ 0.0 atol = 1e-6 @test norm(pv[4:end] - pv_[4:end]) ≈ 0.0 atol = 1e-9 end @test_nowarn vector3(frames, 10, 399, 1, 1.0) @test_nowarn vector9(frames, 10, 399, 1, 1.0) @test_nowarn vector12(frames, 10, 399, 1, 1.0) kclear() end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
532
using FrameTransformations using ReferenceFrameRotations using LinearAlgebra using Tempo using Test frames = FrameSystem{4, Float64}() add_axes_icrf!(frames) add_axes_ecl2000!(frames) e = Epoch("2022-01-01T12:00:00.0000 UTC") @test_nowarn add_axes_frozen!(frames, :FROZEN, -17, 17, e) eTDB = convert(TDB, e) R0 = rotation3(frames, :ICRF, :ECL2000, eTDB) R = rotation3(frames, :ICRF, :FROZEN, eTDB) @test R == R0 R = rotation12(frames, :ICRF, :FROZEN, eTDB) @test R[2] ≈ DCM(0.0I) @test R[3] ≈ DCM(0.0I) @test R[4] ≈ DCM(0.0I)
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
3140
using FrameTransformations using StaticArrays using LinearAlgebra using SPICE using RemoteFiles using Test using Tempo using JSMDInterfaces.Ephemeris using Ephemerides @RemoteFileSet KERNELS "Spice Kernels Set" begin LEAP = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" dir = joinpath( @__DIR__, "..", "assets" ) DE432 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de432s.bsp" dir = joinpath( @__DIR__, "..", "assets" ) PA421 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/moon_pa_de421_1900-2050.bpc" dir = joinpath( @__DIR__, "..", "assets" ) PA440 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/moon_pa_de440_200625.bpc" dir = joinpath( @__DIR__, "..", "assets" ) FK_DE421 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/fk/satellites/moon_080317.tf" dir = joinpath( @__DIR__, "..", "assets" ) FK_DE440 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/fk/satellites/moon_de440_220930.tf" dir = joinpath( @__DIR__, "..", "assets" ) end; download(KERNELS; verbose=true, force=false) v2as = (x, y) -> acosd(max(-1, min(1, dot(x / norm(x), y / norm(y))))) * 3600 @testset "DE421" verbose = false begin for kernel in (:LEAP, :PA421, :FK_DE421) furnsh(path(KERNELS[kernel])) end frames = FrameSystem{2,Float64}() add_axes_icrf!(frames) eph = EphemerisProvider(path(KERNELS[:PA421])) @test_throws ArgumentError add_axes_pa421!(frames, eph, :PA421, -1) @test_throws ArgumentError add_axes_me421!(frames, :ME421, -1) @test_throws ArgumentError add_axes_me421!(frames, :ME421, 31006) add_axes_pa421!(frames, eph, :PA421) add_axes_me421!(frames, :ME421, :PA421) for _ in 1:100 et = rand(0.0:1e8) v = rand(BigFloat, 3) v /= norm(v) # Test PA421! Rb = rotation6(frames, :PA421, :ICRF, et) Rs = sxform("MOON_PA", "J2000", et) @test v2as(Rb[1] * v, Rs[1:3, 1:3] * v) ≤ 1e-6 @test v2as(Rb[2] * v, Rs[4:6, 1:3] * v) ≤ 1e-6 # Test ME421! Rb = rotation6(frames, :ICRF, :ME421, et) Rs = sxform("J2000", "MOON_ME", et) @test v2as(Rb[1] * v, Rs[1:3, 1:3] * v) ≤ 1e-6 @test v2as(Rb[2] * v, Rs[4:6, 1:3] * v) ≤ 1e-6 end end @testset "DE440" verbose = false begin for kernel in (:LEAP, :PA440, :FK_DE440) furnsh(path(KERNELS[kernel])) end frames = FrameSystem{2,Float64}() add_axes_icrf!(frames) eph = EphemerisProvider(path(KERNELS[:PA440])) @test_throws ArgumentError add_axes_pa440!(frames, eph, :PA440, -1) add_axes_pa440!(frames, eph, :PA440) for _ in 1:100 et = rand(0.0:1e8) v = rand(BigFloat, 3) v /= norm(v) # Test PA421! Rb = rotation6(frames, :PA440, :ICRF, et) Rs = sxform("MOON_PA", "J2000", et) @test v2as(Rb[1] * v, Rs[1:3, 1:3] * v) ≤ 1e-6 @test v2as(Rb[2] * v, Rs[4:6, 1:3] * v) ≤ 1e-6 end end
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
921
using FrameTransformations using ReferenceFrameRotations using LinearAlgebra using JSMDInterfaces.Bodies using Test function Bodies.body_rotational_elements(::Number, ::Val{-1}) return -pi / 2, pi / 2, 0.0 end frames = FrameSystem{4,Float64}() @test_throws Exception add_axes_bci2000!(frames, :BCI, -1, -1) @test_throws Exception add_axes_bcrtod!(frames, :BCR, -2, -1) add_axes_icrf!(frames) @test_nowarn add_axes_bci2000!(frames, :BCI, -1, -1) R = rotation12(frames, :ICRF, :BCI, 12.345) @test R[1] ≈ DCM(1.0I) @test R[2] ≈ DCM(0.0I) @test R[3] ≈ DCM(0.0I) @test R[4] ≈ DCM(0.0I) @test_nowarn add_axes_bcrtod!(frames, :BCR, -2, -1; deriv=false) R = rotation12(frames, :ICRF, :BCR, 12.345) @test R[1] ≈ DCM(1.0I) @test R[2] ≈ DCM(0.0I) @test R[3] ≈ DCM(0.0I) @test R[4] ≈ DCM(0.0I) @test_throws Exception add_axes_bci2000!(frames, :BCR, -2, -10) @test_throws Exception add_axes_bcrtod!(frames, :BCR, -2, -10)
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
code
3186
using FrameTransformations using Ephemerides using RemoteFiles using Test using LinearAlgebra using StaticArrays @RemoteFileSet KERNELS "Spice Kernels Set" begin LEAP = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" dir = joinpath( @__DIR__, "..", "assets" ) DE432 = @RemoteFile "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de432s.bsp" dir = joinpath( @__DIR__, "..", "assets" ) end; download(KERNELS; verbose=true, force=false) atol = 1e-8 # Define two non parallel vectors and their 1st, 2nd and 3rd order time derivatives! function get_v1(t) return SA[cos(3t), t*sin(t), t^2*cos(t)] end get_v2(t) = SA[t^3, t^2, t] @testset "Sequence assembly" begin for _ = 1:100 θ = rand() a, b = get_v1(θ)[1:3], get_v2(θ)[1:3] c = cross(a, b) aᵤ, bᵤ, cᵤ = a / norm(a), b / norm(b), c / norm(c) # XY R = FrameTransformations.twodir_to_dcm(a, b, :XY) @test R' * [1, 0, 0] ≈ aᵤ atol = atol @test R' * [0, 0, 1] ≈ cᵤ atol = atol @test dot(R' * [0, 1, 0], aᵤ) ≈ 0 atol = atol # YX R = FrameTransformations.twodir_to_dcm(a, b, :YX) @test R' * [0, 1, 0] ≈ aᵤ atol = atol @test R' * [0, 0, 1] ≈ -cᵤ atol = atol @test dot(R' * [1, 0, 0], aᵤ) ≈ 0 atol = atol # XZ R = FrameTransformations.twodir_to_dcm(a, b, :XZ) @test R' * [1, 0, 0] ≈ aᵤ atol = atol @test R' * [0, 1, 0] ≈ -cᵤ atol = atol @test dot(R' * [0, 1, 0], aᵤ) ≈ 0 atol = atol # ZX R = FrameTransformations.twodir_to_dcm(a, b, :ZX) @test R' * [0, 0, 1] ≈ aᵤ atol = atol @test R' * [0, 1, 0] ≈ cᵤ atol = atol @test dot(R' * [1, 0, 0], aᵤ) ≈ 0 atol = atol # YZ R = FrameTransformations.twodir_to_dcm(a, b, :YZ) @test R' * [0, 1, 0] ≈ aᵤ atol = atol @test R' * [1, 0, 0] ≈ cᵤ atol = atol @test dot(R' * [0, 0, 1], aᵤ) ≈ 0 atol = atol # ZY R = FrameTransformations.twodir_to_dcm(a, b, :ZY) @test R' * [0, 0, 1] ≈ aᵤ atol = atol @test R' * [1, 0, 0] ≈ -cᵤ atol = atol @test dot(R' * [0, 1, 0], aᵤ) ≈ 0 atol = atol end end; @testset "Frames" begin frames = FrameSystem{4,Float64}() add_axes_icrf!(frames) eph = EphemerisProvider(path(KERNELS[:DE432])) add_point!(frames, :SSB, 0, 1) add_point_ephemeris!(frames, eph, :Sun, 10) add_point_ephemeris!(frames, eph, :EarthB, 3) add_point_ephemeris!(frames, eph, :Earth, 399) add_direction_position!(frames, :SunEarthPos, :Sun, :Earth, :ICRF) add_direction_velocity!(frames, :SunEarthVel, :Sun, :Earth, :ICRF) add_axes_twodir!(frames, :SunEarthRot, 2, :ICRF, :SunEarthPos, :SunEarthVel, :XY) @test_throws ArgumentError add_axes_twodir!(frames, :SunEarthRot, 2, :ICRF, :A, :SunEarthVel, :XY) @test_throws ArgumentError add_axes_twodir!(frames, :SunEarthRot, 2, :ICRF, :SunEarthPos, :B, :XY) for _ = 1:100 e = rand(0:1e8) v = vector3(frames, :Sun, :Earth, :SunEarthRot, e) v /= norm(v) @test v[1] ≈ 1.0 end end;
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
2562
# FrameTransformations.jl _A modern high-performance set of tools for transformations between standard and user-defined reference frame._ [![Stable Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliaspacemissiondesign.github.io/FrameTransformations.jl/stable/) [![Dev Documentation](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliaspacemissiondesign.github.io/FrameTransformations.jl/dev/) [![Build Status](https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/JuliaSpaceMissionDesign/FrameTransformations.jl/branch/main/graph/badge.svg?token=7fj9BjJhKF)](https://codecov.io/gh/JuliaSpaceMissionDesign/FrameTransformations.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) Are you in search of fundamental routines for efficient and extensible frames transformations? If so, this package is the ideal starting point. FrameTransformations.jl is designed to provide users with the ability to create a customized, efficient, flexible, and extensible axes/point graph models for mission analysis and space mission design purposes. ## Features - Convert between different time scales and representations (via [Tempo.jl](https://github.com/JuliaSpaceMissionDesign/Tempo.jl)); - Read binary ephemeris files (via [Ephemerides.jl](https://github.com/JuliaSpaceMissionDesign/Ephemerides.jl) or [CalcephEphemeris.jl](https://github.com/JuliaSpaceMissionDesign/CalcephEphemeris.jl)) - Create custom reference frame systems with both standard and user-defined points and axes. - Transform states and their higher-order derivatives between different frames (up to jerk) All of this seamlessly integrated with [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl). ## Installation This package can be installed using Julia's package manager: ```julia julia> import Pkg julia> Pkg.add("FrameTransformations.jl"); ``` ## Documentation For further information on this package and its tutorials please refer to the [stable documentation](https://juliaspacemissiondesign.github.io/FrameTransformations.jl/stable/). ## Support If you found this package useful, please consider starring the repository. We also encourage you to take a look at other astrodynamical packages of the [JSMD](https://github.com/JuliaSpaceMissionDesign/) organisation.
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
1339
# Welcome to FrameTransformations.jl! _A modern, high-performance and comprehensive set of tools for transformations between any standard and user-defined reference frame._ Are you in search of fundamental routines for efficient and extensible frames transformations? If so, this package is the ideal starting point. FrameTransformations.jl is designed to provide users with the ability to create a customized, efficient, flexible, and extensible axes/point graph models for mission analysis and space mission design purposes. ## Features - Convert between different time scales and representations (via [Tempo.jl](https://github.com/JuliaSpaceMissionDesign/Tempo.jl)). - Read binary ephemeris files (via [Ephemerides.jl](https://github.com/JuliaSpaceMissionDesign/Ephemerides.jl) or [CalcephEphemeris.jl](https://github.com/JuliaSpaceMissionDesign/CalcephEphemeris.jl) extensions). - Create custom reference frame systems with both standard and user-defined points, axes and directions. - Transform states and their higher-order derivatives between different frames (up to jerk). All of this integrated with [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl). ## Installation This package can be installed using Julia's package manager: ```julia julia> import Pkg julia> Pkg.add("FrameTransformations.jl"); ```
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
1257
# [Axes](@id axes_api) ## Core ```@docs add_axes! add_axes_fixedoffset! add_axes_projected! add_axes_rotating! add_axes_alias! FrameTransformations.add_axes_ephemeris! ``` ## Celestial ```@docs add_axes_gcrf! add_axes_icrf! add_axes_eme2000! ``` ## Ecliptic ```@docs add_axes_ecl2000! ``` ## Terrestrial ```@docs add_axes_itrf! add_axes_tirf! add_axes_cirf! add_axes_mod! add_axes_tod! add_axes_gtod! add_axes_pef! ``` ## Planetary ```@docs add_axes_bci2000! add_axes_bcrtod! ``` ## Lunar ```@docs add_axes_me421! add_axes_pa421! add_axes_pa440! ``` ## Topocentric ```@docs add_axes_topocentric! ``` ## Others ```@docs add_axes_twodir! add_axes_frozen! add_axes_fixed_quaternion! add_axes_fixed_angles! add_axes_fixed_angleaxis! ``` ## Utils ### [IDs](@id frames_axesid) This is a list of NAIF IDs for standard axes that are used in astrodynamic applications. ```@docs FrameTransformations.AXESID_ICRF FrameTransformations.AXESID_MOONME_DE421 FrameTransformations.AXESID_MOONPA_DE421 FrameTransformations.AXESID_MOONPA_DE440 FrameTransformations.AXESID_ECL2000 FrameTransformations.AXESID_EME2000 FrameTransformations.AXESID_GCRF ``` ### [Rotation Matrices](@id frames_dcms) ```@docs FrameTransformations.DCM_ICRF_TO_EME2000 ```
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
153
# [Directions](@id dir_api) ```@docs add_direction! add_direction_fixed! add_direction_position! add_direction_velocity! add_direction_orthogonal! ```
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
695
## [Frame System](@id frames_api) ```@docs FrameSystem order FrameTransformations.timescale ``` ### Points ```@docs has_point points_graph points_alias ``` ### Axes ```@docs has_axes axes_graph axes_alias ``` ### Directions ```@docs has_direction directions ``` ## [Rotations](@id rotation_api) ```@docs Rotation Base.inv Translation ``` ## [Transformations](@id transformations_api) ### [Points](@id points_transform_api) ```@docs vector3 vector6 vector9 vector12 ``` ### [Axes](@id axes_transform_api) ```@docs rotation3 rotation6 rotation9 rotation12 ``` ### [Directions](@id directions_transform_api) ```@docs direction3 direction6 direction9 direction12 ```
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
3.0.0
cb117510f2ba3d831439f56a5a3c00170cbf7a8d
docs
176
# [Points](@id points_api) ```@docs add_point! add_point_dynamical! add_point_fixedoffset! FrameTransformations.add_point_ephemeris! add_point_surface! add_point_alias! ```
FrameTransformations
https://github.com/JuliaSpaceMissionDesign/FrameTransformations.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
148
module TileMaps import Crayons include("objects.jl") include("object_indexable_array.jl") include("tile_map.jl") include("visualization.jl") end
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
2778
""" ObjectIndexableArray{T, N, A, O} <: AbstractArray{T, N} An instance of `ObjectIndexableArray`, referred to as `object_indexable_array` here, simply wraps an `array` (whose type is captured by the type parameter `A` above) and allows us to index its first dimension using a [singleton](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types) object or an array of singleton objects (in addition to all the other ways of indexing the wrapped `array`). Information about the objects is stored in the type parameter `O` above which is essentially the type of tuple of objects along the `num_objects` dimension. Note that `size(object_indexable_array, 1)` should be equal to the number of elements in the type parameter `O`. """ struct ObjectIndexableArray{T, N, A, O} <: AbstractArray{T, N} array::A end get_objects_type(::ObjectIndexableArray{T, N, A, O}) where {T, N, A, O} = O get_objects(object_indexable_array::ObjectIndexableArray) = Tuple(object_type() for object_type in get_objects_type(object_indexable_array).parameters) Base.size(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.size(object_indexable_array.array, args..., kwargs...) # regular indexing (indexing without using objects) Base.getindex(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.getindex(object_indexable_array.array, args..., kwargs...) Base.setindex!(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.setindex!(object_indexable_array.array, args..., kwargs...) # indexing using a single object @generated function Base.to_index(object_indexable_array::ObjectIndexableArray{T, N, A, O}, object::X) where {T, N, A, O, X <: AbstractObject} i = findfirst(X .=== O.parameters) isnothing(i) && error("Object $object is not present in $object_indexable_array") return :($i) end Base.getindex(object_indexable_array::ObjectIndexableArray, object::AbstractObject, args...; kwargs...) = getindex(object_indexable_array.array, Base.to_index(object_indexable_array, object), args..., kwargs...) Base.setindex!(object_indexable_array::ObjectIndexableArray, value::Bool, object::AbstractObject, args...; kwargs...) = setindex!(object_indexable_array.array, value, Base.to_index(object_indexable_array, object), args..., kwargs...) # indexing using an array of objects Base.to_index(object_indexable_array::ObjectIndexableArray, objects::AbstractArray{<:AbstractObject}) = map(object -> Base.to_index(object_indexable_array, object), objects) Base.getindex(object_indexable_array::ObjectIndexableArray, objects::AbstractArray{<:AbstractObject}, args...; kwargs...) = getindex(object_indexable_array.array, map(object -> Base.to_index(object_indexable_array, object), objects), args..., kwargs...)
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
291
const ObjectOccupancyArray{O, N} = ObjectIndexableArray{O, BitArray{N}, Bool, N} function ObjectOccupancyArray(objects::Tuple{Vararg{AbstractObject}}, dims::Integer...) grid = falses(length(objects), dims...) return ObjectOccupancyArray{typeof(objects), length(dims) + 1}(grid) end
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
294
abstract type AbstractObject end struct ExampleObject1 <: AbstractObject end const EXAMPLE_OBJECT_1 = ExampleObject1() struct ExampleObject2 <: AbstractObject end const EXAMPLE_OBJECT_2 = ExampleObject2() struct ExampleObject3 <: AbstractObject end const EXAMPLE_OBJECT_3 = ExampleObject3()
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
942
""" const TileMap{O} = ObjectIndexableArray{Bool, 3, BitArray{3}, O} An instance of `TileMap`, referred to as `tile_map` here, wraps an `array` of type `BitArray{3}` and is of size `(num_objects, height, width)`, which encodes information about the presence or absence of objects across the tiles using Boolean values. Each tile can contain multiple objects, which is captured by a multi-hot encoding along the first dimension (`num_objects` dimension) of the `array`. """ const TileMap{O} = ObjectIndexableArray{Bool, 3, BitArray{3}, O} TileMap(objects::Tuple{Vararg{AbstractObject}}, grid::BitArray{3}) = TileMap{typeof(objects)}(grid) TileMap(objects::Tuple{Vararg{AbstractObject}}, height::Integer, width::Integer) = TileMap(objects, falses(length(objects), height, width)) get_num_objects(tile_map::TileMap) = size(tile_map, 1) get_height(tile_map::TileMap) = size(tile_map, 2) get_width(tile_map::TileMap) = size(tile_map, 3)
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
2790
get_char(object::Any) = '?' get_foreground_color(::Any) = :white get_background_color(::Any) = :nothing get_char(::Nothing) = '⋅' get_foreground_color(::Nothing) = :white get_background_color(::Nothing) = :nothing # purposefully not defining `get_char(::ExampleObject3)`, `get_foreground_color(::ExampleObject3)`, and `get_background_color(::ExampleObject3)` in order to test fallback to default methods get_char(::ExampleObject1) = '∘' get_foreground_color(::ExampleObject1) = :light_green get_background_color(::ExampleObject1) = :nothing get_char(::ExampleObject2) = '✖' get_foreground_color(::ExampleObject2) = :light_red get_background_color(::ExampleObject2) = :nothing function Base.show(io::IO, ::MIME"text/plain", object::AbstractObject) print(io, typeof(object), "() displayed as <", Crayons.Crayon(foreground = get_foreground_color(object), background = get_background_color(object), reset = true), get_char(object), Crayons.Crayon(reset = true), ">", ) return nothing end function get_first_object(tile_map::TileMap{O}, height::Integer, width::Integer) where {O} idx = findfirst(tile_map[:, height, width]) if isnothing(idx) return nothing else return O.parameters[idx]() end end function Base.show(io::IO, ::MIME"text/plain", tile_map::TileMap) for i in 1:get_height(tile_map) for j in 1:get_width(tile_map) object = get_first_object(tile_map, i, j) print(io, Crayons.Crayon(foreground = get_foreground_color(object), background = get_background_color(object), reset = true), get_char(object), Crayons.Crayon(reset = true), ) end if i < get_height(tile_map) println(io) else print(io) end end return nothing end function show_layers(io::IO, ::MIME"text/plain", tile_map::TileMap{O}) where {O} for (layer, object_type) in enumerate(O.parameters) object = object_type() println("layer = $layer, object = $object") for i in 1:get_height(tile_map) for j in 1:get_width(tile_map) if tile_map[object, i, j] displayed_object = object else displayed_object = nothing end print(io, Crayons.Crayon(foreground = get_foreground_color(displayed_object), background = get_background_color(displayed_object), reset = true), get_char(displayed_object), Crayons.Crayon(reset = true), ) end println(io) end end return nothing end
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
code
2065
import TileMaps as TM import Test Test.@testset "TileMaps.jl" begin objects = (TM.EXAMPLE_OBJECT_1, TM.EXAMPLE_OBJECT_2, TM.EXAMPLE_OBJECT_3) layer_1 = BitArray([0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0]) layer_2 = BitArray([0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0]) layer_3 = BitArray([0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0]) grid = BitArray(undef, 3, 4, 5) grid[1, :, :] .= layer_1 grid[2, :, :] .= layer_2 grid[3, :, :] .= layer_3 tile_map = TM.TileMap(objects, grid) Test.@test TM.get_objects_type(tile_map) == typeof(objects) Test.@test TM.get_objects(tile_map) == objects Test.@test TM.get_num_objects(tile_map) == 3 Test.@test TM.get_height(tile_map) == 4 Test.@test TM.get_width(tile_map) == 5 # regular indexing (indexing without using objects) Test.@test tile_map[1, 2, 3] == false Test.@test tile_map[1:3, 2, 2] == BitArray([1, 0, 1]) Test.@test tile_map[[1, 3], 2, 2] == BitArray([1, 1]) # indexing using one object Test.@test tile_map[TM.EXAMPLE_OBJECT_2, 1, 1] == tile_map[2, 1, 1] == false Test.@test tile_map[TM.EXAMPLE_OBJECT_2, end, end] == tile_map[2, end, end] == false Test.@test tile_map[TM.EXAMPLE_OBJECT_2, :, 1] == tile_map[2, :, 1] == BitArray([0, 0, 1, 1]) Test.@test tile_map[TM.EXAMPLE_OBJECT_2, end, :] == tile_map[2, end, :] == BitArray([1, 1, 0, 0, 0]) Test.@test tile_map[TM.EXAMPLE_OBJECT_2, 2:3, 2:4] == tile_map[2, 2:3, 2:4] == BitArray([0 0 0 1 0 0]) # indexing using more than one object Test.@test tile_map[[TM.EXAMPLE_OBJECT_2], 1, 1] == tile_map[[2], 1, 1] == BitArray([0]) Test.@test tile_map[[TM.EXAMPLE_OBJECT_3, TM.EXAMPLE_OBJECT_1], 2, 1] == tile_map[[3, 1], 2, 1] == BitArray([1, 0]) end
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
2e3e7ee05b1b2f976079ab6a0bc6f03491ead390
docs
6457
# TileMaps `TileMaps` is a package that makes it simple to create 2D tile maps (and higher dimensional equivalents) in Julia. It is designed to be lightweight and fast, and have minimal dependencies. **Note:** This package does not export any names. The examples below that demonstrate the use of this package assume that it has been loaded via `import TileMaps as TM`. **Acknowledgements:** Big thanks to [Jun Tian](https://github.com/findmyway) (@findmyway) for initially introducing the core ideas of this package in [`GridWorlds`](https://github.com/JuliaReinforcementLearning/GridWorlds.jl). ### Index 1. [ObjectIndexableArray](#objectindexablearray) 1. [Objects](#objects) 1. [TileMap](#tilemap) 1. [Constructing a TileMap](#constructing-a-tilemap) 1. [Indexing a TileMap](#indexing-a-tilemap) 1. [Visualizing a TileMap](#visualizing-a-tilemap) ### `ObjectIndexableArray` ``` struct ObjectIndexableArray{T, N, A, O} <: AbstractArray{T, N} array::A end ``` An instance of `ObjectIndexableArray`, referred to as `object_indexable_array` here, simply wraps an `array` (whose type is captured by the type parameter `A` above) and allows us to index its first dimension using a [singleton](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types) object or an array of singleton objects (in addition to all the other ways of indexing the wrapped `array`). Information about the objects is stored in the type parameter `O` above which is essentially the type of tuple of objects along the `num_objects` dimension. Note that `size(object_indexable_array, 1)` should be equal to the number of elements in the type parameter `O`. `size(object_indexable_array, 1)` should be equal to the number of elements in the type parameter `O`. ### Objects Object types are [singletons](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types) (structs with no fields). Here are the example objects that are provided in this package: ``` abstract type AbstractObject end struct ExampleObject1 <: AbstractObject end const EXAMPLE_OBJECT_1 = ExampleObject1() struct ExampleObject2 <: AbstractObject end const EXAMPLE_OBJECT_2 = ExampleObject2() struct ExampleObject3 <: AbstractObject end const EXAMPLE_OBJECT_3 = ExampleObject3() ``` You can crate your own objects like this: ``` julia> struct MyObject <: TM.AbstractObject end julia> ``` For an `object_indexable_array`, you can get the type of tuple of objects in it using `TM.get_objects_type(object_indexable_array)`, or you can get the tuple of objects itself, using `TM.get_objects(object_indexable_array)`. ### `TileMap` ``` const TileMap{O} = ObjectIndexableArray{Bool, 3, BitArray{3}, O} ``` An instance of `TileMap`, referred to as `tile_map` here, wraps an `array` of type `BitArray{3}` and is of size `(num_objects, height, width)`, which encodes information about the presence or absence of objects across the tiles using Boolean values. Each tile can contain multiple objects, which is captured by a multi-hot encoding along the first dimension (`num_objects` dimension) of the `array`. ### Constructing a `TileMap` You can instantiate a `TileMap` using the following constructor that are provided by this package: 1. Create an empty `tile_map` using a tuple of objects and the desired height (8) and width(16): ``` julia> tile_map = TM.TileMap((TM.EXAMPLE_OBJECT_1, TM.EXAMPLE_OBJECT_2, TM.EXAMPLE_OBJECT_3), 8, 16); julia> ``` 1. Create a `tile_map` using a tuple of objects and an existing `array`: ``` julia> tile_map = TM.TileMap((TM.EXAMPLE_OBJECT_1, TM.EXAMPLE_OBJECT_2, TM.EXAMPLE_OBJECT_3), rand(Bool, 3, 8, 16) |> BitArray); julia> ``` ### Indexing a `TileMap` Because of `TileMap <: ObjectIndexableArray`, we can index the first dimension of a `tile_map` in a variety of ways. For example, like this: ``` julia> tile_map[TM.EXAMPLE_OBJECT_3, 4, 6] true julia> tile_map[TM.EXAMPLE_OBJECT_3, 2:4, 6:7] 3×2 BitMatrix: 1 1 0 1 1 1 julia> tile_map[[TM.EXAMPLE_OBJECT_3, TM.EXAMPLE_OBJECT_1], 5, 8] 2-element BitVector: 0 1 julia> ``` ### Visualizing a `TileMap` Using the [`Crayons`](https://github.com/KristofferC/Crayons.jl) package, each object can be displayed as a colored Unicode character. For example, like this: <img src="https://github.com/Sid-Bhatia-0/TileMaps.jl/blob/master/assets/example_object_1.png"> When you create your custom object like this, for example, <img src="https://github.com/Sid-Bhatia-0/TileMaps.jl/blob/master/assets/my_object.png"> you may also want to implement the following methods: `get_char(::MyObject)` (especially this one), `get_foreground_color(::MyObject)`, and `get_backround_color(::MyObject)`. If you don't do so, `MY_OBJECT` will be displayed based on the following default methods as defined in this package: ``` get_char(object::Any) = '?' get_foreground_color(object::Any) = :white get_backround_color(object::Any) = :nothing ``` A `tile_map` is displayed as a 2D grid of colored Unicode characters, with one character displayed per tile. Only the first object present (along the first dimension (`num_objects` dimension) of the `array`) at a tile is displayed for that tile, even though there may be multiple objects present at that tile. If there are no objects present at a tile, then the `⋅` character is displayed for that tile (with white color and no background). This behaviour can be customized by overriding the following methods: ``` get_char(::Nothing) = '⋅' get_foreground_color(::Nothing) = :white get_background_color(::Nothing) = :nothing ``` <img src="https://github.com/Sid-Bhatia-0/TileMaps.jl/blob/master/assets/tile_map.png"> Note that the `get_char`, `get_foreground_color`, and `get_background_color` methods have purposefully not been explictly defined for the `TM.ExampleObject3` type in order to demonstrate the fallback to the default character and colors, which is why `TM.EXAMPLE_OBJECT_3` is displayed using a white colored `?` with no background. We can also inspect each kind of object in the `tile_map` separately using the `show_layers` method. This is very handy for debugging: <img src="https://github.com/Sid-Bhatia-0/TileMaps.jl/blob/master/assets/show_layers.png"> Here we have utilized only a limited number of features from the `Crayons` package in order to show an an example of how one may want to display a `tile_map`. `Crayons` has other features that you can play with to suit your needs.
TileMaps
https://github.com/JuliaReinforcementLearning/TileMaps.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
code
1544
using SyncSort using BenchmarkTools @inbounds function test1(n) x = rand(n) y = rand(n) z = rand(n) syncsort!(x,y,z) x,y,z end @inbounds function test2(n) x = rand(n) y = rand(n) z = rand(n) isorted = sortperm(x) x = x[isorted] y = y[isorted] z = z[isorted] x,y,z end function syncsortperm!(v, rest...) isorted = sortperm(v) # Permute elements of v and rest in-place following isorted done = firstindex(v) - 1 i = firstindex(isorted) @inbounds while i <= lastindex(isorted) j = i js = isorted[j] if js != done @inbounds while true isorted[j] = done isorted[js] == done && break v[j], v[js] = v[js], v[j] for r in rest r[j], r[js] = r[js], r[j] end j = js js = isorted[j] end end i += 1 end end @inbounds function test3(n) x = rand(n) y = rand(n) z = rand(n) syncsortperm!(x,y,z) x,y,z end @inbounds function test4(n) x = rand(n) y = rand(n) z = rand(n) syncsort!(x,y,z; alg=SyncSort.CPUSort.ScratchQuickSort()) x,y,z end println("\nsyncsort:") display(@benchmark(test1(10_000))) println("\nsortperm:") display(@benchmark(test2(10_000))) println("\nsyncsortperm:") display(@benchmark(test3(10_000))) println("\nsyncsort/ScratchQuickSort:") display(@benchmark(test4(10_000)))
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
code
321
# File : SyncSort.jl # License: MIT # Author : Dominik Werner <[email protected]> # Date : 26.01.2023 # Paper : https://drive.google.com/file/d/0B7uLFueU4vLfcjJfZFh3TlIxMFE/view?resourcekey=0-8Ovsx4PtAJn78xLboBEb_g module SyncSort export syncsort! include("cpu_sort.jl") using .CPUSort end # module MergeSortGPU
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
code
53214
# This file was copied from https://github.com/JuliaLang/julia/blob/v1.9.1/base/sort.jl with some # modifications to propagate secondary arrays to be sorted and follow swaps. The original license # is included below. Thank you! # MIT License # Copyright (c) 2009-2023: Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and other contributors: https://github.com/JuliaLang/julia/contributors # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # end of terms and conditions # Please see [THIRDPARTY.md](./THIRDPARTY.md) for license information for other software used in this project. module CPUSort # Relevant exports export syncsort! export RadixSort, ScratchQuickSort, InsertionSort # Internal imports using Base.Order using Base: copymutable, midpoint, require_one_based_indexing, uinttype, sub_with_overflow, add_with_overflow, OneTo, BitSigned, BitIntegerType, IteratorSize, HasShape, IsInfinite, tail top_set_bit(x::Integer) = ceil(Integer, log2(x + oneunit(x))) ## Alternative keyword management macro getkw(syms...) getters = (getproperty(CPUSort, Symbol(:_, sym)) for sym in syms) Expr(:block, (:($(esc(:((kw, $sym) = $getter(v, o, kw))))) for (sym, getter) in zip(syms, getters))...) end for (sym, exp, type) in [ (:lo, :(firstindex(v)), Integer), (:hi, :(lastindex(v)), Integer), (:mn, :(throw(ArgumentError("mn is needed but has not been computed"))), :(eltype(v))), (:mx, :(throw(ArgumentError("mx is needed but has not been computed"))), :(eltype(v))), (:scratch, nothing, :(Union{Nothing, Vector})), # could have different eltype ] usym = Symbol(:_, sym) @eval function $usym(v, o, kw) # using missing instead of nothing because scratch could === nothing. res = get(kw, $(Expr(:quote, sym)), missing) res !== missing && return kw, res::$type $sym = $exp (;kw..., $sym), $sym::$type end end ## Scratch space management """ make_scratch(scratch::Union{Nothing, Vector}, T::Type, len::Integer) Returns `(s, t)` where `t` is an `AbstractVector` of type `T` with length at least `len` that is backed by the `Vector` `s`. If `scratch !== nothing`, then `s === scratch`. This function will allocate a new vector if `scratch === nothing`, `resize!` `scratch` if it is too short, and `reinterpret` `scratch` if its eltype is not `T`. """ function make_scratch(scratch::Nothing, T::Type, len::Integer) s = Vector{T}(undef, len) s, s end function make_scratch(scratch::Vector{T}, ::Type{T}, len::Integer) where T len > length(scratch) && resize!(scratch, len) scratch, scratch end function make_scratch(scratch::Vector, T::Type, len::Integer) len_bytes = len * sizeof(T) len_scratch = div(len_bytes, sizeof(eltype(scratch))) len_scratch > length(scratch) && resize!(scratch, len_scratch) scratch, reinterpret(T, scratch) end ## sorting algorithm components ## """ _sort!(v::AbstractVector, a::Algorithm, o::Ordering, kw; t, offset) An internal function that sorts `v` using the algorithm `a` under the ordering `o`, subject to specifications provided in `kw` (such as `lo` and `hi` in which case it only sorts `view(v, lo:hi)`) Returns a scratch space if provided or constructed during the sort, or `nothing` if no scratch space is present. !!! note `_sort!` modifies but does not return `v`. A returned scratch space will be a `Vector{T}` where `T` is usually the eltype of `v`. There are some exceptions, for example if `eltype(v) == Union{Missing, T}` then the scratch space may be be a `Vector{T}` due to `MissingOptimization` changing the eltype of `v` to `T`. `t` is an appropriate scratch space for the algorithm at hand, to be accessed as `t[i + offset]`. `t` is used for an algorithm to pass a scratch space back to itself in internal or recursive calls. """ function _sort! end abstract type Algorithm end """ MissingOptimization(next) <: Algorithm Filter out missing values. Missing values are placed after other values according to `DirectOrdering`s. This pass puts them there and passes on a view into the original vector that excludes the missing values. This pass is triggered for both `sort([1, missing, 3])` and `sortperm([1, missing, 3])`. """ struct MissingOptimization{T <: Algorithm} <: Algorithm next::T end struct WithoutMissingVector{T, U} <: AbstractVector{T} data::U function WithoutMissingVector(data; unsafe=false) if !unsafe && any(ismissing, data) throw(ArgumentError("data must not contain missing values")) end new{nonmissingtype(eltype(data)), typeof(data)}(data) end end Base.@propagate_inbounds function Base.getindex(v::WithoutMissingVector, i) out = v.data[i] @assert !(out isa Missing) out::eltype(v) end Base.@propagate_inbounds function Base.setindex!(v::WithoutMissingVector, x, i) v.data[i] = x v end Base.size(v::WithoutMissingVector) = size(v.data) Base.axes(v::WithoutMissingVector) = axes(v.data) """ send_to_end!(f::Function, v::AbstractVector; [lo, hi]) Send every element of `v` for which `f` returns `true` to the end of the vector and return the index of the last element for which `f` returns `false`. `send_to_end!(f, v, lo, hi)` is equivalent to `send_to_end!(f, view(v, lo:hi))+lo-1` Preserves the order of the elements that are not sent to the end. """ function send_to_end!(f::F, v::AbstractVector, rest; lo=firstindex(v), hi=lastindex(v)) where F <: Function i = lo @inbounds while i <= hi && !f(v[i]) i += 1 end j = i + 1 @inbounds while j <= hi if !f(v[j]) swap_rest!(v, rest, i, j) i += 1 end j += 1 end i - 1 end """ send_to_end!(f::Function, v::AbstractVector, o::DirectOrdering[, end_stable]; lo, hi) Return `(a, b)` where `v[a:b]` are the elements that are not sent to the end. If `o isa ReverseOrdering` then the "end" of `v` is `v[lo]`. If `end_stable` is set, the elements that are sent to the end are stable instead of the elements that are not """ @inline send_to_end!(f::F, v::AbstractVector, rest, ::ForwardOrdering, end_stable=false; lo, hi) where F <: Function = end_stable ? (lo, hi-send_to_end!(!f, view(v, hi:-1:lo), view_rest(rest, hi:-1:lo))) : (lo, send_to_end!(f, v, rest; lo, hi)) @inline send_to_end!(f::F, v::AbstractVector, rest, ::ReverseOrdering, end_stable=false; lo, hi) where F <: Function = end_stable ? (send_to_end!(!f, v, rest; lo, hi)+1, hi) : (hi-send_to_end!(f, view(v, hi:-1:lo), view_rest(rest, hi:-1:lo))+1, hi) """ Swap two elements at indices i and j for the key vector v and secondary vectors in rest. NEW ADDITION """ @inline function swap_rest!(v, rest, i, j) v[i], v[j] = v[j], v[i] for r in rest r[i], r[j] = r[j], r[i] end end """ Construct views into each of the vectors of within a tuple. NEW ADDITION """ @inline function view_rest(rest::Tuple, inds...) @inbounds tuple((view(r, inds...) for r in rest)...) end """ Reverse each of the vectors within a tuple. NEW ADDITION """ @inline function reverse_rest!(rest::Tuple, lo, hi) for r in rest reverse!(r, lo, hi) end end """ Create copies of the vectors within a tuple. NEW ADDITION """ @inline function similar_rest(rest::Tuple) tuple((similar(r) for r in rest)...) end @inline function _sort!(v::AbstractVector, rest, a::MissingOptimization, o::Ordering, kw) @getkw lo hi if o isa DirectOrdering && eltype(v) >: Missing && nonmissingtype(eltype(v)) != eltype(v) lo, hi = send_to_end!(ismissing, v, rest, o; lo, hi) _sort!(WithoutMissingVector(v, unsafe=true), rest, a.next, o, (;kw..., lo, hi)) elseif o isa Perm && o.order isa DirectOrdering && eltype(v) <: Integer && eltype(o.data) >: Missing && nonmissingtype(eltype(o.data)) != eltype(o.data) && all(i === j for (i,j) in zip(v, eachindex(o.data))) throw(error("SyncSort not defined for Missing types with Perm ordering yet.")) # TODO make this branch known at compile time # This uses a custom function because we need to ensure stability of both sides and # we can assume v is equal to eachindex(o.data) which allows a copying partition # without allocations. lo_i, hi_i = lo, hi for i in eachindex(o.data) # equal to copy(v) x = o.data[i] if ismissing(x) == (o.order == Reverse) # should x go at the beginning/end? v[lo_i] = i lo_i += 1 else v[hi_i] = i hi_i -= 1 end end reverse!(v, lo_i, hi) if o.order == Reverse lo = lo_i else hi = hi_i end _sort!(v, a.next, Perm(o.order, WithoutMissingVector(o.data, unsafe=true)), (;kw..., lo, hi), rest) else _sort!(v, rest, a.next, o, kw) end end """ IEEEFloatOptimization(next) <: Algorithm Move NaN values to the end, partition by sign, and reinterpret the rest as unsigned integers. IEEE floating point numbers (`Float64`, `Float32`, and `Float16`) compare the same as unsigned integers with the bits with a few exceptions. This pass This pass is triggered for both `sort([1.0, NaN, 3.0])` and `sortperm([1.0, NaN, 3.0])`. """ struct IEEEFloatOptimization{T <: Algorithm} <: Algorithm next::T end after_zero(::ForwardOrdering, x) = !signbit(x) after_zero(::ReverseOrdering, x) = signbit(x) is_concrete_IEEEFloat(T::Type) = T <: Base.IEEEFloat && isconcretetype(T) @inline function _sort!(v::AbstractVector, rest, a::IEEEFloatOptimization, o::Ordering, kw) @getkw lo hi if is_concrete_IEEEFloat(eltype(v)) && o isa DirectOrdering lo, hi = send_to_end!(isnan, v, rest, o, true; lo, hi) iv = reinterpret(uinttype(eltype(v)), v) j = send_to_end!(x -> after_zero(o, x), v, rest; lo, hi) scratch = _sort!(iv, rest, a.next, Reverse, (;kw..., lo, hi=j)) if scratch === nothing # Union split _sort!(iv, rest, a.next, Forward, (;kw..., lo=j+1, hi, scratch)) else _sort!(iv, rest, a.next, Forward, (;kw..., lo=j+1, hi, scratch)) end elseif eltype(v) <: Integer && o isa Perm && o.order isa DirectOrdering && is_concrete_IEEEFloat(eltype(o.data)) lo, hi = send_to_end!(i -> isnan(@inbounds o.data[i]), v, rest, o.order, true; lo, hi) ip = reinterpret(uinttype(eltype(o.data)), o.data) j = send_to_end!(i -> after_zero(o.order, @inbounds o.data[i]), v, rest; lo, hi) scratch = _sort!(v, rest, a.next, Perm(Reverse, ip), (;kw..., lo, hi=j)) if scratch === nothing # Union split _sort!(v, rest, a.next, Perm(Forward, ip), (;kw..., lo=j+1, hi, scratch)) else _sort!(v, rest, a.next, Perm(Forward, ip), (;kw..., lo=j+1, hi, scratch)) end else _sort!(v, rest, a.next, o, kw) end end """ BoolOptimization(next) <: Algorithm Sort `AbstractVector{Bool}`s using a specialized version of counting sort. Accesses each element at most twice (one read and one write), and performs at most two comparisons. """ struct BoolOptimization{T <: Algorithm} <: Algorithm next::T end _sort!(v::AbstractVector, rest, a::BoolOptimization, o::Ordering, kw) = _sort!(v, rest, a.next, o, kw) @inline function _sort!(v::AbstractVector{Bool}, rest, ::BoolOptimization, o::Ordering, kw) if size(rest,1) != 0 throw(error("SyncSort is not defined for Vector{Bool} yet.")) end first = lt(o, false, true) ? false : lt(o, true, false) ? true : return v @getkw lo hi scratch count = 0 @inbounds for i in lo:hi if v[i] == first count += 1 end end @inbounds v[lo:lo+count-1] .= first @inbounds v[lo+count:hi] .= !first scratch end """ IsUIntMappable(yes, no) <: Algorithm Determines if the elements of a vector can be mapped to unsigned integers while preserving their order under the specified ordering. If they can be, dispatch to the `yes` algorithm and record the unsigned integer type that the elements may be mapped to. Otherwise dispatch to the `no` algorithm. """ struct IsUIntMappable{T <: Algorithm, U <: Algorithm} <: Algorithm yes::T no::U end @inline function _sort!(v::AbstractVector, rest, a::IsUIntMappable, o::Ordering, kw) #println("Is uintmappable?") if UIntMappable(eltype(v), o) !== nothing _sort!(v, rest, a.yes, o, kw) else _sort!(v, rest, a.no, o, kw) end end """ Small{N}(small=SMALL_ALGORITHM, big) <: Algorithm Sort inputs with `length(lo:hi) <= N` using the `small` algorithm. Otherwise use the `big` algorithm. """ struct Small{N, T <: Algorithm, U <: Algorithm} <: Algorithm small::T big::U end Small{N}(small, big) where N = Small{N, typeof(small), typeof(big)}(small, big) Small{N}(big) where N = Small{N}(SMALL_ALGORITHM, big) @inline function _sort!(v::AbstractVector, rest, a::Small{N}, o::Ordering, kw) where N @getkw lo hi if (hi-lo) < N _sort!(v, rest, a.small, o, kw) else _sort!(v, rest, a.big, o, kw) end end struct InsertionSortAlg <: Algorithm end """ InsertionSort Use the insertion sort algorithm. Insertion sort traverses the collection one element at a time, inserting each element into its correct, sorted position in the output vector. Characteristics: * *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *in-place* in memory. * *quadratic performance* in the number of elements to be sorted: it is well-suited to small collections but should not be used for large ones. """ const InsertionSort = InsertionSortAlg() const SMALL_ALGORITHM = InsertionSortAlg() @inline function _sort!(v::AbstractVector, rest, ::InsertionSortAlg, o::Ordering, kw) @getkw lo hi scratch lo_plus_1 = (lo + 1)::Integer @inbounds for i = lo_plus_1:hi j = i x = v[i] x_rest = tuple((r[i] for r in rest)...) while j > lo y = v[j-1] if !(lt(o, x, y)::Bool) break end v[j] = y for r in rest r[j] = r[j - 1] end j -= 1 end v[j] = x for irest in eachindex(rest) rest[irest][j] = x_rest[irest] end end scratch end """ CheckSorted(next) <: Algorithm Check if the input is already sorted and for large inputs, also check if it is reverse-sorted. The reverse-sorted check is unstable. """ struct CheckSorted{T <: Algorithm} <: Algorithm next::T end @inline function _sort!(v::AbstractVector, rest, a::CheckSorted, o::Ordering, kw) @getkw lo hi scratch # For most arrays, a presorted check is cheap (overhead < 5%) and for most large # arrays it is essentially free (<1%). _issorted(v, lo, hi, o) && return scratch # For most large arrays, a reverse-sorted check is essentially free (overhead < 1%) if hi-lo >= 500 && _issorted(v, lo, hi, ReverseOrdering(o)) # If reversing is valid, do so. This violates stability. reverse!(v, lo, hi) reverse_rest!(rest, lo, hi) return scratch end _sort!(v, rest, a.next, o, kw) end """ ComputeExtrema(next) <: Algorithm Compute the extrema of the input under the provided order. If the minimum is no less than the maximum, then the input is already sorted. Otherwise, dispatch to the `next` algorithm. """ struct ComputeExtrema{T <: Algorithm} <: Algorithm next::T end @inline function _sort!(v::AbstractVector, rest, a::ComputeExtrema, o::Ordering, kw) @getkw lo hi scratch mn = mx = v[lo] @inbounds for i in (lo+1):hi vi = v[i] lt(o, vi, mn) && (mn = vi) lt(o, mx, vi) && (mx = vi) end lt(o, mn, mx) || return scratch # all same _sort!(v, rest, a.next, o, (;kw..., mn, mx)) end """ ConsiderCountingSort(counting=CountingSort(), next) <: Algorithm If the input's range is small enough, use the `counting` algorithm. Otherwise, dispatch to the `next` algorithm. For most types, the threshold is if the range is shorter than half the length, but for types larger than Int64, bitshifts are expensive and RadixSort is not viable, so the threshold is much more generous. """ struct ConsiderCountingSort{T <: Algorithm, U <: Algorithm} <: Algorithm counting::T next::U end ConsiderCountingSort(next) = ConsiderCountingSort(CountingSort(), next) @inline function _sort!(v::AbstractVector{<:Integer}, a::ConsiderCountingSort, o::DirectOrdering, kw) @getkw lo hi mn mx range = maybe_unsigned(o === Reverse ? mn-mx : mx-mn) if range < (sizeof(eltype(v)) > 8 ? 5(hi-lo)-100 : div(hi-lo, 2)) _sort!(v, a.counting, o, kw) else _sort!(v, a.next, o, kw) end end _sort!(v::AbstractVector, a::ConsiderCountingSort, o::Ordering, kw) = _sort!(v, a.next, o, kw) """ CountingSort <: Algorithm Use the counting sort algorithm. `CountingSort` is an algorithm for sorting integers that runs in Θ(length + range) time and space. It counts the number of occurrences of each value in the input and then iterates through those counts repopulating the input with the values in sorted order. """ struct CountingSort <: Algorithm end maybe_reverse(o::ForwardOrdering, x) = x maybe_reverse(o::ReverseOrdering, x) = reverse(x) @inline function _sort!(v::AbstractVector{<:Integer}, ::CountingSort, o::DirectOrdering, kw) @getkw lo hi mn mx scratch range = maybe_unsigned(o === Reverse ? mn-mx : mx-mn) offs = 1 - (o === Reverse ? mx : mn) counts = fill(0, range+1) # TODO use scratch (but be aware of type stability) @inbounds for i = lo:hi counts[v[i] + offs] += 1 end idx = lo @inbounds for i = maybe_reverse(o, 1:range+1) lastidx = idx + counts[i] - 1 val = i-offs for j = idx:lastidx v[j] = val isa Unsigned && eltype(v) <: Signed ? signed(val) : val end idx = lastidx + 1 end scratch end """ ConsiderRadixSort(radix=RadixSort(), next) <: Algorithm If the number of bits in the input's range is small enough and the input supports efficient bitshifts, use the `radix` algorithm. Otherwise, dispatch to the `next` algorithm. """ struct ConsiderRadixSort{T <: Algorithm, U <: Algorithm} <: Algorithm radix::T next::U end ConsiderRadixSort(next) = ConsiderRadixSort(RadixSort(), next) @inline function _sort!(v::AbstractVector, rest, a::ConsiderRadixSort, o::DirectOrdering, kw) @getkw lo hi mn mx urange = uint_map(mx, o)-uint_map(mn, o) bits = unsigned(top_set_bit(urange)) if sizeof(eltype(v)) <= 8 && bits+70 < 22log(hi-lo) _sort!(v, rest, a.radix, o, kw) else _sort!(v, rest, a.next, o, kw) end end """ RadixSort <: Algorithm Use the radix sort algorithm. `RadixSort` is a stable least significant bit first radix sort algorithm that runs in `O(length * log(range))` time and linear space. It first sorts the entire vector by the last `chunk_size` bits, then by the second to last `chunk_size` bits, and so on. Stability means that it will not reorder two elements that compare equal. This is essential so that the order introduced by earlier, less significant passes is preserved by later passes. Each pass divides the input into `2^chunk_size == mask+1` buckets. To do this, it * counts the number of entries that fall into each bucket * uses those counts to compute the indices to move elements of those buckets into * moves elements into the computed indices in the swap array * switches the swap and working array `chunk_size` is larger for larger inputs and determined by an empirical heuristic. """ struct RadixSort <: Algorithm end @inline function _sort!(v::AbstractVector, rest, a::RadixSort, o::DirectOrdering, kw) @getkw lo hi mn mx scratch #println("In sort:", a,o,"\n\n\n") #println("Radixsort: $(eltype(v)), $(typeof(v))") umn = uint_map(mn, o) urange = uint_map(mx, o)-umn bits = unsigned(top_set_bit(urange)) # At this point, we are committed to radix sort. u = uint_map!(v, lo, hi, o) # we subtract umn to avoid radixing over unnecessary bits. For example, # Int32[3, -1, 2] uint_maps to UInt32[0x80000003, 0x7fffffff, 0x80000002] # which uses all 32 bits, but once we subtract umn = 0x7fffffff, we are left with # UInt32[0x00000004, 0x00000000, 0x00000003] which uses only 3 bits, and # Float32[2.012, 400.0, 12.345] uint_maps to UInt32[0x3fff3b63, 0x3c37ffff, 0x414570a4] # which is reduced to UInt32[0x03c73b64, 0x00000000, 0x050d70a5] using only 26 bits. # the overhead for this subtraction is small enough that it is worthwhile in many cases. # this is faster than u[lo:hi] .-= umn as of v1.9.0-DEV.100 @inbounds for i in lo:hi u[i] -= umn end #println("Scratch: $(typeof(scratch))") rest_scratch = similar_rest(rest) scratch, t = make_scratch(scratch, eltype(v), hi-lo+1) tu = reinterpret(eltype(u), t) #println(size(tu)) #println(typeof((u, lo, hi, bits, tu, 1-lo, rest))) if radix_sort!(u, lo, hi, bits, tu, 1-lo, rest, rest_scratch) uint_unmap!(v, u, (), (), lo, hi, o, umn) else uint_unmap!(v, tu, rest, rest_scratch, lo, hi, o, umn, 1-lo) end scratch end """ ScratchQuickSort(next::Algorithm=SMALL_ALGORITHM) <: Algorithm ScratchQuickSort(lo::Union{Integer, Missing}, hi::Union{Integer, Missing}=lo, next::Algorithm=SMALL_ALGORITHM) <: Algorithm Use the `ScratchQuickSort` algorithm with the `next` algorithm as a base case. `ScratchQuickSort` is like `QuickSort`, but utilizes scratch space to operate faster and allow for the possibility of maintaining stability. If `lo` and `hi` are provided, finds and sorts the elements in the range `lo:hi`, reordering but not necessarily sorting other elements in the process. If `lo` or `hi` is `missing`, it is treated as the first or last index of the input, respectively. `lo` and `hi` may be specified together as an `AbstractUnitRange`. Characteristics: * *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *not in-place* in memory. * *divide-and-conquer*: sort strategy similar to [`QuickSort`](@ref). * *linear runtime* if `length(lo:hi)` is constant * *quadratic worst case runtime* in pathological cases (vanishingly rare for non-malicious input) """ struct ScratchQuickSort{L<:Union{Integer,Missing}, H<:Union{Integer,Missing}, T<:Algorithm} <: Algorithm lo::L hi::H next::T end ScratchQuickSort(next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(missing, missing, next) ScratchQuickSort(lo::Union{Integer, Missing}, hi::Union{Integer, Missing}) = ScratchQuickSort(lo, hi, SMALL_ALGORITHM) ScratchQuickSort(lo::Union{Integer, Missing}, next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(lo, lo, next) ScratchQuickSort(r::OrdinalRange, next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(first(r), last(r), next) # select a pivot, partition v[lo:hi] according # to the pivot, and store the result in t[lo:hi]. # # sets `pivot_dest[pivot_index+pivot_index_offset] = pivot` and returns that index. function partition!(t::AbstractVector, lo::Integer, hi::Integer, offset::Integer, o::Ordering, v::AbstractVector, rev::Bool, pivot_dest::AbstractVector, pivot_index_offset::Integer, rest_t, rest_v, rest_pivot_dest) # Ideally we would use `pivot_index = rand(lo:hi)`, but that requires Random.jl # and would mutate the global RNG in sorting. pivot_index = typeof(hi-lo)(hash(lo) % (hi-lo+1)) + lo @inbounds begin pivot = v[pivot_index] while lo < pivot_index x = v[lo] fx = rev ? !lt(o, x, pivot) : lt(o, pivot, x) t[(fx ? hi : lo) - offset] = x for irest in eachindex(rest_t) rest_t[irest][(fx ? hi : lo) - offset] = rest_v[irest][lo] end offset += fx lo += 1 end while lo < hi x = v[lo+1] fx = rev ? lt(o, pivot, x) : !lt(o, x, pivot) t[(fx ? hi : lo) - offset] = x for irest in eachindex(rest_t) rest_t[irest][(fx ? hi : lo) - offset] = rest_v[irest][lo + 1] end offset += fx lo += 1 end new_pivot_index = lo-offset + pivot_index_offset for irest in eachindex(rest_pivot_dest) rest_pivot_dest[irest][new_pivot_index] = rest_v[irest][pivot_index] end pivot_index = new_pivot_index pivot_dest[pivot_index] = pivot end # t_pivot_index = lo-offset (i.e. without pivot_index_offset) # t[t_pivot_index] is whatever it was before unless t is the pivot_dest # t[<t_pivot_index] <* pivot, stable # t[>t_pivot_index] >* pivot, reverse stable pivot_index end @inline function _sort!(v::AbstractVector, rest, a::ScratchQuickSort, o::Ordering, kw; t=nothing, offset=nothing, swap=false, rev=false, rest_scratch = nothing) @getkw lo hi scratch if t === nothing scratch, t = make_scratch(scratch, eltype(v), hi-lo+1) offset = 1-lo kw = (;kw..., scratch) end if rest_scratch === nothing rest_scratch = similar_rest(rest) end while lo < hi && hi - lo > SMALL_THRESHOLD j = if swap partition!(v, lo+offset, hi+offset, offset, o, t, rev, v, 0, rest, rest_scratch, rest) else partition!(t, lo, hi, -offset, o, v, rev, v, -offset, rest_scratch, rest, rest) end swap = !swap # For ScratchQuickSort(), a.lo === a.hi === missing, so the first two branches get skipped if !ismissing(a.lo) && j <= a.lo # Skip sorting the lower part if swap copyto!(v, lo, t, lo+offset, j-lo) for irest in eachindex(rest) copyto!(rest[irest], lo, rest_scratch[irest], lo+offset, j-lo) end end if rev reverse!(v, lo, j-1) reverse_rest!(rest, lo, j-1) end lo = j+1 rev = !rev elseif !ismissing(a.hi) && a.hi <= j # Skip sorting the upper part if swap copyto!(v, j+1, t, j+1+offset, hi-j) for irest in eachindex(rest) copyto!(rest[irest], j+1, rest_scratch[irest], j+1+offset, hi-j) end end if rev reverse!(v, j+1, hi) reverse_rest!(rest, j+1, hi) end hi = j-1 elseif j-lo < hi-j # Sort the lower part recursively because it is smaller. Recursing on the # smaller part guarantees O(log(n)) stack space even on pathological inputs. _sort!(v, rest, a, o, (;kw..., lo, hi=j-1); t, offset, swap, rev, rest_scratch) lo = j+1 rev = !rev else # Sort the higher part recursively _sort!(v, rest, a, o, (;kw..., lo=j+1, hi); t, offset, swap, rev=!rev, rest_scratch) hi = j-1 end end hi < lo && return scratch if swap copyto!(v, lo, t, lo + offset, hi-lo+1) for irest in eachindex(rest) copyto!(rest[irest], lo, rest_scratch[irest], lo+offset, hi-lo+1) end end if rev reverse!(v, lo, hi) reverse_rest!(rest, lo, hi) end _sort!(v, rest, a.next, o, (;kw..., lo, hi)) end """ StableCheckSorted(next) <: Algorithm Check if an input is sorted and/or reverse-sorted. The definition of reverse-sorted is that for every pair of adjacent elements, the latter is less than the former. This is stricter than `issorted(v, Reverse(o))` to avoid swapping pairs of elements that compare equal. """ struct StableCheckSorted{T<:Algorithm} <: Algorithm next::T end @inline function _sort!(v::AbstractVector, rest, a::StableCheckSorted, o::Ordering, kw) @getkw lo hi scratch if _issorted(v, lo, hi, o) return scratch elseif _issorted(v, lo, hi, Lt((x, y) -> !lt(o, x, y))) # Reverse only if necessary. Using issorted(..., Reverse(o)) would violate stability. reverse!(v, lo, hi) reverse_rest!(rest, lo, hi) return scratch end _sort!(v, rest, a.next, o, kw) end # The return value indicates whether v is sorted (true) or t is sorted (false) # This is one of the many reasons radix_sort! is not exported. function radix_sort!(v::AbstractVector{U}, lo::Integer, hi::Integer, bits::Unsigned, t::AbstractVector{U}, offset::Integer,rest,rest_ts, chunk_size=radix_chunk_size_heuristic(lo, hi, bits)) where U <: Unsigned # bits is unsigned for performance reasons. counts = Vector{Int}(undef, 1 << chunk_size + 1) # TODO use scratch for this #println("In Radixsort main func") shift = 0 while true @noinline radix_sort_pass!(t, lo, hi, offset, counts, v, shift, chunk_size, rest_ts,rest) # the latest data resides in t shift += chunk_size shift < bits || return false @noinline radix_sort_pass!(v, lo+offset, hi+offset, -offset, counts, t, shift, chunk_size, rest, rest_ts) # the latest data resides in v shift += chunk_size shift < bits || return true end end function radix_sort_pass!(t, lo, hi, offset, counts, v, shift, chunk_size, rest_ts, rest) mask = UInt(1) << chunk_size - 1 # mask is defined in pass so that the compiler @inbounds begin # ↳ knows it's shape # counts[2:mask+2] will store the number of elements that fall into each bucket. # if chunk_size = 8, counts[2] is bucket 0x00 and counts[257] is bucket 0xff. counts .= 0 for k in lo:hi x = v[k] # lookup the element i = (x >> shift)&mask + 2 # compute its bucket's index for this pass counts[i] += 1 # increment that bucket's count end counts[1] = lo + offset # set target index for the first bucket cumsum!(counts, counts) # set target indices for subsequent buckets # counts[1:mask+1] now stores indices where the first member of each bucket # belongs, not the number of elements in each bucket. We will put the first element # of bucket 0x00 in t[counts[1]], the next element of bucket 0x00 in t[counts[1]+1], # and the last element of bucket 0x00 in t[counts[2]-1]. for k in lo:hi x = v[k] # lookup the element i = (x >> shift)&mask + 1 # compute its bucket's index for this pass j = counts[i] # lookup the target index t[j] = x # put the element where it belongs for irest in eachindex(rest) #println("Type of ID $j, $k") rest_ts[irest][j] = rest[irest][k] # t_ = rest_ts[irest] # v_ = rest[irest] # t_[j] = v_[k] end counts[i] = j + 1 # increment the target index for the next end # ↳ element in this bucket end end function radix_chunk_size_heuristic(lo::Integer, hi::Integer, bits::Unsigned) # chunk_size is the number of bits to radix over at once. # We need to allocate an array of size 2^chunk size, and on the other hand the higher # the chunk size the fewer passes we need. Theoretically, chunk size should be based on # the Lambert W function applied to length. Empirically, we use this heuristic: guess = min(10, log(maybe_unsigned(hi-lo))*3/4+3) # TODO the maximum chunk size should be based on architecture cache size. # We need iterations * chunk size ≥ bits, and these cld's # make an effort to get iterations * chunk size ≈ bits UInt8(cld(bits, cld(bits, guess))) end maybe_unsigned(x::Integer) = x # this is necessary to avoid calling unsigned on BigInt maybe_unsigned(x::BitSigned) = unsigned(x) function _issorted(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering) @boundscheck checkbounds(v, lo:hi) @inbounds for i in (lo+1):hi lt(o, v[i], v[i-1]) && return false end true end ## default sorting policy ## """ InitialOptimizations(next) <: Algorithm Attempt to apply a suite of low-cost optimizations to the input vector before sorting. These optimizations may be automatically applied by the `sort!` family of functions when `alg=InsertionSort`, `alg=MergeSort`, or `alg=QuickSort` is passed as an argument. `InitialOptimizations` is an implementation detail and subject to change or removal in future versions of Julia. If `next` is stable, then `InitialOptimizations(next)` is also stable. The specific optimizations attempted by `InitialOptimizations` are [`MissingOptimization`](@ref), [`BoolOptimization`](@ref), dispatch to [`InsertionSort`](@ref) for inputs with `length <= 10`, and [`IEEEFloatOptimization`](@ref). """ InitialOptimizations(next) = MissingOptimization( BoolOptimization( Small{10}( IEEEFloatOptimization( next)))) """ DEFAULT_STABLE The default sorting algorithm. This algorithm is guaranteed to be stable (i.e. it will not reorder elements that compare equal). It makes an effort to be fast for most inputs. The algorithms used by `DEFAULT_STABLE` are an implementation detail. See extended help for the current dispatch system. # Extended Help `DEFAULT_STABLE` is composed of two parts: the [`InitialOptimizations`](@ref) and a hybrid of Radix, Insertion, Counting, Quick sorts. We begin with MissingOptimization because it has no runtime cost when it is not triggered and can enable other optimizations to be applied later. For example, BoolOptimization cannot apply to an `AbstractVector{Union{Missing, Bool}}`, but after [`MissingOptimization`](@ref) is applied, that input will be converted into am `AbstractVector{Bool}`. We next apply [`BoolOptimization`](@ref) because it also has no runtime cost when it is not triggered and when it is triggered, it is an incredibly efficient algorithm (sorting `Bool`s is quite easy). Next, we dispatch to [`InsertionSort`](@ref) for inputs with `length <= 10`. This dispatch occurs before the [`IEEEFloatOptimization`](@ref) pass because the [`IEEEFloatOptimization`](@ref)s are not beneficial for very small inputs. To conclude the [`InitialOptimizations`](@ref), we apply [`IEEEFloatOptimization`](@ref). After these optimizations, we branch on whether radix sort and related algorithms can be applied to the input vector and ordering. We conduct this branch by testing if `UIntMappable(v, order) !== nothing`. That is, we see if we know of a reversible mapping from `eltype(v)` to `UInt` that preserves the ordering `order`. We perform this check after the initial optimizations because they can change the input vector's type and ordering to make them `UIntMappable`. If the input is not [`UIntMappable`](@ref), then we perform a presorted check and dispatch to [`ScratchQuickSort`](@ref). Otherwise, we dispatch to [`InsertionSort`](@ref) for inputs with `length <= 40` and then perform a presorted check ([`CheckSorted`](@ref)). We check for short inputs before performing the presorted check to avoid the overhead of the check for small inputs. Because the alternate dispatch is to [`InsertionSort`](@ref) which has efficient `O(n)` runtime on presorted inputs, the check is not necessary for small inputs. We check if the input is reverse-sorted for long vectors (more than 500 elements) because the check is essentially free unless the input is almost entirely reverse sorted. Note that once the input is determined to be [`UIntMappable`](@ref), we know the order forms a [total order](wikipedia.org/wiki/Total_order) over the inputs and so it is impossible to perform an unstable sort because no two elements can compare equal unless they _are_ equal, in which case switching them is undetectable. We utilize this fact to perform a more aggressive reverse sorted check that will reverse the vector `[3, 2, 2, 1]`. After these potential fast-paths are tried and failed, we [`ComputeExtrema`](@ref) of the input. This computation has a fairly fast `O(n)` runtime, but we still try to delay it until it is necessary. Next, we [`ConsiderCountingSort`](@ref). If the range the input is small compared to its length, we apply [`CountingSort`](@ref). Next, we [`ConsiderRadixSort`](@ref). This is similar to the dispatch to counting sort, but we conside rthe number of _bits_ in the range, rather than the range itself. Consequently, we apply [`RadixSort`](@ref) for any reasonably long inputs that reach this stage. Finally, if the input has length less than 80, we dispatch to [`InsertionSort`](@ref) and otherwise we dispatch to [`ScratchQuickSort`](@ref). """ const DEFAULT_STABLE = InitialOptimizations( IsUIntMappable( Small{40}( CheckSorted( ComputeExtrema( # SyncSort: Removed ConsiderCountingSort ConsiderRadixSort( Small{80}( ScratchQuickSort()))))), StableCheckSorted( ScratchQuickSort()))) """ DEFAULT_UNSTABLE An efficient sorting algorithm. The algorithms used by `DEFAULT_UNSTABLE` are an implementation detail. They are currently the same as those used by [`DEFAULT_STABLE`](@ref), but this is subject to change in future. """ const DEFAULT_UNSTABLE = DEFAULT_STABLE const SMALL_THRESHOLD = 20 function Base.show(io::IO, alg::Algorithm) print_tree(io, alg, 0) end function print_tree(io::IO, alg::Algorithm, cols::Int) print(io, " "^cols) show_type(io, alg) print(io, '(') for (i, name) in enumerate(fieldnames(typeof(alg))) arg = getproperty(alg, name) i > 1 && print(io, ',') if arg isa Algorithm #println(io) print_tree(io, arg, cols+1) else i > 1 && print(io, ' ') print(io, arg) end end print(io, ')') end show_type(io::IO, alg::Algorithm) = Base.show_type_name(io, typeof(alg).name) show_type(io::IO, alg::Small{N}) where N = print(io, "Base.Sort.Small{$N}") defalg(v::AbstractArray) = DEFAULT_STABLE defalg(v::AbstractArray{<:Union{Number, Missing}}) = DEFAULT_UNSTABLE defalg(v::AbstractArray{Missing}) = DEFAULT_UNSTABLE # for method disambiguation defalg(v::AbstractArray{Union{}}) = DEFAULT_UNSTABLE # for method disambiguation """ sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) Sort the vector `v` in place. A stable algorithm is used by default. You can select a specific algorithm to use via the `alg` keyword (see [Sorting Algorithms](@ref) for available algorithms). The `by` keyword lets you provide a function that will be applied to each element before comparison; the `lt` keyword allows providing a custom "less than" function (note that for every `x` and `y`, only one of `lt(x,y)` and `lt(y,x)` can return `true`); use `rev=true` to reverse the sorting order. `rev=true` preserves forward stability: Elements that compare equal are not reversed. These options are independent and can be used together in all possible combinations: if both `by` and `lt` are specified, the `lt` function is applied to the result of the `by` function; `rev=true` reverses whatever ordering specified via the `by` and `lt` keywords. # Examples ```jldoctest julia> v = [3, 1, 2]; sort!(v); v 3-element Vector{Int64}: 1 2 3 julia> v = [3, 1, 2]; sort!(v, rev = true); v 3-element Vector{Int64}: 3 2 1 julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[1]); v 3-element Vector{Tuple{Int64, String}}: (1, "c") (2, "b") (3, "a") julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[2]); v 3-element Vector{Tuple{Int64, String}}: (3, "a") (2, "b") (1, "c") ``` """ function syncsort!(v::AbstractVector{T}, rest...; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward, scratch::Union{Vector{T}, Nothing}=nothing) where T for r in rest @assert r isa AbstractVector @assert size(v,1) == size(r,1) end _sort!(v, rest, maybe_apply_initial_optimizations(alg), ord(lt,by,rev,order), (;scratch),) v end """ sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) Variant of [`sort!`](@ref) that returns a sorted copy of `v` leaving `v` itself unmodified. Uses `Base.copymutable` to support immutable collections and iterables. !!! compat "Julia 1.10" `sort` of arbitrary iterables requires at least Julia 1.10. # Examples ```jldoctest julia> v = [3, 1, 2]; julia> sort(v) 3-element Vector{Int64}: 1 2 3 julia> v 3-element Vector{Int64}: 3 1 2 ``` """ function sort(v; kws...) size = IteratorSize(v) size == HasShape{0}() && throw(ArgumentError("$v cannot be sorted")) size == IsInfinite() && throw(ArgumentError("infinite iterator $v cannot be sorted")) sort!(copymutable(v); kws...) end sort(v::AbstractVector; kws...) = sort!(copymutable(v); kws...) # for method disambiguation sort(::AbstractString; kws...) = throw(ArgumentError("sort(::AbstractString) is not supported")) sort(::Tuple; kws...) = throw(ArgumentError("sort(::Tuple) is only supported for NTuples")) function sort(x::NTuple{N}; lt::Function=isless, by::Function=identity, rev::Union{Bool,Nothing}=nothing, order::Ordering=Forward) where N o = ord(lt,by,rev,order) if N > 9 v = sort!(copymutable(x), DEFAULT_STABLE, o) tuple((v[i] for i in 1:N)...) else _sort(x, o) end end _sort(x::Union{NTuple{0}, NTuple{1}}, o::Ordering) = x function _sort(x::NTuple, o::Ordering) a, b = Base.IteratorsMD.split(x, Val(length(x)>>1)) merge(_sort(a, o), _sort(b, o), o) end merge(x::NTuple, y::NTuple{0}, o::Ordering) = x merge(x::NTuple{0}, y::NTuple, o::Ordering) = y merge(x::NTuple{0}, y::NTuple{0}, o::Ordering) = x # Method ambiguity merge(x::NTuple, y::NTuple, o::Ordering) = (lt(o, y[1], x[1]) ? (y[1], merge(x, tail(y), o)...) : (x[1], merge(tail(x), y, o)...)) ## uint mapping to allow radix sorting primitives other than UInts ## """ UIntMappable(T::Type, order::Ordering) Return `typeof(uint_map(x::T, order))` if [`uint_map`](@ref) and [`uint_unmap`](@ref) are implemented. If either is not implemented, return `nothing`. """ UIntMappable(T::Type, order::Ordering) = nothing """ uint_map(x, order::Ordering)::Unsigned Map `x` to an un unsigned integer, maintaining sort order. The map should be reversible with [`uint_unmap`](@ref), so `isless(order, a, b)` must be a linear ordering for `a, b <: typeof(x)`. Satisfies `isless(order, a, b) === (uint_map(a, order) < uint_map(b, order))` and `x === uint_unmap(typeof(x), uint_map(x, order), order)` See also: [`UIntMappable`](@ref) [`uint_unmap`](@ref) """ function uint_map end """ uint_unmap(T::Type, u::Unsigned, order::Ordering) Reconstruct the unique value `x::T` that uint_maps to `u`. Satisfies `x === uint_unmap(T, uint_map(x::T, order), order)` for all `x <: T`. See also: [`uint_map`](@ref) [`UIntMappable`](@ref) """ function uint_unmap end ### Primitive Types # Integers uint_map(x::Unsigned, ::ForwardOrdering) = x uint_unmap(::Type{T}, u::T, ::ForwardOrdering) where T <: Unsigned = u uint_map(x::Signed, ::ForwardOrdering) = unsigned(xor(x, typemin(x))) uint_unmap(::Type{T}, u::Unsigned, ::ForwardOrdering) where T <: Signed = xor(signed(u), typemin(T)) UIntMappable(T::BitIntegerType, ::ForwardOrdering) = unsigned(T) # Floats are not UIntMappable under regular orderings because they fail on NaN edge cases. # uint mappings for floats are defined in Float, where the Left and Right orderings # guarantee that there are no NaN values # Chars uint_map(x::Char, ::ForwardOrdering) = reinterpret(UInt32, x) uint_unmap(::Type{Char}, u::UInt32, ::ForwardOrdering) = reinterpret(Char, u) UIntMappable(::Type{Char}, ::ForwardOrdering) = UInt32 ### Reverse orderings uint_map(x, rev::ReverseOrdering) = ~uint_map(x, rev.fwd) uint_unmap(T::Type, u::Unsigned, rev::ReverseOrdering) = uint_unmap(T, ~u, rev.fwd) UIntMappable(T::Type, order::ReverseOrdering) = UIntMappable(T, order.fwd) ### Vectors # Convert v to unsigned integers in place, maintaining sort order. function uint_map!(v::AbstractVector, lo::Integer, hi::Integer, order::Ordering) u = reinterpret(UIntMappable(eltype(v), order), v) @inbounds for i in lo:hi u[i] = uint_map(v[i], order) end u end function uint_unmap!(v::AbstractVector, u::AbstractVector{U}, rest_v, rest_u, lo::Integer, hi::Integer, order::Ordering, offset::U=zero(U), index_offset::Integer=0) where U <: Unsigned @inbounds for i in lo:hi v[i] = uint_unmap(eltype(v), u[i+index_offset]+offset, order) for irest in eachindex(rest_v) rest_v[irest][i] = rest_u[irest][i + index_offset] end end v end ### Unused constructs for backward compatibility ### ## Old algorithms ## struct QuickSortAlg <: Algorithm end struct MergeSortAlg <: Algorithm end """ PartialQuickSort{T <: Union{Integer,OrdinalRange}} Indicate that a sorting function should use the partial quick sort algorithm. Partial quick sort returns the smallest `k` elements sorted from smallest to largest, finding them and sorting them using [`QuickSort`](@ref). Characteristics: * *not stable*: does not preserve the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *in-place* in memory. * *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref). Note that `PartialQuickSort(k)` does not necessarily sort the whole array. For example, ```jldoctest julia> x = rand(100); julia> k = 50:100; julia> s1 = sort(x; alg=QuickSort); julia> s2 = sort(x; alg=PartialQuickSort(k)); julia> map(issorted, (s1, s2)) (true, false) julia> map(x->issorted(x[k]), (s1, s2)) (true, true) julia> s1[k] == s2[k] true ``` """ struct PartialQuickSort{T <: Union{Integer,OrdinalRange}} <: Algorithm k::T end """ QuickSort Indicate that a sorting function should use the quick sort algorithm, which is *not* stable. Characteristics: * *not stable*: does not preserve the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *in-place* in memory. * *divide-and-conquer*: sort strategy similar to [`MergeSort`](@ref). * *good performance* for large collections. """ const QuickSort = QuickSortAlg() """ MergeSort Indicate that a sorting function should use the merge sort algorithm. Merge sort divides the collection into subcollections and repeatedly merges them, sorting each subcollection at each step, until the entire collection has been recombined in sorted form. Characteristics: * *stable*: preserves the ordering of elements which compare equal (e.g. "a" and "A" in a sort of letters which ignores case). * *not in-place* in memory. * *divide-and-conquer* sort strategy. * *good performance* for large collections but typically not quite as fast as [`QuickSort`](@ref). """ const MergeSort = MergeSortAlg() maybe_apply_initial_optimizations(alg::Algorithm) = alg maybe_apply_initial_optimizations(alg::QuickSortAlg) = InitialOptimizations(alg) maybe_apply_initial_optimizations(alg::MergeSortAlg) = InitialOptimizations(alg) maybe_apply_initial_optimizations(alg::InsertionSortAlg) = InitialOptimizations(alg) # selectpivot! # # Given 3 locations in an array (lo, mi, and hi), sort v[lo], v[mi], v[hi] and # choose the middle value as a pivot # # Upon return, the pivot is in v[lo], and v[hi] is guaranteed to be # greater than the pivot @inline function selectpivot!(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering) @inbounds begin mi = midpoint(lo, hi) # sort v[mi] <= v[lo] <= v[hi] such that the pivot is immediately in place if lt(o, v[lo], v[mi]) v[mi], v[lo] = v[lo], v[mi] end if lt(o, v[hi], v[lo]) if lt(o, v[hi], v[mi]) v[hi], v[lo], v[mi] = v[lo], v[mi], v[hi] else v[hi], v[lo] = v[lo], v[hi] end end # return the pivot return v[lo] end end # partition! # # select a pivot, and partition v according to the pivot function partition!(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering) pivot = selectpivot!(v, lo, hi, o) # pivot == v[lo], v[hi] > pivot i, j = lo, hi @inbounds while true i += 1; j -= 1 while lt(o, v[i], pivot); i += 1; end; while lt(o, pivot, v[j]); j -= 1; end; i >= j && break v[i], v[j] = v[j], v[i] end v[j], v[lo] = pivot, v[j] # v[j] == pivot # v[k] >= pivot for k > j # v[i] <= pivot for i < j return j end function sort!(v::AbstractVector, lo::Integer, hi::Integer, a::QuickSortAlg, o::Ordering) @inbounds while lo < hi hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) j = partition!(v, lo, hi, o) if j-lo < hi-j # recurse on the smaller chunk # this is necessary to preserve O(log(n)) # stack space in the worst case (rather than O(n)) lo < (j-1) && sort!(v, lo, j-1, a, o) lo = j+1 else j+1 < hi && sort!(v, j+1, hi, a, o) hi = j-1 end end return v end sort!(v::AbstractVector{T}, lo::Integer, hi::Integer, a::MergeSortAlg, o::Ordering, t0::Vector{T}) where T = invoke(sort!, Tuple{typeof.((v, lo, hi, a, o))..., AbstractVector{T}}, v, lo, hi, a, o, t0) # For disambiguation function sort!(v::AbstractVector{T}, lo::Integer, hi::Integer, a::MergeSortAlg, o::Ordering, t0::Union{AbstractVector{T}, Nothing}=nothing) where T @inbounds if lo < hi hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) m = midpoint(lo, hi) t = t0 === nothing ? similar(v, m-lo+1) : t0 length(t) < m-lo+1 && resize!(t, m-lo+1) Base.require_one_based_indexing(t) sort!(v, lo, m, a, o, t) sort!(v, m+1, hi, a, o, t) i, j = 1, lo while j <= m t[i] = v[j] i += 1 j += 1 end i, k = 1, lo while k < j <= hi if lt(o, v[j], t[i]) v[k] = v[j] j += 1 else v[k] = t[i] i += 1 end k += 1 end while k < j v[k] = t[i] k += 1 i += 1 end end return v end function sort!(v::AbstractVector, lo::Integer, hi::Integer, a::PartialQuickSort, o::Ordering) @inbounds while lo < hi hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) j = partition!(v, lo, hi, o) if j <= first(a.k) lo = j+1 elseif j >= last(a.k) hi = j-1 else # recurse on the smaller chunk # this is necessary to preserve O(log(n)) # stack space in the worst case (rather than O(n)) if j-lo < hi-j lo < (j-1) && sort!(v, lo, j-1, a, o) lo = j+1 else hi > (j+1) && sort!(v, j+1, hi, a, o) hi = j-1 end end end return v end end # module Sort
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
code
27559
# File : SyncSort.jl # License: MIT # Author : Dominik Werner <[email protected]> # Date : 26.01.2023 # Paper : https://drive.google.com/file/d/0B7uLFueU4vLfcjJfZFh3TlIxMFE/view?resourcekey=0-8Ovsx4PtAJn78xLboBEb_g module SyncSort using Base.Order using Base: copymutable, midpoint, require_one_based_indexing, uinttype, sub_with_overflow, add_with_overflow, OneTo, BitSigned, BitIntegerType, IteratorSize, HasShape, IsInfinite, tail, midpoint import Base: sort, sort!, issorted, sortperm, to_indices, midpoint using KernelAbstractions using KernelAbstractions.Extras.LoopInfo: @unroll export merge_sort_gpu! """ Sort an array in parallel using a merge sort algorithm. The array is sorted in place. # Arguments - `v`: array to be sorted - `elements_per_thread`: number of elements to be sorted by each thread - `v2`: temporary array to be used for swapping - `global_tile_ranks`: temporary array to be used for storing the ranks of the splitters """ function merge_sort_gpu!( v::AbstractVector, ::Val{elements_per_thread}, v2::AbstractVector=similar(v), #global_tile_ranks::AbstractVector=CuArray(fill((-1, -1), (div(length(v), elements_per_thread, RoundUp)))), global_tile_ranks::AbstractVector=similar(v,typeof((-1, -1)), (div(length(v), elements_per_thread, RoundUp))), ) where {elements_per_thread} # check on which backend we are running and set the device dev = get_backend(v) # Keep a pointer to the original array as we'll be swapping vpointer = v vlength = length(v) # Calculate the number of threads based on the number of elements and the length of the input array num_threads = div(vlength, elements_per_thread, RoundUp) # sort each block consisting of 'elements_per_thread' elements using insertion_sort initial_sort_kernel!(dev, 64)(v, elements_per_thread, ndrange=num_threads) KernelAbstractions.synchronize(dev) # Step 3: Merging subblock_size = elements_per_thread merge_block_size = elements_per_thread * 2 threads_per_merge_block = 2 # Every loop iteration, double the merge block size generate_ranks_kernel_function! = generate_ranks_kernel!(dev, 64) merge_two_blocks_kernel_function! = merge_two_blocks_kernel!(dev, 64) while merge_block_size < vlength * 2 # The number of blocks we need to merge num_blocks = div(vlength, merge_block_size, RoundUp) num_subblocks = div(2 * vlength, merge_block_size, RoundUp) # Calculate the ranks for each thread generate_ranks_kernel_function!( v, global_tile_ranks, merge_block_size, threads_per_merge_block, num_threads, subblock_size, num_subblocks, num_blocks, ndrange=num_threads) KernelAbstractions.synchronize(dev) # Merge phase. merge_two_blocks_kernel_function!( v, v2, global_tile_ranks, merge_block_size, threads_per_merge_block, num_threads, subblock_size, num_subblocks, num_blocks, ndrange=num_threads) KernelAbstractions.synchronize(dev) # Swap arrays v, v2 = v2, v # The length of an array subsection that is sorted is now bigger subblock_size = merge_block_size merge_block_size *= 2 threads_per_merge_block *= 2 end # If we ended up with the second array as the result, swap it back if v2 === vpointer vpointer .= v end nothing end @kernel function initial_sort_kernel!(v, elements_per_thread) # xtract global index and the start and end of this block index = @index(Global, Linear) start_array_index = (index - 1) * elements_per_thread + 1 end_array_index = min(start_array_index + elements_per_thread - 1, size(v, 1)) # now simply sort a view of this array sub_v = @view v[start_array_index:end_array_index] insertion_sort!(sub_v) #sort!(sub_v) nothing end function insertion_sort!( v::AbstractVector, ) i = firstindex(v) + 1 @inbounds while i <= lastindex(v) x = v[i] j = i - 1 while j >= firstindex(v) && v[j] > x v[j+1] = v[j] j -= 1 end v[j+1] = x i += 1 end nothing end @kernel function generate_ranks_kernel!(v, ranks, merge_block_size, threads_per_merge_block, num_threads, subblock_size, num_subblocks, num_blocks, ) index = @index(Global, Linear) if threads_per_merge_block > num_threads threads_per_merge_block = num_threads end # First we calculate where the merge block starts and which rank # inside the merge block the current thread is merge_block_index = div(index - 1, threads_per_merge_block, RoundDown) + 1 merge_block_start_index = (merge_block_index - 1) * merge_block_size + 1 merge_block_end_index = merge_block_start_index + merge_block_size - 1 if merge_block_end_index > size(v, 1) # we are at the last merge block merge_block_end_index = size(v, 1) end merge_block = @view v[merge_block_start_index:merge_block_end_index] # calculate the current rank id of the thread within the merge block rank_id = mod(index - 1, threads_per_merge_block) + 1 if merge_block_index == num_blocks && num_subblocks % 2 == 1 # do nothing because we are copying this chunk later else if rank_id == threads_per_merge_block || index == num_threads #last ranks are always the last elements in subblocks ranks[index] = (subblock_size, size(merge_block, 1)) else # Now we find the index for the current rank, search fr it in the # right rank with binary search and store it in "ranks" index_splitter_left_subblock = div( rank_id * subblock_size, threads_per_merge_block, RoundDown, ) splitter_left_subblock = merge_block[index_splitter_left_subblock] if splitter_left_subblock < merge_block[subblock_size+1] # if the smallest element of the right subblock, then we dont need to search ranks[index] = (index_splitter_left_subblock, subblock_size) else right_subblock = @view merge_block[subblock_size+1:end] index_splitter_right_subblock = subblock_size + binary_search( right_subblock, splitter_left_subblock, ) ranks[index] = (index_splitter_left_subblock, index_splitter_right_subblock) end end end end # Binary search to find the rank of an element within a block # array must be ordered (obviously) function binary_search(array::AbstractVector, target) low = 1 high = size(array, 1) @inbounds while low < high index = low + div(high - low + 1, 2, RoundDown) if target < array[index] high = index - 1 else low = index end end low end @kernel function merge_two_blocks_kernel!( v, v2, tile_ranks, merge_block_size, threads_per_merge_block, num_threads, subblock_size, num_subblocks, num_blocks, ) index = @index(Global, Linear) # First we calculate where the merge block starts and which rank # inside the merge block the current thread is merge_block_index = div(index - 1, threads_per_merge_block, RoundDown) + 1 merge_block_start_index = (merge_block_index - 1) * merge_block_size + 1 merge_block_end_index = merge_block_start_index + merge_block_size - 1 if merge_block_end_index > size(v, 1) # we are at the last merge block merge_block_end_index = size(v, 1) #threads_per_merge_block = div(merge_block_end_index - merge_block_start_index + 1, elements_per_thread, RoundUp) end if threads_per_merge_block > num_threads threads_per_merge_block = num_threads end # calculate the current rank id of the thread within the merge block rank_id = mod(index - 1, threads_per_merge_block) + 1 merge_block = @view v[merge_block_start_index:merge_block_end_index] if merge_block_index == num_blocks && num_subblocks % 2 == 1 # copy the last subblock to the output array if rank_id == 1 for i in merge_block_start_index:merge_block_end_index v2[i] = v[i] end end else # Now we find the index for the current rank, search # for the element in the other block and insert it left_end, right_end = tile_ranks[index] # print all data with @print if rank_id == 1 left_start = firstindex(v) right_start = firstindex(v) + subblock_size merge_array_insert_start_index = firstindex(v) else left_start = tile_ranks[index-1][1] + 1 right_start = tile_ranks[index-1][2] + 1 merge_array_insert_start_index = ( tile_ranks[index-1][1] + tile_ranks[index-1][2] - subblock_size + 1 ) end tile_a = @view merge_block[left_start:left_end] tile_b = @view merge_block[right_start:right_end] #println(" right start: $right_start, $right_end, $merge_block_index") size_a = size(tile_a, 1) size_b = size(tile_b, 1) merge_tile_start_index = merge_block_start_index + merge_array_insert_start_index - 1 merge_tile_end_index = merge_block_start_index + merge_array_insert_start_index + size_a + size_b - 2 if merge_tile_end_index > size(v2, 1) merge_tile_end_index = size(v2, 1) end merge_tile = @view v2[merge_tile_start_index:merge_tile_end_index] merge_subblock!(merge_tile, tile_a, tile_b) #println("Index: $index\na: $tile_a\nb: $tile_b\nMerged: $merge_tile") end end # Merge two blocks A and B, running on a single thread # Optimization notes: # type of those blocks is the same, something like ::view{::AbstractVector{T}} # with a constant size, it should be always the same # do i wnat this to be in place or should it return? function merge_subblock!(merge_tile, tile_a, tile_b) @assert size(merge_tile,1) == size(tile_a,1) + size(tile_b,1) tile_a_size = size(tile_a, 1) tile_b_size = size(tile_b, 1) # This could be redundant if tile_a_size == 0 #println("\n\nFUCK YOU DOMINIK\n\n") @inbounds for i in axes(merge_tile, 1) merge_tile[i] = tile_b[i] end return end if tile_b_size == 0 @inbounds for i in axes(merge_tile, 1) merge_tile[i] = tile_a[i] end return end a_index = firstindex(tile_a) b_index = firstindex(tile_b) # Merge all elements. some might be left over @inbounds for merge_index in axes(merge_tile, 1) if tile_a[a_index] <= tile_b[b_index] merge_tile[merge_index] = tile_a[a_index] a_index += 1 if a_index > tile_a_size # Merge the rest of the b-block # TODO: make this looping more elegant j = 0 for i in merge_index+1:lastindex(merge_tile) merge_tile[i] = tile_b[b_index+j] j += 1 end break end else merge_tile[merge_index] = tile_b[b_index] b_index += 1 if b_index > tile_b_size # Merge the rest of the a-block j = 0 for i in merge_index+1:lastindex(merge_tile) merge_tile[i] = tile_a[a_index+j] j += 1 end break end end end end lt=isless """ Quicksort taken from Julia/base """ midpoint(lo::T, hi::T) where T<:Integer = lo + ((hi - lo) >>> 0x01) midpoint(lo::Integer, hi::Integer) = midpoint(promote(lo, hi)...) function quicksort!(v::AbstractVector, lo::Integer, hi::Integer) @inbounds while lo < hi hi-lo <= 20 && return sort!(v, lo, hi, InsertionSort, Base.Order.Forward) j = partition!(v, lo, hi) if j-lo < hi-j # recurse on the smaller chunk # this is necessary to preserve O(log(n)) # stack space in the worst case (rather than O(n)) lo < (j-1) && quicksort!(v, lo, j-1) lo = j+1 else j+1 < hi && quicksort!(v, j+1, hi) hi = j-1 end end return v end function partition!(v::AbstractVector, lo::Integer, hi::Integer) pivot = selectpivot!(v, lo, hi) # pivot == v[lo], v[hi] > pivot i, j = lo, hi @inbounds while true i += 1; j -= 1 while isless( v[i], pivot); i += 1; end; while isless( pivot, v[j]); j -= 1; end; i >= j && break v[i], v[j] = v[j], v[i] end v[j], v[lo] = pivot, v[j] return j end @inline function selectpivot!(v::AbstractVector, lo::Integer, hi::Integer) @inbounds begin mi = midpoint(lo, hi) # sort v[mi] <= v[lo] <= v[hi] such that the pivot is immediately in place if isless( v[lo], v[mi]) v[mi], v[lo] = v[lo], v[mi] end if isless( v[hi], v[lo]) if isless( v[hi], v[mi]) v[hi], v[lo], v[mi] = v[lo], v[mi], v[hi] else v[hi], v[lo] = v[lo], v[hi] end end # return the pivot return v[lo] end end ########## Scratch Quick Sort from Julia/base Algorithm = Base.Sort.Algorithm SMALL_ALGORITHM = InsertionSort macro getkw(syms...) getters = (getproperty(Base.Sort, Symbol(:_, sym)) for sym in syms) Expr(:block, (:($(esc(:((kw, $sym) = $getter(v, kw))))) for (sym, getter) in zip(syms, getters))...) end """ make_scratch(scratch::Union{Nothing, Vector}, T::Type, len::Integer) Returns `(s, t)` where `t` is an `AbstractVector` of type `T` with length at least `len` that is backed by the `Vector` `s`. If `scratch !== nothing`, then `s === scratch`. This function will allocate a new vector if `scratch === nothing`, `resize!` `scratch` if it is too short, and `reinterpret` `scratch` if its eltype is not `T`. """ function make_scratch(scratch::Nothing, T::Type, len::Integer) s = Vector{T}(undef, len) s, s end function make_scratch(scratch::Vector{T}, ::Type{T}, len::Integer) where T len > length(scratch) && resize!(scratch, len) scratch, scratch end function make_scratch(scratch::Vector, T::Type, len::Integer) len_bytes = len * sizeof(T) len_scratch = div(len_bytes, sizeof(eltype(scratch))) len_scratch > length(scratch) && resize!(scratch, len_scratch) scratch, reinterpret(T, scratch) end struct ScratchQuickSort{L<:Union{Integer,Missing}, H<:Union{Integer,Missing}, T<:Algorithm} <: Algorithm lo::L hi::H next::T end ScratchQuickSort(next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(missing, missing, next) ScratchQuickSort(lo::Union{Integer, Missing}, hi::Union{Integer, Missing}) = ScratchQuickSort(lo, hi, SMALL_ALGORITHM) ScratchQuickSort(lo::Union{Integer, Missing}, next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(lo, lo, next) ScratchQuickSort(r::OrdinalRange, next::Algorithm=SMALL_ALGORITHM) = ScratchQuickSort(first(r), last(r), next) function scratchpartition!(t::AbstractVector, lo::Integer, hi::Integer, offset::Integer, v::AbstractVector, rev::Bool, pivot_dest::AbstractVector, pivot_index_offset::Integer) # Ideally we would use `pivot_index = rand(lo:hi)`, but that requires Random.jl # and would mutate the global RNG in sorting. pivot_index = typeof(hi-lo)(hash(lo) % (hi-lo+1)) + lo @inbounds begin pivot = v[pivot_index] while lo < pivot_index x = v[lo] fx = rev ? !isless( x, pivot) : isless( pivot, x) t[(fx ? hi : lo) - offset] = x offset += fx lo += 1 end while lo < hi x = v[lo+1] fx = rev ? isless( pivot, x) : !isless( x, pivot) t[(fx ? hi : lo) - offset] = x offset += fx lo += 1 end pivot_index = lo-offset + pivot_index_offset pivot_dest[pivot_index] = pivot end # t_pivot_index = lo-offset (i.e. without pivot_index_offset) # t[t_pivot_index] is whatever it was before unless t is the pivot_dest # t[<t_pivot_index] <* pivot, stable # t[>t_pivot_index] >* pivot, reverse stable pivot_index end function scratchquicksort!(v::AbstractVector, a::ScratchQuickSort=ScratchQuickSort(), t=nothing, offset=nothing, swap=false, rev=false, lo = firstindex(v), hi = size(v,1), scrath = nothing) if t === nothing scratch, t = make_scratch(scratch, eltype(v), hi-lo+1) offset = 1-lo kw = (;kw..., scratch) end while lo < hi && hi - lo > 20 j = if swap scratchpartition!(v, lo+offset, hi+offset, offset, t, rev, v, 0) else scratchpartition!(t, lo, hi, -offset, v, rev, v, -offset) end swap = !swap # For ScratchQuickSort(), a.lo === a.hi === missing, so the first two branches get skipped if !ismissing(a.lo) && j <= a.lo # Skip sorting the lower part swap && copyto!(v, lo, t, lo+offset, j-lo) rev && reverse!(v, lo, j-1) lo = j+1 rev = !rev elseif !ismissing(a.hi) && a.hi <= j # Skip sorting the upper part swap && copyto!(v, j+1, t, j+1+offset, hi-j) rev || reverse!(v, j+1, hi) hi = j-1 elseif j-lo < hi-j # Sort the lower part recursively because it is smaller. Recursing on the # smaller part guarantees O(log(n)) stack space even on pathological inputs. scratchquicksort!(v, a, t, offset, swap, rev,lo = lo, hi=j-1, scratch = scratch) lo = j+1 rev = !rev else # Sort the higher part recursively scratchquicksort!(v, a, t, offset, swap, rev=!rev, lo = j+1, hi = hi, scratch = scratch) hi = j-1 end end hi < lo && return scratch swap && copyto!(v, lo, t, lo+offset, hi-lo+1) rev && reverse!(v, lo, hi) #_sort!(v, a.next, o, (;kw..., lo, hi)) v_view = @view v[lo:hi] insertion_sort!(v_view) end ################ RADIX SORT top_set_bit(x::Integer) = ceil(Integer, log2(x + oneunit(x))) """ uint_unmap(T::Type, u::Unsigned, order::Ordering) Reconstruct the unique value `x::T` that uint_maps to `u`. Satisfies `x === uint_unmap(T, uint_map(x::T, order), order)` for all `x <: T`. See also: [`uint_map`](@ref) [`UIntMappable`](@ref) """ function uint_unmap end ### Primitive Types # Integers uint_map(x::Unsigned, ::ForwardOrdering) = x uint_unmap(::Type{T}, u::T, ::ForwardOrdering) where T <: Unsigned = u uint_map(x::Signed, ::ForwardOrdering) = unsigned(xor(x, typemin(x))) uint_unmap(::Type{T}, u::Unsigned, ::ForwardOrdering) where T <: Signed = xor(signed(u), typemin(T)) UIntMappable(T::BitIntegerType, ::ForwardOrdering) = unsigned(T) # Floats are not UIntMappable under regular orderings because they fail on NaN edge cases. # uint mappings for floats are defined in Float, where the Left and Right orderings # guarantee that there are no NaN values # Chars uint_map(x::Char, ::ForwardOrdering) = reinterpret(UInt32, x) uint_unmap(::Type{Char}, u::UInt32, ::ForwardOrdering) = reinterpret(Char, u) UIntMappable(::Type{Char}, ::ForwardOrdering) = UInt32 ### Reverse orderings uint_map(x, rev::ReverseOrdering) = ~uint_map(x, rev.fwd) uint_unmap(T::Type, u::Unsigned, rev::ReverseOrdering) = uint_unmap(T, ~u, rev.fwd) UIntMappable(T::Type, order::ReverseOrdering) = UIntMappable(T, order.fwd) ### Vectors # Convert v to unsigned integers in place, maintaining sort order. function uint_map!(v::AbstractVector, lo::Integer, hi::Integer, order::Ordering) u = reinterpret(UIntMappable(eltype(v), order), v) @inbounds for i in lo:hi u[i] = uint_map(v[i], order) end u end function uint_unmap!(v::AbstractVector, u::AbstractVector{U}, lo::Integer, hi::Integer, order::Ordering, offset::U=zero(U), index_offset::Integer=0) where U <: Unsigned @inbounds for i in lo:hi v[i] = uint_unmap(eltype(v), u[i+index_offset]+offset, order) end v end """ send_to_end!(f::Function, v::AbstractVector; [lo, hi]) Send every element of `v` for which `f` returns `true` to the end of the vector and return the index of the last element for which `f` returns `false`. `send_to_end!(f, v, lo, hi)` is equivalent to `send_to_end!(f, view(v, lo:hi))+lo-1` Preserves the order of the elements that are not sent to the end. """ function send_to_end!(f::F, v::AbstractVector; lo=firstindex(v), hi=lastindex(v)) where F <: Function i = lo @inbounds while i <= hi && !f(v[i]) i += 1 end j = i + 1 @inbounds while j <= hi if !f(v[j]) v[i], v[j] = v[j], v[i] i += 1 end j += 1 end i - 1 end """ send_to_end!(f::Function, v::AbstractVector, o::DirectOrdering[, end_stable]; lo, hi) Return `(a, b)` where `v[a:b]` are the elements that are not sent to the end. If `o isa ReverseOrdering` then the "end" of `v` is `v[lo]`. If `end_stable` is set, the elements that are sent to the end are stable instead of the elements that are not """ @inline send_to_end!(f::F, v::AbstractVector, ::ForwardOrdering, end_stable=false; lo, hi) where F <: Function = end_stable ? (lo, hi-send_to_end!(!f, view(v, hi:-1:lo))) : (lo, send_to_end!(f, v; lo, hi)) @inline send_to_end!(f::F, v::AbstractVector, ::ReverseOrdering, end_stable=false; lo, hi) where F <: Function = end_stable ? (send_to_end!(!f, v; lo, hi)+1, hi) : (hi-send_to_end!(f, view(v, hi:-1:lo))+1, hi) lt = isless after_zero(::ForwardOrdering, x) = !signbit(x) after_zero(::ReverseOrdering, x) = signbit(x) is_concrete_IEEEFloat(T::Type) = T <: Base.IEEEFloat && isconcretetype(T) function radixsort!(v::AbstractVector, o::DirectOrdering=Forward) scratch = nothing lo = firstindex(v) hi = size(v,1) if is_concrete_IEEEFloat(eltype(v)) && o isa DirectOrdering lo, hi = send_to_end!(isnan, v, o, true; lo, hi) iv = reinterpret(uinttype(eltype(v)), v) j = send_to_end!(x -> after_zero(o, x), v; lo, hi) scratch = _sort!(iv, a.next, Reverse, (;kw..., lo, hi=j)) elseif !(eltype(v) == Int || eltype(v) == UInt) throw(error("The type of your array is not suitable for radixsort")) end mn = mx = v[lo] @inbounds for i in (lo+1):hi vi = v[i] lt(vi, mn) && (mn = vi) lt( mx, vi) && (mx = vi) end lt( mn, mx) || return scratch # all same umn = uint_map(mn, o) urange = uint_map(mx, o)-umn bits = unsigned(top_set_bit(urange)) # At this point, we are committed to radix sort. u = uint_map!(v, lo, hi, o) # we subtract umn to avoid radixing over unnecessary bits. For example, # Int32[3, -1, 2] uint_maps to UInt32[0x80000003, 0x7fffffff, 0x80000002] # which uses all 32 bits, but once we subtract umn = 0x7fffffff, we are left with # UInt32[0x00000004, 0x00000000, 0x00000003] which uses only 3 bits, and # Float32[2.012, 400.0, 12.345] uint_maps to UInt32[0x3fff3b63, 0x3c37ffff, 0x414570a4] # which is reduced to UInt32[0x03c73b64, 0x00000000, 0x050d70a5] using only 26 bits. # the overhead for this subtraction is small enough that it is worthwhile in many cases. # this is faster than u[lo:hi] .-= umn as of v1.9.0-DEV.100 @inbounds for i in lo:hi u[i] -= umn end scratch, t = make_scratch(scratch, eltype(v), hi-lo+1) tu = reinterpret(eltype(u), t) if radix_sort!(u, lo, hi, bits, tu, 1-lo) uint_unmap!(v, u, lo, hi, o, umn) else uint_unmap!(v, tu, lo, hi, o, umn, 1-lo) end scratch end function radix_chunk_size_heuristic(lo::Integer, hi::Integer, bits::Unsigned) # chunk_size is the number of bits to radix over at once. # We need to allocate an array of size 2^chunk size, and on the other hand the higher # the chunk size the fewer passes we need. Theoretically, chunk size should be based on # the Lambert W function applied to length. Empirically, we use this heuristic: guess = min(10, log(maybe_unsigned(hi-lo))*3/4+3) # TODO the maximum chunk size should be based on architecture cache size. # We need iterations * chunk size ≥ bits, and these cld's # make an effort to get iterations * chunk size ≈ bits UInt8(cld(bits, cld(bits, guess))) end # The return value indicates whether v is sorted (true) or t is sorted (false) # This is one of the many reasons radix_sort! is not exported. function radix_sort!(v::AbstractVector{U}, lo::Integer, hi::Integer, bits::Unsigned, t::AbstractVector{U}, offset::Integer, chunk_size=radix_chunk_size_heuristic(lo, hi, bits)) where U <: Unsigned # bits is unsigned for performance reasons. counts = Vector{Int}(undef, 1 << chunk_size + 1) # TODO use scratch for this shift = 0 while true @noinline radix_sort_pass!(t, lo, hi, offset, counts, v, shift, chunk_size) # the latest data resides in t shift += chunk_size shift < bits || return false @noinline radix_sort_pass!(v, lo+offset, hi+offset, -offset, counts, t, shift, chunk_size) # the latest data resides in v shift += chunk_size shift < bits || return true end end function radix_sort_pass!(t, lo, hi, offset, counts, v, shift, chunk_size) mask = UInt(1) << chunk_size - 1 # mask is defined in pass so that the compiler @inbounds begin # ↳ knows it's shape # counts[2:mask+2] will store the number of elements that fall into each bucket. # if chunk_size = 8, counts[2] is bucket 0x00 and counts[257] is bucket 0xff. counts .= 0 for k in lo:hi x = v[k] # lookup the element i = (x >> shift)&mask + 2 # compute its bucket's index for this pass counts[i] += 1 # increment that bucket's count end counts[1] = lo + offset # set target index for the first bucket cumsum!(counts, counts) # set target indices for subsequent buckets # counts[1:mask+1] now stores indices where the first member of each bucket # belongs, not the number of elements in each bucket. We will put the first element # of bucket 0x00 in t[counts[1]], the next element of bucket 0x00 in t[counts[1]+1], # and the last element of bucket 0x00 in t[counts[2]-1]. for k in lo:hi x = v[k] # lookup the element i = (x >> shift)&mask + 1 # compute its bucket's index for this pass j = counts[i] # lookup the target index t[j] = x # put the element where it belongs counts[i] = j + 1 # increment the target index for the next end # ↳ element in this bucket end end end # module MergeSortGPU
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
code
2058
using SyncSort using Test using Random @testset "CPU single vectors" begin x = rand(100) syncsort!(x) @test issorted(x) x = rand(Int, 100) syncsort!(x) @test issorted(x) x = rand(UInt, 100) syncsort!(x) @test issorted(x) x = rand(Int, 100) |> Vector{Integer} syncsort!(x) @test issorted(x) end @testset "CPU double vectors" begin Random.seed!(0) x1 = rand(100) y1 = rand(100) x2 = copy(x1) y2 = copy(y1) syncsort!(x1, y1) @test issorted(x1) @test y1 == y2[sortperm(x2)] x1 = rand(Int, 100) x2 = copy(x1) y1 = rand(100) y2 = copy(y1) syncsort!(x1, y1) @test issorted(x1) @test y1 == y2[sortperm(x2)] x1 = rand(UInt, 100) x2 = copy(x1) y1 = rand(100) y2 = copy(y1) syncsort!(x1, y1) @test issorted(x1) @test y1 == y2[sortperm(x2)] x1 = rand(Int, 100) |> Vector{Integer} x2 = copy(x1) y1 = rand(100) y2 = copy(y1) syncsort!(x1, y1) @test issorted(x1) @test y1 == y2[sortperm(x2)] end @testset "CPU triple vectors" begin Random.seed!(0) x1 = rand(100) y1 = rand(100) z1 = rand(100) x2 = copy(x1) y2 = copy(y1) z2 = copy(z1) syncsort!(x1, y1, z1) @test issorted(x1) @test y1 == y2[sortperm(x2)] @test z1 == z2[sortperm(x2)] x1 = rand(Int, 100) y1 = rand(100) z1 = rand(100) x2 = copy(x1) y2 = copy(y1) z2 = copy(z1) syncsort!(x1, y1, z1) @test issorted(x1) @test y1 == y2[sortperm(x2)] @test z1 == z2[sortperm(x2)] x1 = rand(UInt, 100) y1 = rand(100) z1 = rand(100) x2 = copy(x1) y2 = copy(y1) z2 = copy(z1) syncsort!(x1, y1, z1) @test issorted(x1) @test y1 == y2[sortperm(x2)] @test z1 == z2[sortperm(x2)] x1 = rand(Int, 100) |> Vector{Integer} y1 = rand(100) z1 = rand(100) x2 = copy(x1) y2 = copy(y1) z2 = copy(z1) syncsort!(x1, y1, z1) @test issorted(x1) @test y1 == y2[sortperm(x2)] @test z1 == z2[sortperm(x2)] end
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.0
d01c0040cebc605d4b1ce929654d8cdd58949ca7
docs
2974
# SyncSort: Cross-Architecture Synchronised Sorting of Multiple Arrays While key-value pairs are standard in sorting, oftentimes these keys and values are kept in separate arrays (see Explanation below); we can sort multiple secondary vectors following the values of a primary key vector using a new sorting interface: ```julia syncsort!(v, rest...) # Example interface usage num_particles = 100_000 ids = rand(Int64, num_particles) xcoords = rand(num_particles) ycoords = rand(num_particles) # Reordering applied to `ids` will be done in sync with `xcoords` and `ycoords` syncsort!(ids, xcoords, ycoords) ``` ## Explanation Key-value pair sorting assumes an _Array of Structures_ (AoS) format - e.g., a `Vector{Particle}` where `struct Particle` contains some fields `coord::Float64` and `id::Int64`. However, in many applications, it is more performant to store these fields as a _Structure of Arrays_ (SoA), i.e. separate `coords::Vector{Float64` and `ids::Vector{Int64}`. If we had an Array of Structures, using standard sorting interfaces - as is the case in virtually all programming languages - we'd do something like: ```julia # One primary key and two secondary values struct Particle id::Int64 xcoord::Float64 ycoord::Float64 end # Array of structures particles = [Particle(rand(Int64), rand(Float64)) for i in 1:10_000] # Sort by the field `id` sort!(particles; by=p->p.id) ``` In high-performance applications, we'd use a Structure of Arrays, where we have separate arrays for our keys and values; the typical solution would involve creating a mask of indices sorting the primary array, in Julia named `sortperm`: ```julia # Keys and values held in separate vectors ids = rand(Int64, 10_000) xcoords = rand(Float64, 10_000) ycoords = rand(Float64, 10_000) # Get indices permutation that sorts the primary array sorted_indices = sortperm(ids) # Use indices mask to permute arrays ids = ids[sorted_indices] xcoords = xcoords[sorted_indices] ycoords = ycoords[sorted_indices] ``` An easier and much more performant solution - in terms of time, space, and especially program (re-)design - would be `syncsort`: ```julia using SyncSort # Keys and values held in separate vectors ids = rand(Int64, 10_000) xcoords = rand(Float64, 10_000) ycoords = rand(Float64, 10_000) syncsort!(ids, xcoords, ycoords) ``` ## CPU Sorting Credits The CPU sorting routines in `src/cpu_sort.jl` are copied verbatim from the Julia standard library, with some changes to propagate the secondary arrays and follow the swaps done by the standard sorting routines. All credits go to the Julia contributors, with special thanks to @LilithHafner for writing one of the most performant sorting algorithms of [any programming language](https://github.com/LilithHafner/InterLanguageSortingComparisons) - thank you! The Julia license text is included within the file. ## License This package is shared under the same license as the Julia standard library, MIT.
SyncSort
https://github.com/StellaOrg/SyncSort.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1418
module SyncBarriersBenchmarks using BenchmarkTools: Benchmark, BenchmarkGroup include("bench_uniform_loops.jl") include("bench_fuzzy.jl") include("bench_cml.jl") include("bench_gcm.jl") function setup(; uniform_loops = (), fuzzy = (), cml = (), gcm = ()) suite = BenchmarkGroup() suite["uniform_loops"] = BenchUniformLoops.setup(; uniform_loops...) suite["fuzzy"] = BenchFuzzy.setup(; fuzzy...) suite["cml"] = BenchCML.setup(; cml...) suite["gcm"] = BenchGCM.setup(; gcm...) return suite end function set_smoke_params!(bench) bench.params.seconds = 0.001 bench.params.evals = 1 bench.params.samples = 1 bench.params.gctrial = false bench.params.gcsample = false return bench end foreach_benchmark(f!, bench::Benchmark) = f!(bench) function foreach_benchmark(f!, group::BenchmarkGroup) for x in values(group) foreach_benchmark(f!, x) end end function setup_smoke(; ntasks = Threads.nthreads()) suite = setup( fuzzy = (ntasks = ntasks, n = ntasks, m = ntasks, niters = 10), cml = (ntasks = ntasks, nsites = ntasks + 2, nsteps = 10), gcm = (ntasks = ntasks, nsites = ntasks + 2, nsteps = 10), ) foreach_benchmark(set_smoke_params!, suite) return suite end function clear() BenchUniformLoops.clear() BenchFuzzy.clear() BenchCML.clear() BenchGCM.clear() end end # module SyncBarriersBenchmarks
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
4743
module BenchCML using SyncBarriers using BenchmarkTools function unsafe_update!(xs, t, indices, f, ϵ) for i in indices @inbounds xs[i, t+1] = (1 - ϵ) * f(xs[i, t]) + ϵ / 2 * (f(xs[i-1, t]) + f(xs[i+1, t])) end end function sim_seq!(xs, f::F, ϵ) where {F} for t in firstindex(xs, 2):lastindex(xs, 2)-1 unsafe_update!(xs, t, firstindex(xs, 1)+1:lastindex(xs, 1)-1, f, ϵ) end end function sim_parallel!(xs, f, ϵ, barrier, foreach_parallel, spin) ntasks = length(barrier) space = firstindex(xs, 1)+1:lastindex(xs, 1)-1 xchunks = collect(Iterators.partition(space, cld(length(space), ntasks))) foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] for t in firstindex(xs, 2):lastindex(xs, 2)-1 unsafe_update!(xs, t, indices, f, ϵ) cycle!(barrier[itask], spin) end end end prepare_barriers(f, ntasks) = [f(2) for _ in 1:ntasks-1] function sim_parallel_edges!(xs, f, ϵ, barriers, foreach_parallel, spin) ntasks = length(barriers)+1 space = firstindex(xs, 1)+1:lastindex(xs, 1)-1 xchunks = collect(Iterators.partition(space, cld(length(space), ntasks))) foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] for t in firstindex(xs, 2):lastindex(xs, 2)-1 unsafe_update!(xs, t, indices, f, ϵ) itask == 1 || cycle!(barriers[itask-1][2], spin) itask == ntasks || cycle!(barriers[itask][1], spin) end end end function sim_parallel_nobarrier!(xs, f, ϵ, ntasks, foreach_parallel) space = firstindex(xs, 1)+1:lastindex(xs, 1)-1 xchunks = collect(Iterators.partition(space, cld(length(space), ntasks))) for t in firstindex(xs, 2):lastindex(xs, 2)-1 foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] unsafe_update!(xs, t, indices, f, ϵ) end end end function parallel_foreach_static(f, xs) Threads.@threads :static for x in xs f(x) end end function parallel_foreach_dynamic(f, xs) tasks = empty!(Vector{Task}(undef, length(xs))) for x in xs t = Threads.@spawn f(x) push!(tasks, t) end foreach(wait, tasks) end const CACHE = Ref{Any}(nothing) function setup(; spin = nothing, # spin = 1000, nbranches = 2, ntasks = Threads.nthreads(), nsteps = 2^10, nsites = 2^13 * ntasks, a = 1.85, ϵ = 0.1, ) @debug "BenchCML.setup: spin=$spin nbranches=$nbranches ntasks=$ntasks nsteps=$nsteps nsites=$nsites a=$a ϵ=$ϵ" f(x) = 1 - a * x^2 CACHE[] = zeros(nsites, nsteps) CACHE[][:, 1] .= rand(nsites) suite = BenchmarkGroup() suite["seq"] = @benchmarkable sim_seq!(CACHE[], $f, $ϵ) for (label, barrier) in [ ("dissemination", DisseminationBarrier), ("tree", TreeBarrier{nbranches}), ("flat-tree", FlatTreeBarrier{nbranches}), ("centralized", CentralizedBarrier), # ... ] s1 = suite[label] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel!( CACHE[], $f, $ϵ, $barrier($ntasks), parallel_foreach_static, $spin, ) s1["dynamic"] = @benchmarkable sim_parallel!( CACHE[], $f, $ϵ, $barrier($ntasks), parallel_foreach_static, $spin, ) end for (label, barrier) in [ # ("dissemination-edges", DisseminationBarrier), # ("tree-edges", TreeBarrier{nbranches}), # ("flat-tree"-edges, FlatTreeBarrier{nbranches}), ("centralized-edges", CentralizedBarrier), # ... ] s1 = suite[label] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel_edges!( CACHE[], $f, $ϵ, prepare_barriers($barrier, $ntasks), parallel_foreach_static, $spin, ) s1["dynamic"] = @benchmarkable sim_parallel_edges!( CACHE[], $f, $ϵ, prepare_barriers($barrier, $ntasks), parallel_foreach_static, $spin, ) end let s1 = suite["nobarrier"] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel_nobarrier!( CACHE[], $f, $ϵ, $ntasks, parallel_foreach_static, ) s1["dynamic"] = @benchmarkable sim_parallel_nobarrier!( CACHE[], $f, $ϵ, $ntasks, parallel_foreach_static, ) end return suite end function clear() CACHE[] = nothing end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
7712
module BenchFuzzy import LinearAlgebra using SyncBarriers using BenchmarkTools using UnPack: @unpack function mul_naive!( y::AbstractVector, A::AbstractMatrix, x::AbstractVector, a = true, b = false, ) (axes(y, 1) == axes(A, 1) && axes(A, 2) == axes(x, 1)) || throw(DimensionMismatch()) for i in axes(A, 1) s = zero(eltype(y)) @simd for j in axes(A, 2) s += @inbounds A[i, j] * x[j] # A is adjoint or transpose end y[i] = s * a + y[i] * b end return y end function sim_seq(model, niters, mul! = mul_naive!) @unpack f, g, A, B, C, x0, y0 = model x1 = copy(x0) x2 = similar(x0) y1 = copy(y0) y2 = similar(y0) for _ in 1:niters mul!(x2, A, x1) mul!(y2, C, x1) mul!(y2, B, y1, true, true) x2 .= f.(x2) y2 .= g.(y2) x1, x2 = x2, x1 y1, y2 = y2, y1 end return (x1, y1) end function sim_parallel_fuzzy( model, niters, bx, by, parallel_foreach, spin, mul! = mul_naive!, ) @assert length(bx) == length(by) @unpack f, g, A, B, C, x0, y0 = model x1 = copy(x0) x2 = similar(x0) y1 = copy(y0) y2 = similar(y0) xs = (x1, x2) ys = (y1, y2) ntasks = length(bx) xchunks = collect(Iterators.partition(eachindex(x0), cld(length(x0), ntasks))) ychunks = collect(Iterators.partition(eachindex(y0), cld(length(y0), ntasks))) @assert length(xchunks) == length(ychunks) == ntasks parallel_foreach(1:ntasks) do i for t in 1:niters local x1 , x2 , y1 , y2 if isodd(t) x1, x2 = xs y1, y2 = ys else x2, x1 = xs y2, y1 = ys end @views begin xl = x2[xchunks[i]] yl = y2[ychunks[i]] Al = A[xchunks[i], :] Bl = B[ychunks[i], :] Cl = C[ychunks[i], :] end mul!(xl, Al, x1) t == 1 || depart!(by[i], spin) mul!(yl, Cl, x1) xl .= f.(xl) arrive!(bx[i]) # => x1 writable, x2 readable mul!(yl, Bl, y1, true, true) yl .= g.(yl) arrive!(by[i]) # => y1 writable, y2 readable depart!(bx[i], spin) end end return (x1, y1) end function sim_parallel(model, niters, b, parallel_foreach, spin, mul! = mul_naive!) @unpack f, g, A, B, C, x0, y0 = model x1 = copy(x0) x2 = similar(x0) y1 = copy(y0) y2 = similar(y0) xs = (x1, x2) ys = (y1, y2) ntasks = length(b) xchunks = collect(Iterators.partition(eachindex(x0), cld(length(x0), ntasks))) ychunks = collect(Iterators.partition(eachindex(y0), cld(length(y0), ntasks))) @assert length(xchunks) == length(ychunks) == ntasks parallel_foreach(1:ntasks) do i for t in 1:niters local x1 , x2 , y1 , y2 if isodd(t) x1, x2 = xs y1, y2 = ys else x2, x1 = xs y2, y1 = ys end @views begin xl = x2[xchunks[i]] yl = y2[ychunks[i]] Al = A[xchunks[i], :] Bl = B[ychunks[i], :] Cl = C[ychunks[i], :] end mul!(xl, Al, x1) xl .= f.(xl) mul!(yl, Cl, x1) mul!(yl, Bl, y1, true, true) yl .= g.(yl) cycle!(b[i], spin) end end return (x1, y1) end function sim_parallel_nobarrier(model, niters, ntasks, parallel_foreach, mul! = mul_naive!) @unpack f, g, A, B, C, x0, y0 = model x1 = copy(x0) x2 = similar(x0) y1 = copy(y0) y2 = similar(y0) xs = (x1, x2) ys = (y1, y2) xchunks = collect(Iterators.partition(eachindex(x0), cld(length(x0), ntasks))) ychunks = collect(Iterators.partition(eachindex(y0), cld(length(y0), ntasks))) @assert length(xchunks) == length(ychunks) == ntasks for t in 1:niters parallel_foreach(1:ntasks) do i local x1 , x2 , y1 , y2 if isodd(t) x1, x2 = xs y1, y2 = ys else x2, x1 = xs y2, y1 = ys end @views begin xl = x2[xchunks[i]] yl = y2[ychunks[i]] Al = A[xchunks[i], :] Bl = B[ychunks[i], :] Cl = C[ychunks[i], :] end mul!(xl, Al, x1) xl .= f.(xl) mul!(yl, Cl, x1) mul!(yl, Bl, y1, true, true) yl .= g.(yl) end end return (x1, y1) end function parallel_foreach_static(f, xs) Threads.@threads :static for x in xs f(x) end end function parallel_foreach_dynamic(f, xs) tasks = empty!(Vector{Task}(undef, length(xs))) for x in xs t = Threads.@spawn f(x) push!(tasks, t) end foreach(wait, tasks) end function random_model(n, m, g = 1.5) At = (g / √n) .* rand(n, n) Bt = (g / √m) .* rand(m, m) Ct = (g / √n) .* rand(n, m) return ( A = At', B = Bt', C = Ct', x0 = randn(n), y0 = randn(m), f = tanh, g = tanh, # ... ) end const CACHE = Ref{Any}(nothing) function setup(; n = 2^9, m = 2^10, niters = 1000, ntasks = Threads.nthreads(), spin = nothing, nbranches = 2, ) @debug "BenchFuzzy.setup: n=$n m=$m niters=$niters ntasks=$ntasks spin=$spin nbranches=$nbranches" CACHE[] = random_model(n, m) suite = BenchmarkGroup() suite["seq"] = @benchmarkable sim_seq(CACHE[], $niters) suite["blas"] = @benchmarkable sim_seq(CACHE[], $niters, LinearAlgebra.mul!) for (label, barrier) in [ # Fuzzy barriers: ("tree", TreeBarrier{nbranches}), ("flat-tree", FlatTreeBarrier{nbranches}), ("centralized", CentralizedBarrier), ] s1 = suite[label] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel_fuzzy( CACHE[], $niters, $barrier($ntasks), $barrier($ntasks), parallel_foreach_static, $spin, ) s1["dynamic"] = @benchmarkable sim_parallel_fuzzy( CACHE[], $niters, $barrier($ntasks), $barrier($ntasks), parallel_foreach_dynamic, $spin, ) end for (label, barrier) in [ # Non-fuzzy barriers: ("flat-tree-no-fuzzy", FlatTreeBarrier{nbranches}), ("centralized-no-fuzzy", CentralizedBarrier), ("dissemination", DisseminationBarrier), ] s1 = suite[label] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel( CACHE[], $niters, $barrier($ntasks), parallel_foreach_static, $spin, ) s1["dynamic"] = @benchmarkable sim_parallel( CACHE[], $niters, $barrier($ntasks), parallel_foreach_dynamic, $spin, ) end let s1 = suite["nobarrier"] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel_nobarrier( CACHE[], $niters, $ntasks, parallel_foreach_static, ) s1["dynamic"] = @benchmarkable sim_parallel_nobarrier( CACHE[], $niters, $ntasks, parallel_foreach_static, ) end return suite end function clear() CACHE[] = nothing end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
4038
module BenchGCM using SyncBarriers using BenchmarkTools function sim_seq!(xs, f::F, ϵ) where {F} y = similar(xs, size(xs, 1)) for t in firstindex(xs, 2):lastindex(xs, 2)-1 @views begin @. y = f(xs[:, t]) m = sum(y) / size(xs, 1) @. xs[:, t+1] = (1 - ϵ) * y + ϵ * m end end end function sim_parallel!(xs, f, ϵ, barrier, foreach_parallel, spin) ntasks = length(barrier) space = firstindex(xs, 1)+1:lastindex(xs, 1)-1 xchunks = collect(Iterators.partition(space, cld(length(space), ntasks))) foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] y = similar(xs, length(xchunks[itask])) xl = @view xs[xchunks[itask], :] for t in firstindex(xs, 2):lastindex(xs, 2)-1 @views begin @. y = f(xl[:, t]) s = reduce!(barrier[itask], sum(y), spin) m = s / size(xs, 1) @. xl[:, t+1] = (1 - ϵ) * y + ϵ * m end end end end function sim_parallel_nobarrier!(xs, f, ϵ, ntasks, foreach_parallel) space = firstindex(xs, 1)+1:lastindex(xs, 1)-1 y = similar(xs, size(xs, 1)) sums = similar(xs, ntasks) xchunks = collect(Iterators.partition(space, cld(length(space), ntasks))) foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] xl = @view xs[xchunks[itask], :] yl = @view y[xchunks[itask]] @. yl = f(xl[:, begin]) sums[itask] = sum(y) end for t in firstindex(xs, 2):lastindex(xs, 2)-1 m = sum(sums) / size(xs, 1) foreach_parallel(1:ntasks) do itask local indices = xchunks[itask] xl = @view xs[xchunks[itask], :] yl = @view y[xchunks[itask]] @views begin @. xl[:, t+1] = (1 - ϵ) * yl + ϵ * m @. yl = f(xl[:, t+1]) sums[itask] = sum(yl) end end end end function parallel_foreach_static(f, xs) Threads.@threads :static for x in xs f(x) end end function parallel_foreach_dynamic(f, xs) tasks = empty!(Vector{Task}(undef, length(xs))) for x in xs t = Threads.@spawn f(x) push!(tasks, t) end foreach(wait, tasks) end const CACHE = Ref{Any}(nothing) function setup(; spin = nothing, # spin = 1000, ntasks = Threads.nthreads(), nbranches = max(2, cld(ntasks, 4)), nsteps = 2^10, nsites = 2^13 * ntasks, a = 1.85, ϵ = 0.1, ) @debug "BenchGCM.setup: spin=$spin nbranches=$nbranches ntasks=$ntasks nsteps=$nsteps nsites=$nsites a=$a ϵ=$ϵ" f(x) = 1 - a * x^2 CACHE[] = zeros(nsites, nsteps) CACHE[][:, 1] .= rand(nsites) suite = BenchmarkGroup() suite["seq"] = @benchmarkable sim_seq!(CACHE[], $f, $ϵ) for (label, barrier) in [ ("static-tree", StaticTreeBarrier{nbranches,nbranches,Float64}), ("tree", TreeBarrier{nbranches,Float64}), ("flat-tree", FlatTreeBarrier{nbranches,Float64}), # ... ] s1 = suite[label] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel!( CACHE[], $f, $ϵ, $barrier(+, $ntasks), parallel_foreach_static, $spin, ) s1["dynamic"] = @benchmarkable sim_parallel!( CACHE[], $f, $ϵ, $barrier(+, $ntasks), parallel_foreach_static, $spin, ) end let s1 = suite["nobarrier"] = BenchmarkGroup() s1["static"] = @benchmarkable sim_parallel_nobarrier!( CACHE[], $f, $ϵ, $ntasks, parallel_foreach_static, ) s1["dynamic"] = @benchmarkable sim_parallel_nobarrier!( CACHE[], $f, $ϵ, $ntasks, parallel_foreach_static, ) end return suite end function clear() CACHE[] = nothing end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
4694
module BenchUniformLoops using BenchmarkTools using SyncBarriers function work() t1 = time_ns() + 100 while t1 > time_ns() end end #= const SINKS = Float64[] const SINKS_STRIDE = 32 function __init__() resize!(SINKS, SINKS_STRIDE * (Threads.nthreads() + 1)) fill!(SINKS, -1) end function work(n = 10) i = SINKS_STRIDE * Threads.threadid() x = SINKS[i] for _ in 1:n x = sin(3 * x) end SINKS[i] = x end =# function spawn_and_wait(ncycles, ntasks) tasks = Vector{Task}(undef, ntasks) for _ in 1:ncycles empty!(tasks) for _ in 1:ntasks t = Threads.@spawn work() push!(tasks, t) end foreach(wait, tasks) end end # bad idea? function spawn_and_barrier(ncycles, ntasks) tasks = Vector{Task}(undef, ntasks) barrier = SyncBarriers.CentralizedBarrier(ntasks + 1) for k in 1:ncycles s = mod(k, 2^7) == 0 s && empty!(tasks) for i in 1:ntasks t = Threads.@spawn begin work() SyncBarriers.cycle!(barrier[i]) end s && push!(tasks, t) end SyncBarriers.cycle!(barrier[ntasks+1]) s && foreach(wait, tasks) end end # => works well with dissemination function barrier_with_static(factory, ncycles, ntasks, spin) barrier = factory(ntasks) Threads.@threads :static for i in 1:ntasks for k in 1:ncycles work() SyncBarriers.cycle!(barrier[i], spin) end end end # => works well with centralized function barrier_with_spawn(factory, ncycles, ntasks, spin) barrier = factory(ntasks) tasks = empty!(Vector{Task}(undef, ntasks)) for i in 1:ntasks t = Threads.@spawn begin for k in 1:ncycles work() SyncBarriers.cycle!(barrier[i], spin) end end push!(tasks, t) end foreach(wait, tasks) end function setup(; ncycles::Integer = 2^10, ntasks::Integer = Threads.nthreads(), spin::Integer = 10_000, nbranches_list::AbstractVector{<:Integer} = Int[], ) @debug "BenchUniformLoops: ncycles=$ncycles ntasks=$ntasks spin=$spin" barrier_list = [] push_barrier!(name, value) = push!(barrier_list, (name = name, value = value)) push_barrier!("dissemination", SyncBarriers.DisseminationBarrier), push_barrier!("centralized", SyncBarriers.CentralizedBarrier), if isempty(nbranches_list) if ntasks > 8 push_barrier!("tree-8", SyncBarriers.TreeBarrier{8}) push_barrier!("flat-tree-8", SyncBarriers.FlatTreeBarrier{8}) push_barrier!("static-tree-8-8", SyncBarriers.StaticTreeBarrier{8,8}) elseif ntasks > 4 push_barrier!("tree-4", SyncBarriers.TreeBarrier{4}) push_barrier!("flat-tree-4", SyncBarriers.FlatTreeBarrier{4}) push_barrier!("static-tree-4-4", SyncBarriers.StaticTreeBarrier{4,4}) elseif ntasks > 2 push_barrier!("tree-2", SyncBarriers.TreeBarrier{2}) push_barrier!("flat-tree-2", SyncBarriers.FlatTreeBarrier{2}) push_barrier!("static-tree-2-2", SyncBarriers.StaticTreeBarrier{2,2}) end else for n in nbranches_list push_barrier!("tree-$n", SyncBarriers.TreeBarrier{n}) push_barrier!("flat-tree-$n", SyncBarriers.FlatTreeBarrier{n}) push_barrier!("static-tree-$n-$n", SyncBarriers.StaticTreeBarrier{n,n}) end end spin_list = [ (name = "nospin", value = nothing), (name = "spin", value = spin), # ... ] loop_list = [ (name = "static", value = barrier_with_static), (name = "spawn", value = barrier_with_spawn), # ... ] suite = BenchmarkGroup() suite["wait"] = @benchmarkable spawn_and_wait($ncycles, $ntasks) # suite["spawn_and_barrier"] = @benchmarkable spawn_and_barrier($ncycles, $ntasks) for barrier in barrier_list s1 = suite[string(barrier.name)] = BenchmarkGroup() for spinarg in spin_list s2 = s1[string(spinarg.name)] = BenchmarkGroup() for loop in loop_list s2[string(loop.name)] = @benchmarkable( loop($(barrier.value), $ncycles, $ntasks, $(spinarg.value)), setup = begin # Workaround the error " function argument and static parameter # names must be distinct": loop = $(loop.value) end ) end end end return suite end function clear() end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
238
using Documenter using SyncBarriers makedocs( sitename = "SyncBarriers", format = Documenter.HTML(), modules = [SyncBarriers] ) deploydocs( repo = "github.com/JuliaConcurrent/SyncBarriers.jl", push_preview = true, )
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1298
baremodule SyncBarriers export # Types: Barrier, CentralizedBarrier, DisseminationBarrier, FlatTreeBarrier, StaticTreeBarrier, TreeBarrier, # Functions: arrive!, cycle!, depart!, fuzzy_barrier, fuzzy_reduce_barrier, reduce!, reduce_arrive!, reduce_barrier abstract type Barrier end # Factories function fuzzy_barrier end function fuzzy_reduce_barrier end function reduce_barrier end # Synchronizing API function cycle! end function arrive! end function depart! end function reduce! end function reduce_arrive! end abstract type CentralizedBarrier <: Barrier end abstract type DisseminationBarrier <: Barrier end abstract type TreeBarrier{N,T} <: Barrier end abstract type FlatTreeBarrier{N,T} <: Barrier end abstract type StaticTreeBarrier{NArrive,NDepart,T} <: Barrier end module Internal using ArgCheck: ArgCheck, @argcheck, @check using RecordArrays using ..SyncBarriers: SyncBarriers include("utils.jl") include("oneway.jl") include("common.jl") include("centralized_barrier.jl") include("dissemination_barrier.jl") include("static_tree_barrier.jl") include("tree_barrier.jl") include("flat_tree_barrier.jl") include("barrier_api.jl") end # module Internal Internal.define_docstrings() end # baremodule SyncBarriers
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
3615
# Default barriers: SyncBarriers.Barrier(n::Integer) = _Barrier(n, Threads.nthreads()) SyncBarriers.fuzzy_barrier(n::Integer) = _fuzzy_barrier(n, Threads.nthreads()) SyncBarriers.fuzzy_reduce_barrier(op, ::Type{T}, n::Integer) where {T} = _fuzzy_reduce_barrier(op, T, n, Threads.nthreads()) SyncBarriers.reduce_barrier(op, ::Type{T}, n::Integer) where {T} = _reduce_barrier(op, T, n, Threads.nthreads()) # TODO: find the best cutoff # TODO: make it configurable? function _Barrier(n::Integer, nthreads::Integer) nthreads = min(nthreads, n) if nthreads >= 32 return DisseminationBarrier(n) else return CentralizedBarrier(n) end end function _fuzzy_barrier(n::Integer, nthreads::Integer) nthreads = min(nthreads, n) if nthreads >= 32 return TreeBarrier{8}(n) else return CentralizedBarrier(n) end end function _fuzzy_reduce_barrier(op, ::Type{T}, n::Integer, nthreads::Integer) where {T} nthreads = min(nthreads, n) if nthreads >= 32 return TreeBarrier{8,T}(op, n) elseif nthreads >= 16 return FlatTreeBarrier{4,T}(op, n) else return FlatTreeBarrier{2,T}(op, n) end end function _reduce_barrier(op, ::Type{T}, n::Integer, nthreads::Integer) where {T} nthreads = min(nthreads, n) if nthreads >= 32 return StaticTreeBarrier{8,8,T}(op, n) else return _fuzzy_reduce_barrier(op, T, n, nthreads) end end SyncBarriers.CentralizedBarrier(n) = CentralizedBarrier(n) SyncBarriers.DisseminationBarrier(n) = DisseminationBarrier(n) SyncBarriers.StaticTreeBarrier{NArrive,NDepart}(n) where {NArrive,NDepart} = StaticTreeBarrier{NArrive,NDepart}(n) SyncBarriers.StaticTreeBarrier{NArrive,NDepart,T}(op, n) where {NArrive,NDepart,T} = StaticTreeBarrier{NArrive,NDepart,T}(op, n) SyncBarriers.TreeBarrier{N}(n) where {N} = TreeBarrier{N}(n) SyncBarriers.TreeBarrier{N,T}(op, n) where {N,T} = TreeBarrier{N,T}(op, n) SyncBarriers.FlatTreeBarrier{N}(n) where {N} = FlatTreeBarrier{N}(n) SyncBarriers.FlatTreeBarrier{N,T}(op, n) where {N,T} = FlatTreeBarrier{N,T}(op, n) const FuzzyReduceBarrier{T,NBranches} = Union{TreeBarrier{NBranches,T},FlatTreeBarrier{NBranches,T}} const FuzzyBarrier = Union{CentralizedBarrier,TreeBarrier,FlatTreeBarrier} # Used only in testing ATM: const ReduceBarrier{T} = Union{TreeBarrier{<:Any,T},FlatTreeBarrier{<:Any,T},StaticTreeBarrier{<:Any,<:Any,T}} acctype(::Type{B}) where {T,B<:ReduceBarrier{T}} = T acctype(b::SyncBarriers.Barrier) = acctype(typeof(b)) function SyncBarriers.cycle!( handle::BarrierHandle{<:FuzzyBarrier}, spin::Union{Integer,Nothing} = nothing, ) islast = SyncBarriers.arrive!(handle) islast || SyncBarriers.depart!(handle, spin) return islast end SyncBarriers.arrive!(handle::BarrierHandle{<:FuzzyReduceBarrier{Nothing}}) = SyncBarriers.reduce_arrive!(handle, nothing) === Some(nothing) Base.summary(io::IO, ::CentralizedBarrier) = show(io, SyncBarriers.CentralizedBarrier) Base.summary(io::IO, ::DisseminationBarrier) = show(io, SyncBarriers.DisseminationBarrier) Base.summary(io::IO, ::StaticTreeBarrier{NArrive,NDepart,T}) where {NArrive,NDepart,T} = show(io, SyncBarriers.StaticTreeBarrier{NArrive,NDepart,T}) Base.summary(io::IO, ::TreeBarrier{T,N}) where {T,N} = show(io, SyncBarriers.TreeBarrier{T,N}) Base.summary(io::IO, ::FlatTreeBarrier{T,N}) where {T,N} = show(io, SyncBarriers.FlatTreeBarrier{T,N}) function Base.show(io::IO, ::MIME"text/plain", barrier::SyncBarriers.Barrier) summary(io, barrier) print(io, " for ", length(barrier), " task(s)") end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1873
local_sense_states(n) = RecordArrays.fill(true, n; align = 64) struct CentralizedBarrier <: SyncBarriers.CentralizedBarrier n::Int count::Threads.Atomic{Int} _count_pads::NTuple{ATOMICS_NPADS,Threads.Atomic{Int}} sense::Threads.Atomic{Bool} _sense_pads::NTuple{ATOMICS_NPADS,Threads.Atomic{Bool}} local_sense::typeof(local_sense_states(1)) waiters::Matrix{OneWayCondition} end function CentralizedBarrier(n::Integer) count, _count_pads = cache_aligned_atomic(0) sense, _sense_pads = cache_aligned_atomic(true) return CentralizedBarrier( n, count, _count_pads, sense, _sense_pads, local_sense_states(n), [OneWayCondition() for _ in 1:n, _ in 1:2], ) end @inline waiters_for(barrier::CentralizedBarrier, sense::Bool) = @view barrier.waiters[:, Int(sense) + 1] @inline function waiter_for(handle::BarrierHandle{CentralizedBarrier}) barrier = handle.barrier s = barrier.local_sense[handle.i] return barrier.waiters[handle.i, Int(s) + 1] end function SyncBarriers.arrive!(handle::BarrierHandle{CentralizedBarrier}) barrier = handle.barrier s = !barrier.local_sense[handle.i] barrier.local_sense[handle.i] = s if Threads.atomic_add!(barrier.count, 1) == barrier.n - 1 barrier.count[] = 0 barrier.sense[] = s for (j, waiter) in pairs(waiters_for(barrier, s)) if j != handle.i notify(waiter) end end return true else return false end end function SyncBarriers.depart!( handle::BarrierHandle{CentralizedBarrier}, spin::Union{Integer,Nothing} = nothing, ) barrier = handle.barrier s = barrier.local_sense[handle.i] waiter = waiter_for(handle) sense = barrier.sense waitif(() -> sense[] != s, waiter, spin) return end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1847
mutable struct Channel{T} value::T isset::Bool moretakers::Bool waiters::Vector{OneWayCondition} lock::ReentrantLock end function _tryput!(channel, value) sender = nothing receiver = nothing lock(channel.lock) try if channel.isset @assert !channel.moretakers todelete = Int[] for (i, w) in pairs(channel.waiters) if w.task === current_task() if Atomic.cas!(w.state, OWC_EMPTY, OWC_WAITING) === OWC_EMPTY sender = w break end elseif w.state[] === OWC_EMPTY if Atomic.cas!(w.state, OWC_EMPTY, OWC_CLOSED) === OWC_EMPTY push!(todelete, i) end end end deleteat!(channel.waiters, todelete) if sender === nothing sender = OneWayCondition() sender.task = current_task() push!(channel.waiters, sender) end else if channel.moretakers todelete = Int[] for (i, w) in pairs(channel.waiters) if Atomic.cas!(w.state, OWC_WAITING, OWC_WAITING) === OWC_EMPTY sender = w break end end else channel.isset = true channel.value = value end end finally unlock(channel.lock) end end function _trytake!(channel) lock(channel.lock) try if channel.isset channel.isset = false return Some(channel.value) end for waiter in channel.waiters end finally unlock(channel.lock) end end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
337
struct BarrierHandle{Barrier<:SyncBarriers.Barrier} barrier::Barrier i::Int end Base.length(barrier::SyncBarriers.Barrier) = barrier.n @inline function Base.getindex(barrier::SyncBarriers.Barrier, i::Integer) @boundscheck 1 <= i <= length(barrier) || throw(BoundsError(barrier, i)) return BarrierHandle(barrier, i) end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1373
sense_parity_states(n) = RecordArrays.fill((sense = true, parity = 0), n; align = 64) struct DisseminationBarrier <: SyncBarriers.DisseminationBarrier n::Int flags::Array{OneWayObservable{Bool},3} locals::typeof(sense_parity_states(1)) end DisseminationBarrier(n::Integer) = DisseminationBarrier( n, [OneWayObservable{Bool}(false) for _ in 1:ceillog2(n), _ in 1:n, _ in 1:2], sense_parity_states(n), ) function inc_sense_parity!(state) parity = state.parity[] sense = state.sense[] if parity == 1 state.sense[] = !sense end state.parity[] = 1 - parity return sense, parity end function prev_sense_parity(state) parity = 1 - state.parity[] sense = state.sense[] return ((parity == 1 ? !sense : sense), parity) end function SyncBarriers.cycle!( handle::BarrierHandle{DisseminationBarrier}, spin::Union{Nothing,Integer} = nothing, ) i = handle.i barrier = handle.barrier sense, parity = inc_sense_parity!(view(barrier.locals, handle.i)) shift = 1 for flags in eachrow(@view barrier.flags[:, :, parity+1]) @_assert flags[i][] != sense flags[i][] = sense j = i - shift if j <= 0 j += lastindex(flags) end shift *= 2 waitif(x -> x != sense, flags[j], spin) @_assert flags[j][] == sense end end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
3423
struct FlatNode{NBranches,T,Values<:Union{Nothing,MutableNTuple{NBranches,T}}} count::NTuple{2,Threads.Atomic{Int}} values::NTuple{2,Values} end function FlatNode{NBranches,T}() where {NBranches,T} if Base.issingletontype(T) Values = Nothing values = (nothing, nothing) else Values = MutableNTuple{NBranches,T} values = (Values(), Values()) end count = (Threads.Atomic{Int}(0), Threads.Atomic{Int}(0)) return FlatNode{NBranches,T,Values}(count, values) end struct FlatTreeBarrier{NBranches,T,Op,Values} <: SyncBarriers.FlatTreeBarrier{NBranches,T} n::Int flags::Matrix{OneWayObservable{Bool}} locals::typeof(sense_parity_states(1)) nodes::Vector{FlatNode{NBranches,T,Values}} values::MutableNTuple{2,T} op::Op end # TODO: check if parity is required FlatTreeBarrier{NBranches}(n) where {NBranches} = FlatTreeBarrier{NBranches,Nothing}(right, n) function FlatTreeBarrier{NBranches,T}(op::Op, n::Integer) where {NBranches,T,Op} @argcheck NBranches isa Integer && NBranches > 1 && T isa Type && n > 0 nnodes = foldl_leaf_to_root((_, x) -> x.stop, nothing, n, Val(NBranches), 1) nodes = [FlatNode{NBranches,T}() for _ in 1:nnodes] flags = [OneWayObservable{Bool}(false) for _ in 1:n, _ in 1:2] values = MutableNTuple{2,T}() return FlatTreeBarrier( n, flags, sense_parity_states(n), nodes, values, op, )::FlatTreeBarrier{NBranches,T,Op} end function SyncBarriers.reduce!( handle::BarrierHandle{<:FlatTreeBarrier}, value, spin::Union{Integer,Nothing} = nothing, ) acc1 = SyncBarriers.reduce_arrive!(handle, value) acc2 = SyncBarriers.depart!(handle, spin) if acc1 isa Some @_assert acc2 === something(acc1) return something(acc1) else return acc2 end end function SyncBarriers.reduce_arrive!( handle::BarrierHandle{<:FlatTreeBarrier{NBranches,T}}, value, ) where {NBranches,T} value = convert(T, value) barrier = handle.barrier i = handle.i s, parity = inc_sense_parity!(view(barrier.locals, handle.i)) acc = foldl_leaf_to_root(Some(value), barrier.n, Val(NBranches), i) do acc, x node = barrier.nodes[x.inode] cnt = node.count[parity+1] vals = node.values[parity+1] if vals !== nothing vals[x.iself] = something(acc) end if Threads.atomic_add!(cnt, 1) == length(x.branches) - 1 cnt[] = 0 if vals === nothing return acc # continue else a = vals[1] for j in x.branches[2:end] a = barrier.op(a, vals[j]) end return Some(a) end else return Break(nothing) end end if acc isa Break return nothing else barrier.values[parity+1] = something(acc) for (j, flag) in pairs(@view barrier.flags[:, parity+1]) flag[] = s end return acc::Some end end function SyncBarriers.depart!( handle::BarrierHandle{<:FlatTreeBarrier}, spin::Union{Integer,Nothing} = nothing, ) barrier = handle.barrier s, parity = prev_sense_parity(view(barrier.locals, handle.i)) flag = barrier.flags[handle.i, parity+1] waitif(!=(s), flag, spin) return barrier.values[parity+1] end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
2300
const OWC_EMPTY = 0 const OWC_WAITING = 1 const OWC_NOTIFYING = 2 const OWC_CLOSED = 3 """ OneWayCondition() Single-reader single-writer condition variable. """ mutable struct OneWayCondition state::Threads.Atomic{Int} _pads::NTuple{ATOMICS_NPADS,Threads.Atomic{Int}} task::Union{Task,Nothing} end function OneWayCondition() state, _pads = cache_aligned_atomic(OWC_EMPTY) return OneWayCondition( state, _pads, nothing) end function Base.notify(cond::OneWayCondition) @_assert cond.state[] in (OWC_EMPTY, OWC_WAITING) state = Threads.atomic_cas!(cond.state, OWC_WAITING, OWC_NOTIFYING) @_assert state in (OWC_EMPTY, OWC_WAITING) if state === OWC_WAITING schedule(cond.task) end return end function waitif(f, cond::OneWayCondition, spin::Union{Nothing,Integer}) if spin isa Integer for _ in Base.OneTo(spin) f() || return ccall(:jl_cpu_pause, Cvoid, ()) GC.safepoint() end end cond.task = current_task() @_assert cond.state[] == OWC_EMPTY cond.state[] = OWC_WAITING Threads.atomic_fence() # prevent store-load reordering if f() # load wait()::Nothing @_assert !f() else state = Threads.atomic_cas!(cond.state, OWC_WAITING, OWC_EMPTY) if state === OWC_NOTIFYING # then we must "receive" the `schedule` call wait()::Nothing @_assert !f() else @_assert !f() end @_assert state in (OWC_WAITING, OWC_NOTIFYING) end cond.state[] = OWC_EMPTY cond.task = nothing return end """ OneWayObservable{T}(x::T) Single-reader single-writer observable-ish. """ struct OneWayObservable{T} value::Threads.Atomic{T} _pads::NTuple{ATOMICS_NPADS,Threads.Atomic{T}} cond::OneWayCondition end function OneWayObservable{T}(x::T) where {T} value, _pads = cache_aligned_atomic(x) return OneWayObservable{T}(value, _pads, OneWayCondition()) end @inline Base.getindex(o::OneWayObservable) = o.value[] @inline function Base.setindex!(o::OneWayObservable{T}, v::T) where {T} o.value[] = v notify(o.cond) end waitif(f::F, o::OneWayObservable, spin::Union{Nothing,Integer}) where {F} = waitif(() -> f(o.value[]), o.cond, spin)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
4055
struct StaticFlagNode{NBranches,T,Value<:Cell{T}} nchildren::Int children::NTuple{NBranches,Int} flag::OneWayObservable{Bool} value::Value end StaticFlagNode{NBranches,T,Value}( nchildren, children, flag, ) where {NBranches,T,Value<:Cell{T}} = StaticFlagNode{NBranches,T,Value}(nchildren, children, flag, Value()) function concrete(::Type{StaticFlagNode{NBranches,T}}) where {NBranches,T} if Base.issingletontype(T) return StaticFlagNode{NBranches,T,SingletonCell{T}} else return StaticFlagNode{NBranches,T,MutableCell{T}} end end struct StaticTreeBarrier{NArrive,NDepart,T,Value,Op} <: SyncBarriers.StaticTreeBarrier{NArrive,NDepart,T} n::Int local_sense::Vector{Bool} # TODO: pad arrives::Vector{StaticFlagNode{NArrive,T,Value}} departs::Vector{StaticFlagNode{NDepart,Nothing,SingletonCell{Nothing}}} op::Op end StaticTreeBarrier{NArrive,NDepart}(n::Integer) where {NArrive,NDepart} = StaticTreeBarrier{NArrive,NDepart,Nothing}(right, n) function StaticTreeBarrier{NArrive,NDepart,T}(op, n::Integer) where {NArrive,NDepart,T} @argcheck n > 0 arrives = Vector{concrete(StaticFlagNode{NArrive,T})}(undef, n) departs = Vector{concrete(StaticFlagNode{NDepart,Nothing})}(undef, n) static_tree!(arrives) static_tree!(departs) local_sense = [false for _ in 1:n] return StaticTreeBarrier(n, local_sense, arrives, departs, op) end function static_tree_depth(B, n) len(d) = (B^d - 1) ÷ (B - 1) d = ceil(Int, log(B, (B - 1) * n + 1)) @assert len(d - 1) <= n <= len(d) return d end function static_tree!(nodes::AbstractVector{<:StaticFlagNode{NBranches}}) where {NBranches} i = _static_tree!(nodes, 1, 1, static_tree_depth(NBranches, length(nodes))) @assert i == length(nodes) + 1 end # Filling nodes in depth-first order so that the reduction does not require commutativity. function _static_tree!( nodes::AbstractVector{<:Node}, i, depth, maxdepth, ) where {NBranches,Node<:StaticFlagNode{NBranches}} children = ntuple(_ -> firstindex(nodes) - 1, Val(NBranches)) nchildren = 0 if depth < maxdepth for k in 1:NBranches i <= length(nodes) - depth || break i = _static_tree!(nodes, i, depth + 1, maxdepth) nchildren += 1 children = Base.setindex(children, i - 1, k) end end nodes[i] = Node(nchildren, children, OneWayObservable{Bool}(false)) return i + 1 end function foldr_children(op, acc, nodes::AbstractVector{<:StaticFlagNode}, i) node = nodes[i] for k in node.nchildren:-1:1 acc = op(nodes[node.children[k]], acc) end return acc end # The iteration order of foldr_children and foreach_child_flag are different so # that the communication is done in FIFO manner. (TODO: check if it matters) function foreach_child_flag(f::F, nodes, i) where {F} node = nodes[i] for k in 1:node.nchildren f(nodes[node.children[k]].flag) end return end SyncBarriers.cycle!( handle::BarrierHandle{<:StaticTreeBarrier{<:Any,<:Any,Nothing}}, spin::Union{Nothing,Integer} = nothing, ) = SyncBarriers.reduce!(handle, nothing, spin) function SyncBarriers.reduce!( handle::BarrierHandle{<:StaticTreeBarrier{<:Any,<:Any,T}}, value, spin::Union{Nothing,Integer} = nothing, ) where {T} value = convert(T, value) i = handle.i barrier = handle.barrier acc = foldr_children(value, barrier.arrives, i) do node, value waitif(!=(true), node.flag, spin) node.flag.value[] = false # for next episode barrier.op(node.value[], value) end barrier.arrives[i].value[] = acc barrier.arrives[i].flag[] = true sense = barrier.local_sense[i] = !barrier.local_sense[i] root_node = length(barrier) if i != root_node waitif(!=(sense), barrier.departs[i].flag, spin) end foreach_child_flag(barrier.departs, i) do flag flag[] = sense end return barrier.arrives[root_node].value[] end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
7260
struct Node{NBranches,T,Values<:Union{Nothing,MutableNTuple{NBranches,T}}} count::Threads.Atomic{Int} sense::Threads.Atomic{Bool} winner::NTuple{2,Threads.Atomic{Int}} values::NTuple{2,Values} waiters::NTuple{2,NTuple{NBranches,OneWayCondition}} end # TODO: Clarify why two sets of `values` are required: different rounds can have # different sets of tasks involved. If not, remove it. function Node{NBranches,T}() where {NBranches,T} if Base.issingletontype(T) Values = Nothing values = (nothing, nothing) else Values = MutableNTuple{NBranches,T} values = (Values(), Values()) end return Node{NBranches,T,Values}( Threads.Atomic{Int}(0), Threads.Atomic{Bool}(true), (Threads.Atomic{Int}(0), Threads.Atomic{Int}(0)), values, ntuple(_ -> ntuple(_ -> OneWayCondition(), NBranches), 2), ) end struct TreeBarrier{NBranches,T,Op,Values} <: SyncBarriers.TreeBarrier{NBranches,T} n::Int local_sense::Vector{Bool} # TODO: pad nodes::Vector{Node{NBranches,T,Values}} values::MutableNTuple{2,T} op::Op end TreeBarrier{NBranches}(n) where {NBranches} = TreeBarrier{NBranches,Nothing}(right, n) function TreeBarrier{NBranches,T}(op::Op, n::Integer) where {NBranches,T,Op} @argcheck NBranches isa Integer && NBranches > 1 && T isa Type && n > 0 local_sense = [true for _ in 1:n] nnodes = foldl_leaf_to_root((_, x) -> x.stop, nothing, n, Val(NBranches), 1) nodes = [Node{NBranches,T}() for _ in 1:nnodes] values = MutableNTuple{2,T}() return TreeBarrier(n, local_sense, nodes, values, op)::TreeBarrier{NBranches,T,Op} end function foldl_leaf_to_root( rf, acc, n::Integer, ::Val{NBranches}, i::Integer, ) where {NBranches} offset = 0 width = n # number of nodes for each depth while true width, nlast = divrem(width, NBranches) width += nlast > 0 q, r = divrem(i - 1, NBranches) i = q + 1 if nlast > 0 && i == width branches = 1:nlast else branches = 1:NBranches end acc = rf( acc, ( inode = offset + i, # node = nodes[inode] iself = r + 1, # node.values[_][iself] is my slot branches = branches, # node.values[_][brancehs] is me + siblings offset = offset, stop = offset + width, width = width, ), ) acc isa Break && break width == 1 && break offset += width end return acc end function recurse_leaf_to_root( rf, acc, n::Integer, ::Val{NBranches}, i::Integer, ) where {NBranches} function rec(acc, offset, width) width, nlast = divrem(width, NBranches) width += nlast > 0 q, r = divrem(i - 1, NBranches) i = q + 1 if nlast > 0 && i == width branches = 1:nlast else branches = 1:NBranches end isroot = width == 1 x = ( inode = offset + i, # node = nodes[inode] iself = r + 1, # node.values[_][iself] is my slot branches = branches, # node.values[_][brancehs] is me + siblings offset = offset, stop = offset + width, isroot = isroot, ) rf(acc, x) do acc acc isa Break && return acc isroot && return acc rec(acc, offset + width, width) end end return rec(acc, 0, n) end function _reduce_arrive!( handle::BarrierHandle{<:TreeBarrier{NBranches,T}}, value, ::Val{ShouldWait}, spin = nothing, ) where {NBranches,T,ShouldWait} value = convert(T, value) barrier = handle.barrier i = handle.i s = barrier.local_sense[handle.i] = !barrier.local_sense[handle.i] return recurse_leaf_to_root( Some(value), barrier.n, Val(NBranches), i, ) do recurse, acc, x node = barrier.nodes[x.inode] vals = node.values[s+1] if vals !== nothing vals[x.iself] = something(acc) end if Threads.atomic_add!(node.count, 1) == length(x.branches) - 1 if !ShouldWait node.winner[s+1][] = x.iself end if vals !== nothing a = vals[1] for j in x.branches[2:end] a = barrier.op(a, vals[j]) end if x.isroot barrier.values[s+1] = a end acc = Some(a) end acc0 = acc acc = recurse(acc) if acc isa Break return acc end if !ShouldWait if x.isroot for node in barrier.nodes node.winner[!s+1][] = 0 end end end node.count[] = 0 node.sense[] = s for (j, waiter) in pairs(node.waiters[s+1]) if j != x.iself notify(waiter) end end return acc else if ShouldWait sense = node.sense waitif(() -> sense[] != s, node.waiters[s+1][x.iself], spin) return nothing else return Break(nothing) end end end end function SyncBarriers.reduce!( handle::BarrierHandle{<:TreeBarrier{NBranches,T}}, value, spin::Union{Nothing,Integer} = nothing, ) where {NBranches,T} acc = _reduce_arrive!(handle, value, Val(true), spin)::Union{Nothing,Some} barrier = handle.barrier s = barrier.local_sense[handle.i] if acc isa Some @_assert barrier.values[s+1] === something(acc) return something(acc) else return barrier.values[s+1] end end function SyncBarriers.reduce_arrive!( handle::BarrierHandle{<:TreeBarrier{NBranches,T}}, value, ) where {NBranches,T} acc = _reduce_arrive!(handle, value, Val(false)) if acc isa Break return nothing else return acc::Some end end function SyncBarriers.depart!( handle::BarrierHandle{<:TreeBarrier{NBranches}}, spin::Union{Integer,Nothing} = nothing, ) where {NBranches} barrier = handle.barrier s = barrier.local_sense[handle.i] recurse_leaf_to_root(nothing, barrier.n, Val(NBranches), handle.i) do recurse, _, x node = barrier.nodes[x.inode] if node.winner[s+1][] == x.iself if x.isroot # already notified during arrive return Break(nothing) end acc = recurse(nothing) acc isa Break && return acc node.count[] = 0 node.sense[] = s for (j, waiter) in pairs(node.waiters[s+1]) if j != x.iself notify(waiter) end end else sense = node.sense waitif(() -> sense[] != s, node.waiters[s+1][x.iself], spin) end return nothing end return barrier.values[s+1] end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
4323
function debugging end enable_debug() = @eval debugging() = true disable_debug() = @eval debugging() = false enable_debug() # disable_debug() macro _assert(args...) call = Expr( :macrocall, getfield(ArgCheck, Symbol("@check")), # injecting the callable for esc __source__, args..., ) ex = Expr(:block, __source__, call) quote if $debugging() $ex end nothing end |> esc end function ceillog2(n::Integer) n > 0 || throw(DomainError(n)) i = trailing_zeros(n) j = 8 * sizeof(n) - leading_zeros(n) - 1 if i == j return i else return j + 1 end end abstract type Cell{T} end mutable struct MutableCell{T} <: Cell{T} value::T # TODO: pad MutableCell{T}() where {T} = new{T}() end struct SingletonCell{T} <: Cell{T} end @inline Base.getindex(cell::MutableCell{T}) where {T} = cell.value @inline Base.getindex(::SingletonCell{T}) where {T} = T.instance @inline Base.setindex!(cell::MutableCell{T}, value::T) where {T} = cell.value = value @inline Base.setindex!(::SingletonCell{T}, value::T) where {T} = value USE_PADDED_ATOMICS = true # USE_PADDED_ATOMICS = false if USE_PADDED_ATOMICS # TODO: use RecordArrays to allocate atomics # TODO: load cache line size const ATOMICS_NPADS = 7 # The allocator is very likely to hand over objects allocated at consecutive locations function cache_aligned_atomic(x::T) where {T} a1 = Threads.Atomic{T}(x) a2 = Threads.Atomic{T}(x) a3 = Threads.Atomic{T}(x) a4 = Threads.Atomic{T}(x) a5 = Threads.Atomic{T}(x) a6 = Threads.Atomic{T}(x) a7 = Threads.Atomic{T}(x) a8 = Threads.Atomic{T}(x) if mod(UInt(pointer_from_objref(a1)), 64) == 0 return (a1, (a2, a3, a4, a5, a6, a7, a8)) elseif mod(UInt(pointer_from_objref(a2)), 64) == 0 return (a2, (a1, a3, a4, a5, a6, a7, a8)) elseif mod(UInt(pointer_from_objref(a3)), 64) == 0 return (a3, (a1, a2, a4, a5, a6, a7, a8)) else return (a4, (a1, a2, a3, a5, a6, a7, a8)) end end else const ATOMICS_NPADS = 0 cache_aligned_atomic(x::T) where {T} = (Threads.Atomic{T}(x), ()) end """ Something like Transducers.Reduced """ struct Break{T} value::T end right(_, x) = x mutable struct ExperimentalMutableNTuple{N,T} values::NTuple{N,T} ExperimentalMutableNTuple{N,T}(values::NTuple{N,T}) where {N,T} = new{N,T}(values) ExperimentalMutableNTuple{N,T}() where {N,T} = new{N,T}() end @inline Base.getindex(mut::ExperimentalMutableNTuple, i) = mut.values[i] # TODO: need to use unsafe_store! to make it data race-free #= @inline function Base.setindex!(mut::ExperimentalMutableNTuple{N,T}, v, i) where {T} @boundscheck 1 <= i <= N || throw(BoundsError(mut, i)) if Base.issingletontype(T) return elseif Base.isimmutable(T) else end mut.values = Base.setindex(mut.values, v, i) end =# struct FallbackMutableNTuple{N,T} values::Vector{T} FallbackMutableNTuple{N,T}(values::NTuple{N,T}) where {N,T} = new{N,T}(collect(values)) FallbackMutableNTuple{N,T}() where {N,T} = new{N,T}(Vector{T}(undef, N)) end Base.@propagate_inbounds Base.getindex(mut::FallbackMutableNTuple, i) = mut.values[i] Base.@propagate_inbounds Base.setindex!(mut::FallbackMutableNTuple, v, i) = mut.values[i] = v USE_EXPERIMENTAL_MUTABLE_NTUPLE = false if USE_EXPERIMENTAL_MUTABLE_NTUPLE const MutableNTuple = ExperimentalMutableNTuple else const MutableNTuple = FallbackMutableNTuple end function define_docstrings() docstrings = [:SyncBarriers => joinpath(dirname(@__DIR__), "README.md")] docsdir = joinpath(@__DIR__, "docs") for filename in readdir(docsdir) stem, ext = splitext(filename) ext == ".md" || continue name = Symbol(stem) name in names(SyncBarriers, all=true) || continue push!(docstrings, name => joinpath(docsdir, filename)) end for (name, path) in docstrings include_dependency(path) doc = read(path, String) doc = replace(doc, r"^```julia"m => "```jldoctest $name") doc = replace(doc, "<kbd>TAB</kbd>" => "_TAB_") @eval SyncBarriers $Base.@doc $doc $name end end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
356
try using SyncBarriersTests true catch false end || begin let path = joinpath(@__DIR__, "SyncBarriersTests") path in LOAD_PATH || push!(LOAD_PATH, path) end let path = joinpath(@__DIR__, "..", "benchmark", "SyncBarriersBenchmarks") path in LOAD_PATH || push!(LOAD_PATH, path) end using SyncBarriersTests end
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
48
include("load.jl") SyncBarriersTests.runtests()
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
1379
module SyncBarriersTests using Test function include_tests(m = @__MODULE__, dir = @__DIR__) for file in readdir(dir) if match(r"^test_.*\.jl$", file) !== nothing Base.include(m, joinpath(dir, file)) end end end include_tests() function collect_modules(root::Module) modules = Module[] for n in names(root, all = true) m = getproperty(root, n) m isa Module || continue m === root && continue startswith(string(nameof(m)), "Test") || continue push!(modules, m) end return modules end collect_modules() = collect_modules(@__MODULE__) function runtests(modules = collect_modules()) @testset "$(nameof(m))" for m in modules if m === TestDoctest && VERSION < v"1.6" @info "Skip doctest in Julia $VERSION" continue end tests = map(names(m, all = true)) do n n == :test || startswith(string(n), "test_") || return nothing f = getproperty(m, n) f !== m || return nothing parentmodule(f) === m || return nothing applicable(f) || return nothing # removed by Revise? return f end filter!(!isnothing, tests) @testset "$f" for f in tests @debug "Testing $m.$f" f() end end end end # module SyncBarriersTests
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
124
module TestAqua import Aqua import SyncBarriers test() = Aqua.test_all(SyncBarriers; unbound_args = false) end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
3251
module TestSyncBarriers using Test using SyncBarriers using SyncBarriers: Internal function test_barrier() barrier_factories = [ SyncBarriers.CentralizedBarrier, SyncBarriers.DisseminationBarrier, SyncBarriers.TreeBarrier{2}, SyncBarriers.TreeBarrier{3}, SyncBarriers.FlatTreeBarrier{2}, SyncBarriers.FlatTreeBarrier{3}, SyncBarriers.StaticTreeBarrier{4,2}, SyncBarriers.StaticTreeBarrier{5,3}, # ... ] ntasks_list = unique([1, 2, Threads.nthreads(), 2 * Threads.nthreads()]) @testset for f in barrier_factories, ntasks in ntasks_list test_barrier(f, ntasks) end end function test_barrier(factory, ntasks) @debug "`test_barrier($factory, $ntasks)`" states = use_barrier(factory, ntasks) ncycles = size(states, 1) desired = repeat((1:ncycles) .* ntasks, 1, ntasks) @test states[:, 1] == (1:ncycles) .* ntasks @test all(states[:, 1] .== states) @test states == desired end function use_barrier(factory, ntasks; kwargs...) barrier = factory(ntasks) if factory isa Type @test barrier isa factory end return use_barrier(barrier; kwargs...) end function use_barrier(barrier::SyncBarriers.Barrier; ncycles = 1000) ntasks = length(barrier) states = zeros(Int, ncycles, ntasks) return use_barrier!(states, barrier) end function use_barrier!(states::Matrix, barrier::SyncBarriers.Barrier, spin = nothing) ncycles, ntasks = size(states) @assert ntasks == length(barrier) value = Threads.Atomic{Int}(0) @sync for i in 1:ntasks Threads.@spawn try for k in 1:ncycles Threads.atomic_add!(value, 1) SyncBarriers.cycle!(barrier[i], spin) states[k, i] = value[] SyncBarriers.cycle!(barrier[i], spin) end catch err @error( "`use_barrier` failed", exception = (err, catch_backtrace()), i, current_task() ) # TODO: close(barrier) rethrow() end end return states end function test_default_barriers() @test SyncBarriers.Barrier(2) isa SyncBarriers.CentralizedBarrier @test SyncBarriers.fuzzy_barrier(2) isa SyncBarriers.CentralizedBarrier @test SyncBarriers.fuzzy_reduce_barrier(+, Int, 2) isa SyncBarriers.FlatTreeBarrier{2,Int} @test SyncBarriers.reduce_barrier(+, Int, 2) isa SyncBarriers.FlatTreeBarrier{2,Int} @test SyncBarriers.Barrier(32) isa SyncBarriers.Barrier @test SyncBarriers.fuzzy_barrier(32) isa SyncBarriers.Barrier @test SyncBarriers.fuzzy_reduce_barrier(+, Int, 32) isa SyncBarriers.Barrier @test SyncBarriers.reduce_barrier(+, Int, 32) isa SyncBarriers.Barrier end function test_default_barriers_internal() @testset for n in 1:32, nthreads in 1:32 @test Internal._Barrier(n, nthreads) isa SyncBarriers.Barrier @test Internal._fuzzy_barrier(n, nthreads) isa SyncBarriers.Barrier @test Internal._fuzzy_reduce_barrier(+, Int, n, nthreads) isa SyncBarriers.Barrier @test Internal._reduce_barrier(+, Int, n, nthreads) isa SyncBarriers.Barrier end end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
274
module TestBenchSmoke using Test using SyncBarriersBenchmarks: clear, setup_smoke function test_bench_smoke() try local suite @test (suite = setup_smoke()) isa Any @test run(suite) isa Any finally clear() end end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
139
module TestDoctest import SyncBarriers using Documenter: doctest using Test function test() doctest(SyncBarriers) end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
3486
module TestReduce using Test using SyncBarriers using SyncBarriers.Internal: BarrierHandle, acctype # An example of non-commutative reduction function larger((i, a), (j, b)) if a < b (j, b) else (i, a) end end initof(op, T) = Base.reduce_empty(op, T) initof(::typeof(xor), T::Type{<:Integer}) = zero(T) initof(::typeof(larger), ::Type{Tuple{I,X}}) where {I,X} = (zero(I), typemin(X)) samples(::Type{T}) where {T<:Real} = T(100):T(999) samples(::Type{T}) where {I,X,T<:Tuple{I,X}} = collect(zip(samples(I), samples(X))) function test_reduce() @testset "+" begin test_reduce(+, Int) end @testset "xor" begin test_reduce(xor, UInt) end @testset "larger" begin test_reduce(larger, Tuple{Int,Float64}) end end struct TreeBarrier′{NBranches,T,B<:SyncBarriers.TreeBarrier{NBranches,T}} <: SyncBarriers.Barrier barrier::B end Base.length(barrier::TreeBarrier′) = length(barrier.barrier) TreeBarrier′{NBranches,T}(op, n) where {NBranches,T} = TreeBarrier′(SyncBarriers.TreeBarrier{NBranches,T}(op, n)) SyncBarriers.Internal.acctype(::Type{B}) where {T,B<:TreeBarrier′{<:Any,T}} = T function SyncBarriers.reduce!( handle::BarrierHandle{<:TreeBarrier′}, value, spin::Union{Nothing,Integer} = nothing, ) handle = BarrierHandle(handle.barrier.barrier, handle.i) SyncBarriers.reduce_arrive!(handle, value) SyncBarriers.depart!(handle, spin) end function test_reduce(op, T) barrier_factories = [ SyncBarriers.StaticTreeBarrier{2,2,T}, SyncBarriers.StaticTreeBarrier{3,4,T}, SyncBarriers.TreeBarrier{3,T}, SyncBarriers.FlatTreeBarrier{2,T}, SyncBarriers.FlatTreeBarrier{3,T}, TreeBarrier′{2,T}, TreeBarrier′{3,T}, # ... ] ntasks_list = unique([1, 2, Threads.nthreads(), 2 * Threads.nthreads()]) @testset for f in barrier_factories, ntasks in ntasks_list @debug "Testing `test_reduce($op, $f, $ntasks)`" test_reduce(op, f, ntasks) end end function test_reduce(op, factory, ntasks) output, input = use_barrier(op, factory, ntasks) desired = repeat(reduce(op, input; init = initof(op, eltype(output)), dims = 2), 1, ntasks) @test output[:, 1] == desired[:, 1] @test all(output[:, 1] .== output) @test output == desired end function use_barrier(op, factory, ntasks; kwargs...) barrier = factory(op, ntasks) if factory isa Type @test barrier isa factory end return use_barrier(barrier; kwargs...) end function use_barrier(barrier::SyncBarriers.Barrier; ncycles = 1000) ntasks = length(barrier) input = rand(samples(acctype(barrier)), ncycles, ntasks) output = similar(input) return use_barrier!(output, input, barrier) end function use_barrier!( output::Matrix, input::Matrix, barrier::SyncBarriers.Barrier, spin = nothing, ) ncycles, ntasks = size(output) @assert ntasks == length(barrier) @sync for i in 1:ntasks Threads.@spawn try for k in 1:ncycles output[k, i] = SyncBarriers.reduce!(barrier[i], input[k, i], spin) end catch err @error( "`use_barrier` failed", exception = (err, catch_backtrace()), i, current_task() ) # TODO: close(barrier) rethrow() end end return output, input end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
code
177
module TestUtils using Test using SyncBarriers.Internal: ceillog2 function test_ceillog2() xs = 1:2^10 @test ceillog2.(xs) == ceil.(Int, log2.(xs)) end end # module
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
2089
# SyncBarriers [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliaconcurrent.github.io/SyncBarriers.jl/dev) SyncBarriers.jl provides various implementations of [barrier](https://en.wikipedia.org/wiki/Barrier_(computer_science)) for shared memory synchronization and reductions in concurrent Julia programs. It respects the cooperative multitasking nature of Julia's task system while allowing the programmers to express and leverage the structure of the parallelism in their program. See the [documentation](https://juliaconcurrent.github.io/SyncBarriers.jl/dev) for more information. **Note:** Appropriate insertion of barriers for correct and efficient parallel program is rather hard. For casual programming, it is recommended to ues [higher-level data-parallel approaches](https://juliafolds.github.io/data-parallelism/). ## A toy example ```julia julia> using SyncBarriers julia> xs = zeros(Bool, 20); julia> xs[end÷2] = true; julia> barrier = Barrier(length(xs) - 2); julia> @sync for i in 2:length(xs)-1 b = barrier[i-1] Threads.@spawn begin if i == 2 println() join(stdout, (" █"[x + 1] for x in xs)) println() end for _ in 1:8 cycle!(b) # wait for print l, c, r = xs[i-1:i+1] # (loading) cycle!(b) # wait for load xs[i] = l ⊻ (c | r) # (storing) cycle!(b) # wait for store if i == 2 join(stdout, (" █"[x + 1] for x in xs)) println() end end end end █ ███ ██ █ ██ ████ ██ █ █ ██ ████ ███ ██ █ █ █ ██ ████ ██████ ██ █ ███ █ ``` See the [benchmarks](https://github.com/JuliaConcurrent/SyncBarriers.jl/tree/master/benchmark/SyncBarriersBenchmarks/src) for examples with actual performance considerations.
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
528
# SyncBarriers.jl ```@docs SyncBarriers ``` ## Barrier factories Barrier factories create a barrier with a given property without specifying the actual implementation. They use simple heuristics to determine an appropriate implementation. ```@docs Barrier reduce_barrier fuzzy_barrier fuzzy_reduce_barrier ``` ## Barrier constructors ```@docs CentralizedBarrier DisseminationBarrier StaticTreeBarrier TreeBarrier FlatTreeBarrier ``` ## Synchronizing operations ```@docs cycle! arrive! depart! reduce! reduce_arrive! ```
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
413
Barrier(ntasks::Integer) -> barrier Create a barrier for `ntasks` tasks. Call [`cycle!(barrier[i])`](@ref SyncBarriers.cycle!) in the `i`-th task for waiting for other tasks to arrive at the same phase. The actual returned concrete type is not the part of API. It is [`CentralizedBarrier`](@ref) for small `ntasks` and [`DisseminationBarrier`](@ref) for large `ntasks`. Supported method: [`cycle!`](@ref)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
281
CentralizedBarrier(ntasks::Integer) Create the sense-reversing centralized barrier for `ntasks` tasks. It supports fuzzy barrier methods. For small `ntasks` (⪅ 32), it provides the best performance. Supported methods: [`cycle!`](@ref), [`arrive!`](@ref), [`depart!`](@ref)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
204
DisseminationBarrier(ntasks::Integer) Create the dissemination barrier for `ntasks` tasks. It provides the best performance especially for large `ntasks` (⪆ 32). Supported method: [`cycle!`](@ref)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
552
FlatTreeBarrier{NBranches}(ntasks::Integer) FlatTreeBarrier{NBranches,T}(op, ntasks::Integer) Create the tree barrier for `ntasks` tasks with the branching factor specified by the type parameter `NBranches::Integer`. The departure is done serially (hence "flat"). It support fuzzy reduce barrier methods if the associative operations `op` and its domain `T` are given. Otherwise, it only supports fuzzy barrier methods. Supported methods: [`cycle!`](@ref), [`arrive!`](@ref), [`depart!`](@ref) [`reduce!`](@ref). [`reduce_arrive!`](@ref).
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
592
StaticTreeBarrier{NArrive,NDepart}(ntasks::Integer) StaticTreeBarrier{NArrive,NDepart,T}(op, ntasks::Integer) Create the static tree barrier for `ntasks` tasks with the branching factor for arrival `NArrive::Integer` and departure `NDepart::Integer` specified by the type parameters. It support fuzzy reduce barrier methods if the associative operations `op` and its domain `T` are given. Otherwise, it only supports fuzzy barrier methods. It provides the best performance for large `ntasks` (⪆ 32) when reduction is needed. Supported methods: [`cycle!`](@ref), [`reduce!`](@ref)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
494
TreeBarrier{NBranches}(ntasks::Integer) TreeBarrier{NBranches,T}(op, ntasks::Integer) Create the tree barrier for `ntasks` tasks with the branching factor specified by the type parameter `NBranches::Integer`. It support fuzzy reduce barrier methods if the associative operations `op` and its domain `T` are given. Otherwise, it only supports fuzzy barrier methods. Supported methods: [`cycle!`](@ref), [`arrive!`](@ref), [`depart!`](@ref) [`reduce!`](@ref), [`reduce_arrive!`](@ref)
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
1076
arrive!(barrier[i]) Signal that the `i::Integer`-th task has reached a certain phase but postpone the synchronization for the departure. A call to `cycle!` is equivalent to `arrive!` followed by `depart!`. However, the task calling `arrive!` can work on some other local computations before calling `depart!` which waits for other tasks to call `arrive!`. Note that not all `Barrier` subtypes support `arrive!.` See [`fuzzy_barrier`](@ref), [`depart!`](@ref). # Examples ```julia julia> using SyncBarriers julia> xs = [1:3;]; julia> ys = similar(xs); julia> barrier = fuzzy_barrier(3); julia> @sync for i in 1:3 Threads.@spawn begin x = i^2 xs[i] = x arrive!(barrier[i]) # does not `wait` ys[i] = x - 1 # do some work while waiting for other tasks depart!(barrier[i]) # ensure all tasks have reached `arrive!` xs[mod1(i + 1, 3)] -= x end end julia> xs 3-element Vector{Int64}: -8 3 5 julia> ys 3-element Vector{Int64}: 0 3 8 ```
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
539
cycle!(barrier[i]) Using a `barrier::Barrier`, signal that the `i::Integer`-th task has reached a certain phase of the program and wait for other tasks to reach the same phase. # Examples ```julia julia> using SyncBarriers julia> xs = [1:3;]; julia> barrier = Barrier(3); julia> @sync for i in 1:3 Threads.@spawn begin x = i^2 xs[i] = x cycle!(barrier[i]) xs[mod1(i + 1, 3)] -= x end end julia> xs 3-element Vector{Int64}: -8 3 5 ```
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
646
depart!(barrier[i]) depart!(barrier[i]) -> acc::T Wait for all calls to [`arrive!(barrier[i])`](@ref SyncBarriers.arrive!) or [`reduce_arrive!(barrier[i], _)`](@ref SyncBarriers.reduce_arrive!) for `i = 1, 2, ..., ntasks`. If the `barrier` is a fuzzy reduce barrier (created, e.g., by [`fuzzy_reduce_barrier(op, T, ntasks)`](@ref SyncBarriers.fuzzy_reduce_barrier)), it returns the result of reduction started by the prior call to [`reduce_arrive!(barrier[i], xᵢ::T)`](@ref SyncBarriers.reduce_arrive!). Note that not all `Barrier` subtypes support `depart!.` See [`fuzzy_barrier`](@ref), [`arrive!`](@ref), [`reduce_arrive!`](@ref).
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
350
fuzzy_barrier(ntasks::Integer) -> barrier::Barrier Create a *fuzzy barrier* for `ntasks` tasks. In addition to the methods supported by "plain" barriers (see [`Barrier`](@ref)), fuzzy barriers support [`arrive!(barrier[i])`](@ref SyncBarriers.arrive!) and [`depart!(barrier[i])`](@ref SyncBarriers.depart!) to do [`cycle!`](@ref) in two steps.
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
372
fuzzy_reduce_barrier(op, T::Type, ntasks::Integer) -> barrier::Barrier Create a *fuzzy reduce barrier* for `ntasks` tasks. In addition to the methods supported by reduce barriers (see [`reduce_barrier`](@ref)], fuzzy reduce barriers support [`reduce_arrive!(barrier[i], xᵢ)`](@ref SyncBarriers.reduce_arrive!) and [`depart!(barrier[i])`](@ref SyncBarriers.depart!).
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
619
reduce!(barrier[i], xᵢ::T) -> acc::T Using a reduce barrier `barrier` (created, e.g., by [`reduce_barrier(⊗, T, n)`](@ref SyncBarriers.reduce_barrier)), it computes `acc = x₁ ⊗ x₂ ⊗ ⋯ ⊗ xₙ`. # Examples ```julia julia> using SyncBarriers julia> xs = Float64[1:4;]; julia> barrier = reduce_barrier(+, Float64, length(xs)); julia> @sync for i in eachindex(xs) Threads.@spawn begin x = i^2 s = reduce!(barrier[i], x) m = s / length(xs) xs[i] = x - m end end julia> xs 4-element Vector{Float64}: -6.5 -3.5 1.5 8.5 ```
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
962
reduce_arrive!(barrier[i], xᵢ::T) Using a fuzzy reduce barrier `barrier` (created, e.g., by [`fuzzy_reduce_barrier(op, T, ntasks)`](@ref SyncBarriers.fuzzy_reduce_barrier)), it initiates the reduction across tasks. The result of the reduction can be retrieved by a call to [`depart!(barrier[i])`](@ref SyncBarriers.depart!) once all tasks have called `reduce_arrive!`. # Examples ```julia julia> using SyncBarriers julia> xs = Float64[1:4;]; julia> ys = similar(xs); julia> barrier = fuzzy_reduce_barrier(+, Float64, length(xs)); julia> @sync for i in eachindex(xs) Threads.@spawn begin x = i^2 reduce_arrive!(barrier[i], x) ys[i] = x - 1 s = depart!(barrier[i]) m = s / length(xs) xs[i] = x - m end end julia> xs 4-element Vector{Float64}: -6.5 -3.5 1.5 8.5 julia> ys 4-element Vector{Float64}: 0.0 3.0 8.0 15.0 ```
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.1.1
c68ebdfbb4c9e2a4a5cd7b5e47f4313b71bc1f90
docs
292
reduce_barrier(op, T::Type, ntasks::Integer) -> barrier::Barrier Create a *reduce barrier* for `ntasks` tasks. A reduce barrier supports computing a reduction with an associative operator `op(::T, ::T)` across tasks by calling [`reduce!(barrier[i], xᵢ::T)`](@ref SyncBarriers.reduce!).
SyncBarriers
https://github.com/JuliaConcurrent/SyncBarriers.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
615
module ClusteringDifferences using DifferencesBase using Distances import Clustering: FuzzyCMeansResult, KmeansResult, KmedoidsResult export # clustering.jl AbstractClustering, HierarchicalClustering, PartitionalClustering, assignments, constraints, features, parameters, weights, # difference.jl AbstractClusteringDifference, PartitionalClusteringDifference, backwarddiff, forwarddiff, # kmeans.jl kmeans # pckmeans.jl #pckmeans include("clustering.jl") include("difference.jl") include("kmeans.jl") #include("pckmeans.jl") end # module
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
4720
""" AbstractClustering Supertype for clusterings. """ abstract type AbstractClustering end """ PartitionalClustering{Tc<:Integer,Tw<:Real,Ty<:Real,Tm<:Real} <: AbstractClustering Partitional clustering. """ struct PartitionalClustering{Tc<:Integer,Tw<:Real,Ty<:Real} <: AbstractClustering r::Vector{Int} c::Vector{Int} C::Matrix{Tc} W::Matrix{Tw} Y::Matrix{Ty} p::NamedTuple function PartitionalClustering{Tc,Tw,Ty}(r::Vector{Int}, c::Vector{Int}, C::Matrix{Tc}, W::Matrix{Tw}, Y::Matrix{Ty}, p::NamedTuple) where {Tc<:Integer,Tw<:Real,Ty<:Real} size(C, 2) == size(W, 2) || throw(DimensionMismatch("dimensions of constraints and weights must match")) return new(r, c, C, W, Y, p) end end PartitionalClustering(r::Vector{Int}, c::Vector{Int}, C::Matrix{Tc}, W::Matrix{Tw}, Y::Matrix{Ty}, p::NamedTuple) where {Tc,Tw,Ty} = PartitionalClustering{Tc,Tw,Ty}(r, c, C, W, Y, p) function PartitionalClustering(clust::KmeansResult) r = Int[] c = Int[] C = Matrix{Int}(undef, 0, 0) W = Matrix{Float64}(undef, 0, 0) k = size(clust.centers, 2) n = length(clust.assignments) Y = zeros(Int, k, n) for i = 1:n Y[clust.assignments[i], i] = 1 end p = (centers=clust.centers, costs=clust.costs, counts=clust.counts, wcounts=clust.wcounts, totalcost=clust.totalcost, iterations=clust.iterations, converged=clust.converged) return PartitionalClustering(r, c, C, W, Y, p) end function PartitionalClustering(clust::KmedoidsResult) r = Int[] c = Int[] C = Matrix{Int}(undef, 0, 0) W = Matrix{Float64}(undef, 0, 0) k = length(clust.medoids) n = length(clust.assignments) Y = zeros(Int, k, n) for i = 1:n Y[clust.assignments[i], i] = 1 end p = (medoids=clust.medoids, costs=clust.costs, counts=clust.counts, totalcost=clust.totalcost, iterations=clust.iterations, converged=clust.converged) return PartitionalClustering(r, c, C, W, Y, p) end function PartitionalClustering(clust::FuzzyCMeansResult) r = Int[] c = Int[] C = Matrix{Int}(undef, 0, 0) W = Matrix{Float64}(undef, 0, 0) Y = permutedims(clust.weights) p = (centers=clust.centers, iterations=clust.iterations, converged=clust.converged) return PartitionalClustering(r, c, C, W, Y, p) end # Partitional clustering equality operator Base.:(==)(a::PartitionalClustering, b::PartitionalClustering) = (a.r == b.r && a.c == b.c && a.C == b.C && a.W == b.W && a.Y == b.Y && a.p == b.p) # Compute hash code Base.hash(a::PartitionalClustering, h::UInt) = hash(a.r, hash(a.c, hash(a.C, hash(a.W, hash(a.Y, hash(a.p, hash(:PartitionalClustering, h))))))) """ HierarchicalClustering{Tc<:Integer,Tw<:Real} <: AbstractClustering Hierarchical clustering. """ struct HierarchicalClustering{Tc<:Integer,Tw<:Real} <: AbstractClustering r::Vector{Int} c::Vector{Int} C::Array{Tc,3} W::Array{Tw,3} p::NamedTuple function HierarchicalClustering{Tc,Tw}(r::Vector{Int}, c::Vector{Int}, C::Array{Tc,3}, W::Array{Tw,3}, p::NamedTuple) where {Tc<:Integer,Tw<:Real} size(C, 2) == size(W, 2) || throw(DimensionMismatch("dimensions of constraints and weights must match")) return new(r, c, C, W, p) end end HierarchicalClustering(r::Vector{Int}, c::Vector{Int}, C::Array{Tc,3}, W::Array{Tw,3}, p::NamedTuple) where {Tc,Tw} = HierarchicalClustering{Tc,Tw}(r, c, C, W, p) """ axes(a::AbstractClustering[, d]) Access the feature and instance identifiers. Optionally, specify dimension `d` to get the identifiers of that dimension only. """ Base.axes(a::AbstractClustering) = a.r, a.c Base.axes(a::AbstractClustering, d) = d::Integer <= 2 ? axes(a)[d] : Int[] """ features(a::AbstractClustering) Access the feature identifiers. """ features(a::AbstractClustering) = axes(a, 1) """ instances(a::AbstractClustering) Access the instance identifiers. """ Base.instances(a::AbstractClustering) = axes(a, 2) """ constraints(a::AbstractClustering) Access the contraints. """ constraints(a::AbstractClustering) = a.C """ weights(a::AbstractClustering) Access the weights. """ weights(a::AbstractClustering) = a.W """ parameters(c::PartitionalClustering) Access the parameters. """ parameters(a::AbstractClustering) = a.p """ assignments(a::PartitionalClustering) Access the assignments. """ assignments(a::PartitionalClustering) = a.Y
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
3586
""" AbstractClusteringDifference Supertype for clustering differences. """ abstract type AbstractClusteringDifference end """ PartitionalClusteringDifference <: AbstractClusteringDifference Difference between two partitional clusterings. """ struct PartitionalClusteringDifference <: AbstractClusteringDifference r::SetDifference{Int} c::SetDifference{Int} C::MatrixDifference W::MatrixDifference Y::MatrixDifference p::NamedTupleDifference function PartitionalClusteringDifference(r::SetDifference{Int}, c::SetDifference{Int}, C::MatrixDifference, W::MatrixDifference, Y::MatrixDifference, p::NamedTupleDifference) return new(r, c, C, W, Y, p) end end # Partitional clustering difference equality operator Base.:(==)(a::PartitionalClusteringDifference, b::PartitionalClusteringDifference) = (a.r == b.r && a.c == b.c && a.C == b.C && a.W == b.W && a.Y == b.Y && a.p == b.p) # Compute hash code Base.hash(a::PartitionalClusteringDifference, h::UInt) = hash(a.r, hash(a.c, hash(a.C, hash(a.W, hash(a.Y, hash(a.p, hash(:PartitionalClusteringDifference, h))))))) """ axes(a::AbstractClusteringDifference[, d]) Access the feature and instance identifiers differences. Optionally, specify dimension `d` to get the identifier difference of that dimension only. """ Base.axes(a::AbstractClusteringDifference) = a.r, a.c Base.axes(a::AbstractClusteringDifference, d) = d::Integer <= 2 ? axes(a)[d] : Int[] """ features(a::AbstractClusteringDifference) Access the feature identifiers difference. """ features(a::AbstractClusteringDifference) = axes(a, 1) """ instances(a::AbstractClusteringDifference) Access the instance identifiers difference. """ Base.instances(a::AbstractClusteringDifference) = axes(a, 2) """ constraints(a::AbstractClusteringDifference) Access the contraints difference. """ constraints(a::AbstractClusteringDifference) = a.C """ weights(a::AbstractClusteringDifference) Access the weights difference. """ weights(a::AbstractClusteringDifference) = a.W """ parameters(c::AbstractClusteringDifference) Access the parameters difference. """ parameters(a::AbstractClusteringDifference) = a.p """ assignments(a::PartitionalClusteringDifference) Access the assignments difference. """ assignments(a::PartitionalClusteringDifference) = a.Y # Partitional clustering subtraction operator function Base.:-(a::PartitionalClustering, b::PartitionalClustering) r = diff(Set(a.r), Set(b.r)) c = diff(Set(a.c), Set(b.c)) C = diff(a.C, b.C, a.c, a.c, b.c, b.c) W = diff(a.W, b.W, a.c, a.c, b.c, b.c) ayr = collect(1:size(a.Y, 1)) byr = collect(1:size(b.Y, 1)) Y = diff(a.Y, b.Y, ayr, a.c, byr, b.c) p = diff(a.p, b.p) return PartitionalClusteringDifference(r, c, C, W, Y, p) end """ forwarddiff(a::AbstractVector{<:AbstractClustering}, i::Int[, h::Int=1]) Compute the forward difference of the clustering at index `i` with step size `h`. """ forwarddiff(a::AbstractVector{<:AbstractClustering}, i::Int, h::Int=1) = a[i + h] - a[i] """ backwarddiff(a::AbstractVector{<:AbstractClustering}, i::Int[, h::Int=1]) Compute the backward difference of the clustering at index `i` with step size `h`. """ backwarddiff(a::AbstractVector{<:AbstractClustering}, i::Int, h::Int=1) = a[i] - a[i - h]
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
2612
""" kmeans(X::AbstractMatrix{<:Real}, r::AbstractVector{Int}, c::AbstractVector{Int}, μ::AbstractMatrix{<:Real}; <keyword arguments>) Cluster the data `X` with the ``k``-means algorithm. # Keyword arguments - `maxiter::Int=256`: the number of maximum iterations. - `dist::SemiMetric=SqEuclidean()`: the distance function. - `ϵ::AbstractFloat=1.0e-6`: the absolute tolerance for convergence. """ function kmeans(X::AbstractMatrix{<:Real}, r::AbstractVector{Int}, c::AbstractVector{Int}, μ::AbstractMatrix{<:Real}; maxiter::Int=256, dist::SemiMetric=SqEuclidean(), ϵ::AbstractFloat=1.0e-6) mx, n = size(X) mμ, k = size(μ) mx == mμ || throw(DimensionMismatch("number of data features must match")) k > 1 || throw(ArgumentError("number of clusters must at least be 2")) k <= n || throw(ArgumentError("more clusters than data instances are not allowed")) C = Matrix{Int}(undef, 0, 0) W = Matrix{Float64}(undef, 0, 0) Y = zeros(Float64, k, n) μ2 = convert(Matrix{Float64}, μ) pcs = Vector{PartitionalClustering}(undef, 0) distances = pairwise(dist, μ2, X, dims=2) pre_objcosts = 0 objcosts = 0 for i = 1:maxiter # Update cluster assignments, objective function costs, and cluster # centers (part 1/2) @inbounds for j = 1:n cost, y = findmin(view(distances, :, j)) Y[y, j] = 1 objcosts += cost μ2[:, y] += X[:, j] end # Update cluster centers (part 2/2) @inbounds for j = 1:k sz = sum(Y[j, :]) μ2[:, j] = iszero(sz) ? μ[:, j] : μ2[:, j] / sz end pairwise!(distances, dist, μ2, X, dims=2) pc = PartitionalClustering(copy(r), copy(c), copy(C), copy(W), copy(Y), (μ=copy(μ2),)) push!(pcs, pc) # Check for convergence isapprox(objcosts, pre_objcosts, atol=ϵ) && break fill!(Y, zero(eltype(Y))) fill!(μ2, zero(eltype(μ2))) pre_objcosts = objcosts objcosts = 0 end return pcs end """ kmeans(X::AbstractMatrix{<:Real}, μ::AbstractMatrix{<:Real}; <keyword arguments>) Like [`kmeans`](@ref), but automatically generate `r` and `c` according to the size of `X`. """ function kmeans(X::AbstractMatrix{<:Real}, μ::AbstractMatrix{<:Real}; maxiter::Int=256, dist::SemiMetric=SqEuclidean(), ϵ::AbstractFloat=1.0e-6) r = collect(1:size(X, 1)) c = collect(1:size(X, 2)) return kmeans(X, r, c, μ, maxiter=maxiter, dist=dist, ϵ=ϵ) end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
3385
#= """ transitive_closure!(A::AbstractMatrix{Int}) Compute the transitive closure of the matrix `A`. """ function transitive_closure!(A::AbstractMatrix{Int}) mustlinkto = findall(val -> val == 1, C) for instance in mustlinkto first = instance[1] second = instance[2] C[C[first, second] == && C[second, :]] == 1 end return A end """ """ function pckmeans(X::AbstractMatrix{<:Real}, C::AbstractMatrix{Int}, W::AbstractMatrix{<:Real}, k::Int; maxiter::Int=256, dist::SemiMetric=SqEuclidean(), ϵ::AbstractFloat=1.0e-6) pckmeans(X, C, W, M, maxiter=maxiter, dist=dist, ϵ=ϵ) end """ pckmeans(X::AbstractMatrix{<:Real}, C::AbstractMatrix{Int}, W::AbstractMatrix{<:Real}, M::AbstractMatrix{<:Real}; <keyword arguments>) Cluster the data `X` with the pairwise constrained ``k``-means algorithm. # Keyword arguments - `maxiter::Int=256`: the number of maximum iterations. - `dist::SemiMetric=SqEuclidean()`: the distance function. - `ϵ::AbstractFloat=1.0e-6`: the absolute tolerance for convergence. """ function pckmeans(X::AbstractMatrix{<:Real}, C::AbstractMatrix{Int}, W::AbstractMatrix{<:Real}, M::AbstractMatrix{<:Real}; maxiter::Int=256, dist::SemiMetric=SqEuclidean(), ϵ::AbstractFloat=1.0e-6) mx, nx = size(X) nc = size(C, 2) nw = size(W, 2) mm, k = size(M) mx == mm || throw(DimensionMismatch("number of data features must match")) nc == nx || throw(DimensionMismatch("number of data instances and maximum number of constraints must match")) nc == nw || throw(DimensionMismatch("dimensions of constraints and weights must match")) k > 1 || throw(ArgumentError("number of clusters must at least be 2")) k <= nx || throw(ArgumentError("more clusters than data instances are not allowed")) n = nx Y = zeros(Float64, k, n) M = convert(Matrix{Float64}, M) pcs = Vector{PartitionalClustering}(undef, 0) pc = PartitionalClustering(copy(X), copy(C), copy(W), copy(Y), copy(M)) push!(pcs, pc) # Derive neighborhood sets, and initialize the cluster centers transitive_closure!(C) distances = pairwise(dist, M, X, dims=2) pre_objcosts = 0 i = 1 while i <= maxiter costs = distances objcosts = 0 fill!(Y, zero(eltype(Y))) fill!(M, zero(eltype(M))) # Update cluster assignments, objective function costs, and center # coordinates per cluster @inbounds for j = 1:n cj = view(C, :, j) mustlinkto = findall(val -> val == 1, cj) for instance in mustlinkto y = argmax(view(Y, :, instance)) costs[, j] += W[, ] * 1 end cannotlink = findall(val -> val == -1, cj) cost, y = findmin(view(costs, :, j)) Y[y, j] = 1 objcosts += cost M[:, y] += X[:, j] end # Update cluster centers @inbounds for j = 1:k M[:, j] /= sum(Y[j, :]) end pairwise!(distances, dist, M, X, dims=2) pc = PartitionalClustering(X, C, W, Y, M) push!(pcs, pc) # Check for convergence isapprox(objcosts, pre_objcosts, atol=ϵ) && break pre_objcosts = objcosts i += 1 end return pcs end =#
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
3765
@testset "clustering" begin @testset "partitional clustering" begin r = [10, 20] c = [2, 3, 5] C = [0 0 0; 0 0 0; 0 0 0] W = [0 0 0; 0 0 0; 0 0 0] Y = [1 0 0.5; 0 1 0.5] p = (μ=[0 1.0; 1.0 0],) pc = PartitionalClustering(r, c, C, W, Y, p) pc2 = PartitionalClustering(r, c, C, W, Y, p) pc3 = PartitionalClustering(r, c, C, W, Y, p) @testset "constructors" begin @test isa(pc, PartitionalClustering) @test (pc.r == r && pc.c == c && pc.C == C && pc.W == W && pc.Y == Y && pc.p == p) end @testset "interface constructors" begin pc4 = PartitionalClustering(KmeansResult(p.μ, [1, 2, 1], [0.5, 0.25, 0.125], [2, 1], [2, 1], 0.875, 100, true)) @test isa(pc4, PartitionalClustering) @test (pc4.r == Int[] && pc4.c == Int[] && pc4.C == Matrix{Int}(undef, 0, 0) && pc4.W == Matrix{Float64}(undef, 0, 0) && pc4.Y == [1 0 1; 0 1 0] && pc4.p == (centers=p.μ, costs=[0.5, 0.25, 0.125], counts=[2, 1], wcounts=[2, 1], totalcost=0.875, iterations=100, converged=true)) pc4 = PartitionalClustering(KmedoidsResult([11, 23], [1, 2, 1], [0.5, 0.25, 0.125], [2, 1], 0.875, 100, true)) @test isa(pc4, PartitionalClustering) @test (pc4.r == Int[] && pc4.c == Int[] && pc4.C == Matrix{Int}(undef, 0, 0) && pc4.W == Matrix{Float64}(undef, 0, 0) && pc4.Y == [1 0 1; 0 1 0] && pc4.p == (medoids=[11, 23], costs=[0.5, 0.25, 0.125], counts=[2, 1], totalcost=0.875, iterations=100, converged=true)) pc4 = PartitionalClustering(FuzzyCMeansResult(p.μ, [1 0; 0.5 0.5; 1 0], 100, true)) @test isa(pc4, PartitionalClustering) @test (pc4.r == Int[] && pc4.c == Int[] && pc4.C == Matrix{Int}(undef, 0, 0) && pc4.W == Matrix{Float64}(undef, 0, 0) && pc4.Y == [1 0.5 1; 0 0.5 0] && pc4.p == (centers=p.μ, iterations=100, converged=true)) end @testset "equality operator" begin @test pc == pc @test pc == pc2 && pc2 == pc @test pc == pc2 && pc2 == pc3 && pc == pc3 end @testset "hash" begin @test hash(pc) == hash(pc) @test pc == pc2 && hash(pc) == hash(pc2) end @testset "accessors" begin @test axes(pc) == (r, c) @test features(pc) == axes(pc, 1) == r @test instances(pc) == axes(pc, 2) == c @test constraints(pc) == C @test weights(pc) == W @test parameters(pc) == p @test assignments(pc) == Y end end @testset "hierarchical clustering" begin r = [10, 20] c = [2, 3, 5] C = rand([-1, 0, 1], 3, 3, 3) W = rand(3, 3, 3) .+ 1 p = NamedTuple() hc = HierarchicalClustering(r, c, C, W, p) @testset "constructors" begin @test isa(hc, HierarchicalClustering) @test hc.r == r && hc.c == c && hc.C == C && hc.W == W && hc.p == p end @testset "accessors" begin @test axes(hc) == (r, c) @test features(hc) == axes(hc, 1) == r @test instances(hc) == axes(hc, 2) == c @test constraints(hc) == C @test weights(hc) == W @test parameters(hc) == p end end end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
3888
@testset "difference" begin pc = PartitionalClustering([1, 2], [1, 2, 3], [0 0 0; 0 0 0; 0 0 0], [0 0 0; 0 0 0; 0 0 0], [1 0 0.5; 0 1 0.5], (μ=[0 1; 1 0],)) pc2 = PartitionalClustering([1, 2], [1, 2, 3], [0 0 -1; 0 0 -1; -1 -1 0], [0 0 1; 0 0 1; 1 1 0], [1 0 0; 0 1 0; 0 0 1], (μ=[0 1 1; 1 0 1],)) # pc - pc2 r = SetDifference(Set([1, 2]), Set(), Set()) c = SetDifference(Set([1, 2, 3]), Set(), Set()) C = MatrixDifference(sparse([0, 0, 1, 0, 0, 1, 1, 1, 0]), [], []) W = MatrixDifference(sparse([0, 0, -1, 0, 0, -1, -1, -1, 0]), [], []) Y = MatrixDifference(sparse([0, 0, 0, 0, 0.5, 0.5]), [0, 0, 1], []) p = NamedTupleDifference((μ=MatrixDifference(sparse([0, 0, 0, 0]), [1, 1], []),), NamedTuple(), NamedTuple()) cd = PartitionalClusteringDifference(r, c, C, W, Y, p) cd2 = PartitionalClusteringDifference(r, c, C, W, Y, p) cd3 = PartitionalClusteringDifference(r, c, C, W, Y, p) # pc2 - pc r2 = SetDifference(Set([1, 2]), Set(), Set()) c2 = SetDifference(Set([1, 2, 3]), Set(), Set()) C2 = MatrixDifference(sparse([0, 0, -1, 0, 0, -1, -1, -1, 0]), [], []) W2 = MatrixDifference(sparse([0, 0, 1, 0, 0, 1, 1, 1, 0]), [], []) Y2 = MatrixDifference(sparse([0, 0, 0, 0, -0.5, -0.5]), [], [0, 0, 1]) p2 = NamedTupleDifference((μ=MatrixDifference(sparse([0, 0, 0, 0]), [], [1, 1]),), NamedTuple(), NamedTuple()) @testset "constructors" begin @test isa(cd, PartitionalClusteringDifference) @test (cd.r == r && cd.c == c && cd.C == C && cd.W == W && cd.Y == Y && cd.p == p) end @testset "equality operator" begin @test cd == cd @test cd == cd2 && cd2 == cd @test cd == cd2 && cd2 == cd3 && cd == cd3 end @testset "hash" begin @test hash(cd) == hash(cd) @test cd == cd2 && hash(cd) == hash(cd2) end @testset "accessors" begin @test axes(cd) == (r, c) @test features(cd) == axes(cd, 1) == r @test instances(cd) == axes(cd, 2) == c @test constraints(cd) == C @test weights(cd) == W @test assignments(cd) == Y @test parameters(cd) == p end @testset "subtraction operator" begin pc = PartitionalClustering([1, 2], [1, 2, 3], [0 0 0; 0 0 0; 0 0 0], [0 0 0; 0 0 0; 0 0 0], [1 0 0.5; 0 1 0.5], (μ=[0 1; 1 0],)) cd = pc - pc @test isa(cd, PartitionalClusteringDifference) @test (cd.r == SetDifference(Set([1, 2]), Set(), Set()) && cd.c == SetDifference(Set([1, 2, 3]), Set(), Set()) && cd.C == MatrixDifference(sparse([0, 0, 0, 0, 0, 0, 0, 0, 0]), [], []) && cd.W == MatrixDifference(sparse([0, 0, 0, 0, 0, 0, 0, 0, 0]), [], []) && cd.Y == MatrixDifference(sparse([0, 0, 0, 0, 0, 0]), [], []) && cd.p == NamedTupleDifference((μ=MatrixDifference(sparse([0, 0, 0, 0]), [], []),), NamedTuple(), NamedTuple())) cd = pc - pc2 @test isa(cd, PartitionalClusteringDifference) @test (cd.r == r && cd.c == c && cd.C == C && cd.W == W && cd.Y == Y && cd.p == p) cd = pc2 - pc @test isa(cd, PartitionalClusteringDifference) @test (cd.r == r2 && cd.c == c2 && cd.C == C2 && cd.W == W2 && cd.Y == Y2 && cd.p == p2) end @testset "forward difference" begin cd = forwarddiff([pc, pc2], 1) @test isa(cd, PartitionalClusteringDifference) @test (cd.r == r2 && cd.c == c2 && cd.C == C2 && cd.W == W2 && cd.Y == Y2 && cd.p == p2) end @testset "backward difference" begin cd = backwarddiff([pc, pc2], 2) @test isa(cd, PartitionalClusteringDifference) @test (cd.r == r2 && cd.c == c2 && cd.C == C2 && cd.W == W2 && cd.Y == Y2 && cd.p == p2) end end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
661
@testset "kmeans" begin X = [1 0 -1 0; 0 1 0 -1] μ = [1 -1; 1 -1] mx, n = size(X) mμ, k = size(μ) r = collect(1:n) c = collect(1:mx) pcs = kmeans(X, r, c, μ) pc = pcs[end] pcs2 = kmeans(X, μ) pc2 = pcs2[end] @test isa(pcs, Vector{PartitionalClustering}) @test size(pc.C) == size(pc2.C) == (0, 0) @test eltype(pc.C) == eltype(pc2.C) == Int @test size(pc.W) == size(pc2.W) == (0, 0) @test eltype(pc.W) == eltype(pc2.W) == Float64 @test size(pc.Y) == size(pc2.Y) == (k, n) @test all(y -> 0 <= y <= 1, pc.Y) && all(y -> 0 <= y <= 1, pc2.Y) @test size(pc.p.μ) == size(pc2.p.μ) == (mμ, k) end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
562
@testset "pckmeans" begin X = [1 0 -1 0 0; 0 1 0 -1 0] C = [0 1 0 0 0; 1 0 1 0 0; 0 1 0 1 0; 0 0 1 0 -1; 0 0 0 -1 0] W = abs.(C) M = [1 0; -1 0] mx, nx = size(X) mm, km = size(M) pcs = pckmeans(X, C, W, M) pc = pcs[end] @test isa(pcs, Vector{PartitionalClustering}) @test pc.X == X @test size(pc.C) == (nx, nx) @test eltype(pc.C) == Int @test size(pc.W) == (nx, nx) @test eltype(pc.W) == Float64 @test size(pc.Y) == (km, nx) @test all(y -> 0 <= y <= 1, pc.Y) @test size(pc.M) == (mm, km) end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
code
303
using ClusteringDifferences using DifferencesBase using SparseArrays using Test import Clustering: FuzzyCMeansResult, KmeansResult, KmedoidsResult @testset "ClusteringDifferences" begin include("clustering.jl") include("difference.jl") include("kmeans.jl") #include("pckmeans.jl") end
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
0.9.1
cb939e89416c71970cf9957141b614d4f93171a6
docs
1084
# ClusteringDifferences.jl [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/laschuet/ClusteringDifferences.jl/blob/master/LICENSE.txt) [![build status](https://travis-ci.com/laschuet/ClusteringDifferences.jl.svg?branch=master)](https://travis-ci.com/laschuet/ClusteringDifferences.jl) [![build status](https://ci.appveyor.com/api/projects/status/2e0kddhoawudilci/branch/master?svg=true)](https://ci.appveyor.com/project/laschuet/clusteringdifferences-jl/branch/master) [![coveralls status](https://coveralls.io/repos/github/laschuet/ClusteringDifferences.jl/badge.svg?branch=master)](https://coveralls.io/github/laschuet/ClusteringDifferences.jl?branch=master) [![codecov status](https://codecov.io/gh/laschuet/ClusteringDifferences.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/laschuet/ClusteringDifferences.jl) Clustering and clustering difference models. ## Installation Open a Julia REPL and enter ```julia ] add ClusteringDifferences ``` ## License ClusteringDifferences.jl is licensed under the [MIT License](./LICENSE.txt).
ClusteringDifferences
https://github.com/laschuet/ClusteringDifferences.jl.git
[ "MIT" ]
1.9.1
9e2f36d3c96a820c678f2f1f1782582fcf685bae
code
780
@static if Base.VERSION >= v"1.6" using TOML using Test else using Pkg: TOML using Test end # To generate the new UUID, we simply modify the first character of the original UUID const original_uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" const new_uuid = "9bb1440f-4735-579b-a4ab-409b98df4dab" # `@__DIR__` is the `.ci/` folder. # Therefore, `dirname(@__DIR__)` is the repository root. const project_filename = joinpath(dirname(@__DIR__), "Project.toml") @testset "Test that the UUID is unchanged" begin project_dict = TOML.parsefile(project_filename) @test project_dict["uuid"] == original_uuid end write( project_filename, replace( read(project_filename, String), r"uuid = .*?\n" => "uuid = \"$(new_uuid)\"\n", ), )
DelimitedFiles
https://github.com/JuliaData/DelimitedFiles.jl.git
[ "MIT" ]
1.9.1
9e2f36d3c96a820c678f2f1f1782582fcf685bae
code
428
using DelimitedFiles using Documenter: DocMeta, makedocs, deploydocs DocMeta.setdocmeta!(DelimitedFiles, :DocTestSetup, :(using DelimitedFiles); recursive=true) makedocs( modules = [DelimitedFiles], sitename = "DelimitedFiles", pages = Any[ "DelimitedFiles" => "index.md" ]; # strict = true, strict = Symbol[:doctest], ) deploydocs(repo = "github.com/JuliaData/DelimitedFiles.jl.git")
DelimitedFiles
https://github.com/JuliaData/DelimitedFiles.jl.git
[ "MIT" ]
1.9.1
9e2f36d3c96a820c678f2f1f1782582fcf685bae
code
28947
# This file is a part of Julia. License is MIT: https://julialang.org/license """ Utilities for reading and writing delimited files, for example ".csv". See [`readdlm`](@ref) and [`writedlm`](@ref). """ module DelimitedFiles using Mmap import Base: tryparse_internal, show export readdlm, writedlm invalid_dlm(::Type{Char}) = reinterpret(Char, 0xfffffffe) invalid_dlm(::Type{UInt8}) = 0xfe invalid_dlm(::Type{UInt16}) = 0xfffe invalid_dlm(::Type{UInt32}) = 0xfffffffe const offs_chunk_size = 5000 """ readdlm(source, T::Type; options...) The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as `\\n`. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = [5; 6; 7; 8]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y]) end; julia> readdlm("delim_file.txt", Int64) 4×2 Matrix{Int64}: 1 5 2 6 3 7 4 8 julia> readdlm("delim_file.txt", Float64) 4×2 Matrix{Float64}: 1.0 5.0 2.0 6.0 3.0 7.0 4.0 8.0 julia> rm("delim_file.txt") ``` """ readdlm(input, T::Type; opts...) = readdlm(input, invalid_dlm(Char), T, '\n'; opts...) """ readdlm(source, delim::AbstractChar, T::Type; options...) The end of line delimiter is taken as `\\n`. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = [1.1; 2.2; 3.3; 4.4]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y], ',') end; julia> readdlm("delim_file.txt", ',', Float64) 4×2 Matrix{Float64}: 1.0 1.1 2.0 2.2 3.0 3.3 4.0 4.4 julia> rm("delim_file.txt") ``` """ readdlm(input, dlm::AbstractChar, T::Type; opts...) = readdlm(input, dlm, T, '\n'; opts...) """ readdlm(source; options...) The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as `\\n`. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = ["a"; "b"; "c"; "d"]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y]) end; julia> readdlm("delim_file.txt") 4×2 Matrix{Any}: 1 "a" 2 "b" 3 "c" 4 "d" julia> rm("delim_file.txt") ``` """ readdlm(input; opts...) = readdlm(input, invalid_dlm(Char), '\n'; opts...) """ readdlm(source, delim::AbstractChar; options...) The end of line delimiter is taken as `\\n`. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = [1.1; 2.2; 3.3; 4.4]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y], ',') end; julia> readdlm("delim_file.txt", ',') 4×2 Matrix{Float64}: 1.0 1.1 2.0 2.2 3.0 3.3 4.0 4.4 julia> z = ["a"; "b"; "c"; "d"]; julia> open("delim_file.txt", "w") do io writedlm(io, [x z], ',') end; julia> readdlm("delim_file.txt", ',') 4×2 Matrix{Any}: 1 "a" 2 "b" 3 "c" 4 "d" julia> rm("delim_file.txt") ``` """ readdlm(input, dlm::AbstractChar; opts...) = readdlm(input, dlm, '\n'; opts...) """ readdlm(source, delim::AbstractChar, eol::AbstractChar; options...) If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned. """ readdlm(input, dlm::AbstractChar, eol::AbstractChar; opts...) = readdlm_auto(input, dlm, Float64, eol, true; opts...) """ readdlm(source, delim::AbstractChar, T::Type, eol::AbstractChar; header=false, skipstart=0, skipblanks=true, use_mmap, quotes=true, dims, comments=false, comment_char='#') Read a matrix from the source where each line (separated by `eol`) gives one row, with elements separated by the given delimiter. The source can be a text file, stream or byte array. Memory mapped files can be used by passing the byte array representation of the mapped segment as source. If `T` is a numeric type, the result is an array of that type, with any non-numeric elements as `NaN` for floating-point types, or zero. Other useful values of `T` include `String`, `AbstractString`, and `Any`. If `header` is `true`, the first row of data will be read as header and the tuple `(data_cells, header_cells)` is returned instead of only `data_cells`. Specifying `skipstart` will ignore the corresponding number of initial lines from the input. If `skipblanks` is `true`, blank lines in the input will be ignored. If `use_mmap` is `true`, the file specified by `source` is memory mapped for potential speedups if the file is large. Default is `false`. On a Windows filesystem, `use_mmap` should not be set to `true` unless the file is only read once and is also not written to. Some edge cases exist where an OS is Unix-like but the filesystem is Windows-like. If `quotes` is `true`, columns enclosed within double-quote (\") characters are allowed to contain new lines and column delimiters. Double-quote characters within a quoted field must be escaped with another double-quote. Specifying `dims` as a tuple of the expected rows and columns (including header, if any) may speed up reading of large files. If `comments` is `true`, lines beginning with `comment_char` and text following `comment_char` in any line are ignored. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = [5; 6; 7; 8]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y]) end julia> readdlm("delim_file.txt", '\\t', Int, '\\n') 4×2 Matrix{Int64}: 1 5 2 6 3 7 4 8 julia> rm("delim_file.txt") ``` """ readdlm(input, dlm::AbstractChar, T::Type, eol::AbstractChar; opts...) = readdlm_auto(input, dlm, T, eol, false; opts...) readdlm_auto(input::Vector{UInt8}, dlm::AbstractChar, T::Type, eol::AbstractChar, auto::Bool; opts...) = readdlm_string(String(copyto!(Base.StringVector(length(input)), input)), dlm, T, eol, auto, val_opts(opts)) readdlm_auto(input::IO, dlm::AbstractChar, T::Type, eol::AbstractChar, auto::Bool; opts...) = readdlm_string(read(input, String), dlm, T, eol, auto, val_opts(opts)) function readdlm_auto(input::AbstractString, dlm::AbstractChar, T::Type, eol::AbstractChar, auto::Bool; opts...) isfile(input) || throw(ArgumentError("Cannot open \'$input\': not a file")) optsd = val_opts(opts) use_mmap = get(optsd, :use_mmap, false) fsz = filesize(input) if use_mmap && fsz > 0 && fsz < typemax(Int) a = open(input, "r") do f mmap(f, Vector{UInt8}, (Int(fsz),)) end # TODO: It would be nicer to use String(a) without making a copy, # but because the mmap'ed array is not NUL-terminated this causes # jl_try_substrtod to segfault below. return readdlm_string(GC.@preserve(a, unsafe_string(pointer(a),length(a))), dlm, T, eol, auto, optsd) else return readdlm_string(read(input, String), dlm, T, eol, auto, optsd) end end # # Handlers act on events generated by the parser. # Parser calls store_cell on the handler to pass events. # # DLMOffsets: Keep offsets (when result dimensions are not known) # DLMStore: Store values directly into a result store (when result dimensions are known) abstract type DLMHandler end mutable struct DLMOffsets <: DLMHandler oarr::Vector{Vector{Int}} offidx::Int thresh::Int bufflen::Int function DLMOffsets(sbuff::String) offsets = Vector{Vector{Int}}(undef, 1) offsets[1] = Vector{Int}(undef, offs_chunk_size) thresh = ceil(min(typemax(UInt), Base.Sys.total_memory()) / sizeof(Int) / 5) new(offsets, 1, thresh, sizeof(sbuff)) end end function store_cell(dlmoffsets::DLMOffsets, row::Int, col::Int, quoted::Bool, startpos::Int, endpos::Int) offidx = dlmoffsets.offidx (offidx == 0) && return # offset collection stopped to avoid choking on memory oarr = dlmoffsets.oarr offsets = oarr[end] if length(offsets) < offidx offlen = offs_chunk_size * length(oarr) if (offlen + offs_chunk_size) > dlmoffsets.thresh est_tot = round(Int, offlen * dlmoffsets.bufflen / endpos) if (est_tot - offlen) > offs_chunk_size # allow another chunk # abandon offset collection dlmoffsets.oarr = Vector{Int}[] dlmoffsets.offidx = 0 return end end offsets = Vector{Int}(undef, offs_chunk_size) push!(oarr, offsets) offidx = 1 end offsets[offidx] = row offsets[offidx+1] = col offsets[offidx+2] = Int(quoted) offsets[offidx+3] = startpos offsets[offidx+4] = endpos dlmoffsets.offidx = offidx + 5 nothing end function result(dlmoffsets::DLMOffsets) trimsz = (dlmoffsets.offidx-1) % offs_chunk_size ((trimsz > 0) || (dlmoffsets.offidx == 1)) && resize!(dlmoffsets.oarr[end], trimsz) dlmoffsets.oarr end mutable struct DLMStore{T} <: DLMHandler hdr::Array{AbstractString, 2} data::Array{T, 2} nrows::Int ncols::Int lastrow::Int lastcol::Int hdr_offset::Int sbuff::String auto::Bool eol::Char end function DLMStore(::Type{T}, dims::NTuple{2,Int}, has_header::Bool, sbuff::String, auto::Bool, eol::Char) where T (nrows,ncols) = dims nrows <= 0 && throw(ArgumentError("number of rows in dims must be > 0, got $nrows")) ncols <= 0 && throw(ArgumentError("number of columns in dims must be > 0, got $ncols")) hdr_offset = has_header ? 1 : 0 DLMStore{T}(fill(SubString(sbuff,1,0), 1, ncols), Matrix{T}(undef, nrows-hdr_offset, ncols), nrows, ncols, 0, 0, hdr_offset, sbuff, auto, eol) end function DLMStore(::Type{T}, dims::NTuple{2,Integer}, has_header::Bool, sbuff::String, auto::Bool, eol::AbstractChar) where T nrows, ncols = dims DLMStore(T, (Int(nrows)::Int, Int(ncols)::Int), has_header, sbuff, auto, Char(eol)::Char) end _chrinstr(sbuff::String, chr::UInt8, startpos::Int, endpos::Int) = GC.@preserve sbuff (endpos >= startpos) && (C_NULL != ccall(:memchr, Ptr{UInt8}, (Ptr{UInt8}, Int32, Csize_t), pointer(sbuff)+startpos-1, chr, endpos-startpos+1)) function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int, quoted::Bool, startpos::Int, endpos::Int) where T drow = row - dlmstore.hdr_offset ncols = dlmstore.ncols lastcol = dlmstore.lastcol lastrow = dlmstore.lastrow cells::Matrix{T} = dlmstore.data sbuff = dlmstore.sbuff endpos = prevind(sbuff, nextind(sbuff,endpos)) if (endpos > 0) && ('\n' == dlmstore.eol) && ('\r' == Char(sbuff[endpos])) endpos = prevind(sbuff, endpos) end if quoted startpos += 1 endpos = prevind(sbuff, endpos) end if drow > 0 # fill missing elements while ((drow - lastrow) > 1) || ((drow > lastrow > 0) && (lastcol < ncols)) if (lastcol == ncols) || (lastrow == 0) lastcol = 0 lastrow += 1 end for cidx in (lastcol+1):ncols if (T <: AbstractString) || (T == Any) cells[lastrow, cidx] = SubString(sbuff, 1, 0) elseif ((T <: Number) || (T <: AbstractChar)) && dlmstore.auto throw(TypeError(:store_cell, "", Any, T)) else error("missing value at row $lastrow column $cidx") end end lastcol = ncols end # fill data if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos) unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"") fail = colval(unescaped, 1, lastindex(unescaped), cells, drow, col) else fail = colval(sbuff, startpos, endpos, cells, drow, col) end if fail sval = SubString(sbuff, startpos, endpos) if (T <: Number) && dlmstore.auto throw(TypeError(:store_cell, "", Any, T)) else error("file entry \"$(sval)\" cannot be converted to $T") end end dlmstore.lastrow = drow dlmstore.lastcol = col else # fill header if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos) unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"") colval(unescaped, 1, lastindex(unescaped), dlmstore.hdr, 1, col) else colval(sbuff, startpos, endpos, dlmstore.hdr, 1, col) end end nothing end function result(dlmstore::DLMStore{T}) where T nrows = dlmstore.nrows - dlmstore.hdr_offset ncols = dlmstore.ncols lastcol = dlmstore.lastcol lastrow = dlmstore.lastrow cells = dlmstore.data sbuff = dlmstore.sbuff if (nrows > 0) && ((lastcol < ncols) || (lastrow < nrows)) while lastrow <= nrows (lastcol == ncols) && (lastcol = 0; lastrow += 1) for cidx in (lastcol+1):ncols if (T <: AbstractString) || (T == Any) cells[lastrow, cidx] = SubString(sbuff, 1, 0) elseif ((T <: Number) || (T <: AbstractChar)) && dlmstore.auto throw(TypeError(:store_cell, "", Any, T)) else error("missing value at row $lastrow column $cidx") end end lastcol = ncols (lastrow == nrows) && break end dlmstore.lastrow = lastrow dlmstore.lastcol = ncols end (dlmstore.hdr_offset > 0) ? (dlmstore.data, dlmstore.hdr) : dlmstore.data end function readdlm_string(sbuff::String, dlm::AbstractChar, T::Type, eol::AbstractChar, auto::Bool, optsd::Dict) ign_empty = (dlm == invalid_dlm(Char)) quotes = get(optsd, :quotes, true) comments = get(optsd, :comments, false) comment_char = get(optsd, :comment_char, '#') dims = get(optsd, :dims, nothing) has_header = get(optsd, :header, get(optsd, :has_header, false)) haskey(optsd, :has_header) && (optsd[:has_header] != has_header) && throw(ArgumentError("conflicting values for header and has_header")) skipstart = get(optsd, :skipstart, 0) (skipstart >= 0) || throw(ArgumentError("skipstart must be ≥ 0, got $skipstart")) skipblanks = get(optsd, :skipblanks, true) offset_handler = (dims === nothing) ? DLMOffsets(sbuff) : DLMStore(T, dims, has_header, sbuff, auto, eol) for retry in 1:2 try dims = dlm_parse(sbuff, eol, dlm, '"', comment_char, ign_empty, quotes, comments, skipstart, skipblanks, offset_handler) break catch ex if isa(ex, TypeError) && (ex.func === :store_cell) T = ex.expected else rethrow() end offset_handler = (dims === nothing) ? DLMOffsets(sbuff) : DLMStore(T, dims, has_header, sbuff, auto, eol) end end isa(offset_handler, DLMStore) && (return result(offset_handler)) offsets = result(offset_handler) !isempty(offsets) && (return dlm_fill(T, offsets, dims, has_header, sbuff, auto, eol)) optsd[:dims] = dims return readdlm_string(sbuff, dlm, T, eol, auto, optsd) end const valid_opts = [:header, :has_header, :use_mmap, :quotes, :comments, :dims, :comment_char, :skipstart, :skipblanks] const valid_opt_types = [Bool, Bool, Bool, Bool, Bool, NTuple{2,Integer}, Char, Integer, Bool] function val_opts(opts) d = Dict{Symbol, Union{Bool, NTuple{2, Integer}, Char, Integer}}() for (opt_name, opt_val) in opts in(opt_name, valid_opts) || throw(ArgumentError("unknown option $opt_name")) opt_typ = valid_opt_types[findfirst(isequal(opt_name), valid_opts)::Int] isa(opt_val, opt_typ) || throw(ArgumentError("$opt_name should be of type $opt_typ, got $(typeof(opt_val))")) d[opt_name] = opt_val end return d end function dlm_fill(T::DataType, offarr::Vector{Vector{Int}}, dims::NTuple{2,Integer}, has_header::Bool, sbuff::String, auto::Bool, eol::AbstractChar) idx = 1 offidx = 1 offsets = offarr[1] row = 0 col = 0 try dh = DLMStore(T, dims, has_header, sbuff, auto, eol) while idx <= length(offsets) row = offsets[idx] col = offsets[idx+1] quoted = offsets[idx+2] != 0 startpos = offsets[idx+3] endpos = offsets[idx+4] ((idx += 5) > offs_chunk_size) && (offidx < length(offarr)) && (idx = 1; offsets = offarr[offidx += 1]) store_cell(dh, row, col, quoted, startpos, endpos) end return result(dh) catch ex isa(ex, TypeError) && (ex.func === :store_cell) && (return dlm_fill(ex.expected, offarr, dims, has_header, sbuff, auto, eol)) error("at row $row, column $col : $ex") end end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Bool,2}, row::Int, col::Int) n = tryparse_internal(Bool, sbuff, startpos, endpos, 0, false) n === nothing || (cells[row, col] = n) n === nothing end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{T,2}, row::Int, col::Int) where T<:Integer n = tryparse_internal(T, sbuff, startpos, endpos, 0, false) n === nothing || (cells[row, col] = n) n === nothing end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{T,2}, row::Int, col::Int) where T<:Union{Real,Complex} n = tryparse_internal(T, sbuff, startpos, endpos, false) n === nothing || (cells[row, col] = n) n === nothing end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{<:AbstractString,2}, row::Int, col::Int) cells[row, col] = SubString(sbuff, startpos, endpos) return false end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Any,2}, row::Int, col::Int) # if array is of Any type, attempt parsing only the most common types: Int, Bool, Float64 and fallback to SubString len = endpos-startpos+1 if len > 0 # check Inteter ni64 = tryparse_internal(Int, sbuff, startpos, endpos, 0, false) ni64 === nothing || (cells[row, col] = ni64; return false) # check Bool nb = tryparse_internal(Bool, sbuff, startpos, endpos, 0, false) nb === nothing || (cells[row, col] = nb; return false) # check float64 hasvalue, valf64 = ccall(:jl_try_substrtod, Tuple{Bool, Float64}, (Ptr{UInt8}, Csize_t, Csize_t), sbuff, startpos-1, endpos-startpos+1) hasvalue && (cells[row, col] = valf64; return false) end cells[row, col] = SubString(sbuff, startpos, endpos) false end function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{<:AbstractChar,2}, row::Int, col::Int) if startpos == endpos cells[row, col] = iterate(sbuff, startpos)[1] return false else return true end end colval(sbuff::String, startpos::Int, endpos::Int, cells::Array, row::Int, col::Int) = true function dlm_parse(dbuff::String, eol::D, dlm::D, qchar::D, cchar::D, ign_adj_dlm::Bool, allow_quote::Bool, allow_comments::Bool, skipstart::Int, skipblanks::Bool, dh::DLMHandler) where D ncols = nrows = col = 0 is_default_dlm = (dlm == invalid_dlm(D)) error_str = "" # 0: begin field, 1: quoted field, 2: unquoted field, # 3: second quote (could either be end of field or escape character), # 4: comment, 5: skipstart state = (skipstart > 0) ? 5 : 0 is_eol = is_dlm = is_cr = is_quote = is_comment = expct_col = false idx = 1 try slen = sizeof(dbuff) col_start_idx = 1 was_cr = false while idx <= slen val,idx = iterate(dbuff, idx) if (is_eol = (Char(val) == Char(eol))) is_dlm = is_comment = is_cr = is_quote = false elseif (is_dlm = (is_default_dlm ? isspace(Char(val)) : (Char(val) == Char(dlm)))) is_comment = is_cr = is_quote = false elseif (is_quote = (Char(val) == Char(qchar))) is_comment = is_cr = false elseif (is_comment = (Char(val) == Char(cchar))) is_cr = false else is_cr = (Char(eol) == '\n') && (Char(val) == '\r') end if 2 == state # unquoted field if is_dlm state = 0 col += 1 store_cell(dh, nrows+1, col, false, col_start_idx, idx-2) col_start_idx = idx !ign_adj_dlm && (expct_col = true) elseif is_eol nrows += 1 col += 1 store_cell(dh, nrows, col, false, col_start_idx, idx - (was_cr ? 3 : 2)) col_start_idx = idx ncols = max(ncols, col) col = 0 state = 0 elseif (is_comment && allow_comments) nrows += 1 col += 1 store_cell(dh, nrows, col, false, col_start_idx, idx - 2) ncols = max(ncols, col) col = 0 state = 4 end elseif 1 == state # quoted field is_quote && (state = 3) elseif 4 == state # comment line if is_eol col_start_idx = idx state = 0 end elseif 0 == state # begin field if is_quote state = (allow_quote && !was_cr) ? 1 : 2 expct_col = false elseif is_dlm if !ign_adj_dlm expct_col = true col += 1 store_cell(dh, nrows+1, col, false, col_start_idx, idx-2) end col_start_idx = idx elseif is_eol if (col > 0) || !skipblanks nrows += 1 if expct_col col += 1 store_cell(dh, nrows, col, false, col_start_idx, idx - (was_cr ? 3 : 2)) end ncols = max(ncols, col) col = 0 end col_start_idx = idx expct_col = false elseif is_comment && allow_comments if col > 0 nrows += 1 if expct_col col += 1 store_cell(dh, nrows, col, false, col_start_idx, idx - 2) end ncols = max(ncols, col) col = 0 end expct_col = false state = 4 elseif !is_cr state = 2 expct_col = false end elseif 3 == state # second quote if is_quote && !was_cr state = 1 elseif is_dlm && !was_cr state = 0 col += 1 store_cell(dh, nrows+1, col, true, col_start_idx, idx-2) col_start_idx = idx !ign_adj_dlm && (expct_col = true) elseif is_eol nrows += 1 col += 1 store_cell(dh, nrows, col, true, col_start_idx, idx - (was_cr ? 3 : 2)) col_start_idx = idx ncols = max(ncols, col) col = 0 state = 0 elseif is_comment && allow_comments && !was_cr nrows += 1 col += 1 store_cell(dh, nrows, col, true, col_start_idx, idx - 2) ncols = max(ncols, col) col = 0 state = 4 elseif (is_cr && was_cr) || !is_cr error_str = escape_string("unexpected character '$(Char(val))' after quoted field at row $(nrows+1) column $(col+1)") break end elseif 5 == state # skip start if is_eol col_start_idx = idx skipstart -= 1 (0 == skipstart) && (state = 0) end end was_cr = is_cr end if isempty(error_str) if 1 == state # quoted field error_str = "truncated column at row $(nrows+1) column $(col+1)" elseif (2 == state) || (3 == state) || ((0 == state) && is_dlm) # unquoted field, second quote, or begin field with last character as delimiter col += 1 nrows += 1 store_cell(dh, nrows, col, (3 == state), col_start_idx, idx-1) ncols = max(ncols, col) end end catch ex if isa(ex, TypeError) && (ex.func === :store_cell) rethrow() else error("at row $(nrows+1), column $col : $ex)") end end !isempty(error_str) && error(error_str) return (nrows, ncols) end # todo: keyword argument for # of digits to print writedlm_cell(io::IO, elt::AbstractFloat, dlm, quotes) = print(io, elt) function writedlm_cell(io::IO, elt::AbstractString, dlm::T, quotes::Bool) where T if quotes && !isempty(elt) && (('"' in elt) || ('\n' in elt) || ((T <: AbstractChar) ? (dlm in elt) : occursin(dlm, elt))) print(io, '"', replace(elt, r"\"" => "\"\""), '"') else print(io, elt) end end writedlm_cell(io::IO, elt, dlm, quotes) = print(io, elt) function writedlm(io::IO, a::AbstractMatrix, dlm; opts...) optsd = val_opts(opts) quotes = get(optsd, :quotes, true) pb = PipeBuffer() lastc = last(axes(a, 2)) for i = axes(a, 1) for j = axes(a, 2) writedlm_cell(pb, a[i, j], dlm, quotes) j == lastc ? print(pb,'\n') : print(pb,dlm) end (bytesavailable(pb) > (16*1024)) && write(io, take!(pb)) end write(io, take!(pb)) nothing end writedlm(io::IO, a::AbstractArray{<:Any,0}, dlm; opts...) = writedlm(io, reshape(a,1), dlm; opts...) # write an iterable row as dlm-separated items function writedlm_row(io::IO, row, dlm, quotes) y = iterate(row) while y !== nothing (x, state) = y y = iterate(row, state) writedlm_cell(io, x, dlm, quotes) y === nothing ? print(io,'\n') : print(io,dlm) end end # If the row is a single string, write it as a string rather than # iterating over characters. Also, include the common case of # a Number (handled correctly by the generic writedlm_row above) # purely as an optimization. function writedlm_row(io::IO, row::Union{Number,AbstractString}, dlm, quotes) writedlm_cell(io, row, dlm, quotes) print(io, '\n') end # write an iterable collection of iterable rows function writedlm(io::IO, itr, dlm; opts...) optsd = val_opts(opts) quotes = get(optsd, :quotes, true) pb = PipeBuffer() for row in itr writedlm_row(pb, row, dlm, quotes) (bytesavailable(pb) > (16*1024)) && write(io, take!(pb)) end write(io, take!(pb)) nothing end function writedlm(fname::AbstractString, a, dlm; opts...) open(fname, "w") do io writedlm(io, a, dlm; opts...) end end """ writedlm(f, A, delim='\\t'; opts) Write `A` (a vector, matrix, or an iterable collection of iterable rows) as text to `f` (either a filename string or an `IO` stream) using the given delimiter `delim` (which defaults to tab, but can be any printable Julia object, typically a `Char` or `AbstractString`). For example, two vectors `x` and `y` of the same length can be written as two columns of tab-delimited text to `f` by either `writedlm(f, [x y])` or by `writedlm(f, zip(x, y))`. # Examples ```jldoctest julia> using DelimitedFiles julia> x = [1; 2; 3; 4]; julia> y = [5; 6; 7; 8]; julia> open("delim_file.txt", "w") do io writedlm(io, [x y]) end julia> readdlm("delim_file.txt", '\\t', Int, '\\n') 4×2 Matrix{Int64}: 1 5 2 6 3 7 4 8 julia> rm("delim_file.txt") ``` """ writedlm(io, a; opts...) = writedlm(io, a, '\t'; opts...) show(io::IO, ::MIME"text/csv", a) = writedlm(io, a, ',') show(io::IO, ::MIME"text/tab-separated-values", a) = writedlm(io, a, '\t') end # module DelimitedFiles
DelimitedFiles
https://github.com/JuliaData/DelimitedFiles.jl.git