Skip to content

BasicTypes.jl

Documentation for BasicTypes.jl.

BasicTypes.NotSet Type
julia
NotSet = Union{NotProvided, NotSimulated}
source
BasicTypes.Optional Type
julia
Optional{T} = Union{T, NotProvided, NotSimulated}

This type alias is used to represent an optional value, mostly for use as type of struct fields for which a default value (either NotProvided or NotSimulated) is expected and used as default in the type's constructor.

source
BasicTypes.Point Type
julia
Point{N,T} = Union{Tuple{Vararg{T, N}},SVector{N,<:T}}
Point2D = Point{2, Union{Real, Unitful.Quantity{<:Real}}}
Point3D = Point{3, Union{Real, Unitful.Quantity{<:Real}}}
source
BasicTypes.ValidAngle Type
julia
const ValidAngle = Union{UnitfulAngleQuantity, Real}

Union type representing a scalar value that can be interpreted as an angle, which can be either a unitless real number, or a Unitful.Quantity with u"rad" or u"°" as unit.

source
BasicTypes.ValidDistance Type
julia
const ValidDistance = Union{Len, Real}

Union type representing a scalar value that can be interpreted as a distance, which can be either a unitless real number, or a Unitful.Quantity with a valid Length unit.

source
BasicTypes.EmptyIterator Type
julia
abstract type EmptyIterator end

Abstract type which defines methods so that concrete subtypes behave as empty iterators, so that the code:

for item in T()
    # Do something
end

where T <: EmptyIterator will simply do nothing.

source
BasicTypes.ExtraOutput Type
julia
ExtraOutput

Singleton type used for dispatch, and specifically to create function methods that return more than one output.

source
BasicTypes.NoTrait Type
julia
struct NoTrait end

Singleton type used to indicate that a trait is not implemented, resorting the eventual default behavior.

source
BasicTypes.NotProvided Type
julia
NotProvided <: EmptyIterator

Type used to specify that a field is not provided. This is useful when a field is optional and the user wants to specify that it is not provided, instead of using nothing which could be a valid value for the field.

source
BasicTypes.NotSimulated Type
julia
NotSimulated <: EmptyIterator

Custom type to indicate that a certain operation or function is not simulated. Used mostly for dispatch and for explicitly indicating that something should be skipped during the simulation (without relying on nothing or missing).

source
BasicTypes.PropertyOrNothing Type
julia
PropertyOrNothing{name}

Singleton structure that can be used as a functor of the form:

julia
PropertyOrNothing{name}(object)

to extract the property name from the provided object, falling back to returning nothing if the provided object does not have a property called name.

This is mostly useful as a fallback (or part of a fallback) to be used with getproperty_oftype.

source
BasicTypes.SkipChecks Type
julia
struct SkipChecks end

Singleton type used for dispatch to indicate that a certain check should be skipped.

source
BasicTypes.asdeg Method
julia
asdeg(x::Real)

Convert the provided value assumed to be in radians to Unitful degrees.

The stripdeg function performs the inverse operation.

julia
julia> using BasicTypes

julia> asdeg(π)
180.0°
source
BasicTypes.basetype Method
julia
basetype(t)

Returns the type of t, removing type parameters if for parametric types (thus returning the more generic UnionAll type for typeof(t))

julia
basetype(rand(Complex{Float64})) === Complex
source
BasicTypes.change_valuetype Function
julia
change_valuetype(::Type{T}, x)

Change the type of the value contained in x to T.

If x is a primitive type like Number, this will convert x to T and return it. If x is a container type like SVector{T}, this will convert the elements of x to T.

source
BasicTypes.common_valuetype Function
julia
common_valuetype(::Type{BaseType}, ::Type{DefaultType}, args...)

Determine the common value type of the arguments args..., ensuring it is a subtype of BaseType. For args that are containers, such as AbstractArray{T}, the common value type is determined by the element type T.

If the promoted value type of args... is not a subtype of BaseType, then DefaultType is returned instead.

Arguments

  • BaseType::Type: The required base type for the common value type.

  • DefaultType::Type: The fallback type if the common value type is not a subtype of BaseType.

  • args...: Arguments from which to determine the common value type.

Returns

The common value type of args..., or DefaultType if the common type is not a subtype of BaseType.

source
BasicTypes.constructor_without_checks Function
julia
constructor_without_checks(T, args...)

Custom types T with inner constructors that do checks on inputs may want to implement a method for this function where T is the specific type and args... are just the fields of T.

This method must be defined inside the struct definition and should simply return new(args...), as a way to create an instance of the type without running the potentially expensive checks.

This is especially useful for internal methods that might already know that the inputs are valid and within bounds, so they can skip the checks.

Example

julia
struct MyType{T}
    x::T
    y::T
    #= 
    This is an unsafe constructor that skips all the input checks, we have this as our only inner constructor. 
    The `CoordinateSystemsBase` is important (even if explicitly imported in the
    parent module), or a local function with the same name will be created in
    the local scope of the struct definition body.
    =#
    BasicTypes.constructor_without_checks(::Type{MyType{T}}, x::T, y::T) where T = new{T}(x, y)
end
# We define the constructor with checks as an outer one, but we could have also done this inside the struct definition
function MyType{T}(x::T, y::T)
    # do some input checks...
    validated_x = check_x(x)
    validated_y = check_y(y)
    # Return the potentially modified inputs, if we had this as inner constructor this last line would be `new{T}(validated_x, validated_y)`
    BasicTypes.constructor_without_checks(MyType{T}, validated_x, validated_y)
end
source
BasicTypes.enforce_unit Method
julia
enforce_unit(reference, value)
enforce_unit(reference)

Takes the provided value (supposed to represent a quantity tied to a specific unit) and converts it so that it to the unit provided as reference.

Note

The provided reference must represent a unit compatible with the unit expected from value.

In case only reference is provided (second signature above), this function simply returns Base.Fix1(enforce_unit, reference).

Arguments

  • reference: The unit to convert value to. It can be an instance from one of the following types:

    • Unitful.Units: e.g. u"m".

    • Type{<:Quantity}: e.g. typeof(1u"°").

    • Quantity: e.g. 2f0 * u"m/s".

  • value: The value to convert. It can be an instance from one of the following types:

    • Quantity: e.g. 2f0 * u"m/s".

    • Number: A unitless number. NOTE: In this case, the number is simply assumed to already have the right scale and simply returned as a Quantity with the provided reference unit.

Examples

julia
julia> using BasicTypes

julia> enforce_unit(u"m", 2f0 * u"km/h") # Throws are units are not compatible
ERROR: DimensionError:

julia> enforce_unit(typeof(1f0u"m"), 1km) # Also converts to Float32 as the provided reference is a Float32 quantity
1000.0f0 m

julia> enforce_unit(1f0u"rad", 10°) # Also converts to Float32 as the provided reference is a Float32 quantity
0.17453292f0 rad

julia> enforce_unit(1u"km", 3u"m") # Providing a quantity directly also tries to enforce the precision
ERROR: InexactError:

julia> enforce_unit(u"km", 3u"m") # This will not enforce precision
3//1000 km

julia> enforce_unit(u"km", 3) # This will simply apply the desired unit to the provided value
3 km

julia> 1km |> enforce_unit(u"m")  float # Test the method returning a function
1000.0 m

See also: enforce_unitless

source
BasicTypes.enforce_unitless Method
julia
enforce_unitless(reference, value)
enforce_unitless(reference)

Takes the provided value (supposed to represent a quantity tied to a specific unit), converts it to the unit represented by reference and then strips the units. This will simply call ustrip(enforce_unit(reference, value)).

If only reference is provided (second signature above), this function simply returns Base.Fix1(enforce_unitless, reference).

See enforce_unit for more details on the supported argument types.

Examples

julia
julia> using BasicTypes

julia> enforce_unitless(1f0u"m", 1km)
1000.0f0

julia> enforce_unitless(u"m", 1)
1

julia> 1km |> enforce_unitless(u"m")  float # Test the method returning a function
1000.0
source
BasicTypes.fallback Function
julia
fallback(x...)

Return the first value in the arguments which is set, i.e. is not equal to NotProvided or NotSimulated. If no value is found, an ArgumentError is thrown.

Examples

julia> x = NotProvided()
julia> y = NotSimulated()
julia> z = 1.0
julia> fallback(x, y, z)
1.0
source
BasicTypes.getproperty_oftype Function
julia
getproperty_oftype(container, target_type::Type, fallback, default)
getproperty_oftype(container, target_type::Type, fallback, exception::Exception)
getproperty_oftype(container, target_type::Type[, fallback]; exception::Exception)

Returns the first field of container which satisfies field isa target_type.

Note

When the type of a specific field (as returned by fieldtype) is Optional{T} (with T being any arbitrary type), the function will actually tests for T <: target_type rather than Optional{T} <: target_type

In case no field is found this way, the function will try to extract the desired property calling fallback(container).

If fallback(container) returns nothing, the function will finally return the provided default, or throw the provided exception.

Note

This function can not be called with a target_type === Optional or target_type <: Union{Nothing, NotSet}.

The second method is a convenience methdo which allow customizing the default exception thrown when fallback(container) returns nothing, and defaults fallback = Returns(nothing).

Example

julia
julia> using BasicTypes

julia> @kwdef struct MyType
           a::Int
           b::Float64
           c::Optional{String} = NotProvided()
       end;

julia> getproperty_oftype(MyType(1, 2.0, "test"), String) # Returns field `c`
"test"

julia> getproperty_oftype(MyType(; a = 1, b = 2.0), String) # Still returns `c` even if its value is not actually a String as its field is `Optional{String}`
NotProvided()

julia> getproperty_oftype(MyType(; a = 1, b = 2.0), ComplexF64, PropertyOrNothing(:b)) # This will return field `:b` as fallback
2.0

julia> getproperty_oftype(MyType(; a = 1, b = 2.0), ComplexF64, PropertyOrNothing(:d), 15) # This will fail the type check and the fallback, and returns 15
15

julia> try
           # This throws an error as it couldn't find a field with the right type and has no fallback
           getproperty_oftype((; a = 1), String; exception = ArgumentError("OPS"))
       catch e
           e.msg
       end
"OPS"
source
BasicTypes.isnotset Method
julia
isnotset(x)

Return true if x is not set to a value. (That is, x is either NotProvided or NotSimulated)

source
BasicTypes.isprovided Method
julia
isprovided(x) -> Bool

Check if the value x is not of type NotProvided. Returns true if x is provided, otherwise false.

source
BasicTypes.issimulated Method
julia
issimulated(x) -> Bool

Check if x is simulated by verifying its type is not NotSimulated. Returns true if x is simulated, false otherwise.

source
BasicTypes.progress_logger Method
julia
progress_logger()

Returns the logger to use for progress monitoring via ProgressLogging.jl.

When called from the REPL (checking the isinteractive function), it will return a TeeLogger (from LoggingExtras.jl) containing the current logger and a TerminalLogger (from TerminalLoggers.jl). This is because the @progress macro from ProgressLogging.jl does not print the progress bar in the REPL without TerminalLogger.

Outside of interactive sessions, it will simply return the current logger.

source
BasicTypes.promote_valuetype Function
julia
promote_valuetype(::Type{BaseType}, ::Type{DefaultType}, args...)

Cbange the value type of the arguments args... to a common type that is a subtype of BaseType. For args that are containers, such as AbstractArray{T}, the type of the underlying elements is changed. If the promoted value type of args... is not a subtype of BaseType, then DefaultType is used instead.

Arguments

  • BaseType::Type: The required base type for the common value type.

  • DefaultType::Type: The fallback type if the common value type is not a subtype of BaseType.

  • args...: Arguments to convert to the common value type.

Returns

The arguments args... with their value types changed to a common type that is a subtype of BaseType.

source
BasicTypes.sa_type Method
julia
sa_type(DT::DataType, N::Union{Int, TypeVar}; unwrap = T -> false)

This is a helper function that simplifies creating concrete StructArray types for types within struct definitions.

Arguments

  • DT::DataType: The type of the struct to create the StructArray for.

  • N::Union{Int, TypeVar}: Specifies the dimensions of the array stored within the resulting StructArray type

Examples

julia
struct ASD{G}
    a::sa_type(Complex{G}, 3)
end

is equivalent to

julia
struct ASD{G}
    a::StructArray{Complex{G}, 3, @NamedTuple{re::Array{G, 3}, im::Array{G, 3}}, Int64}
end

Note

This function is defined inside an extension and is thus available only conditionally to the StructArrays package being explicitly imported

Extended Help

The function supports unwrapping like in the StructArray constructor by providing the appropriate function as the unwrap keyword argument.

It also supports a TypeVar as second argument instead of simply an Int. This is useful for creating complex composite types like in the example below.

julia
@kwdef struct InnerField
    a::Float64 = rand()
    b::Complex{Float64} = rand(ComplexF64)
end

@kwdef struct CompositeStruct
    inner::InnerField = InnerField()
    int::Int = rand(1:10)
end

struct SAField{N}
    sa::sa_type(CompositeStruct, N; unwrap=T -> (T <: InnerField))
end

saf = SAField(StructArray([CompositeStruct() for i in 1:3, j in 1:2]; unwrap = T -> (T <: InnerField)))

where the SAField type has a fully concrete type for it's field sa which would be quite complex to specify manually

source
BasicTypes.stripdeg Method
julia
stripdeg(x::Deg)

Strip the units from the provided value (expected to be a Unitful.Quantity in degrees) and convert it to radians.

The asdeg function performs the inverse operation.

julia
julia> using BasicTypes

julia> stripdeg(180.0°)
3.141592653589793
source
BasicTypes.terminal_logger Method
julia
terminal_logger()

Returns the global TerminalLogger to be used for logging progress bars via ProgressLogging.jl in the REPL.

source
BasicTypes.to_degrees Method
julia
to_degrees(x::ValidAngle)
to_degrees(x::ValidAngle, rounding::RoundingMode)
to_degrees(rounding::RoundingMode)

Take one scalar valid angle and convert it to floating point Unitful quantities with degree (°) units.

Note

The input angles provided as unitless numbers are treated as degrees.

The 2-arg method can be used to also wrap (using rem) the angle provided as first argument using the rounding mode specified as second argument.

The last method taking a single RoundingMode argument is equivalent to Base.Fix2(to_degrees, rounding).

See also: to_radians, enforce_unit

source
BasicTypes.to_length Method
julia
to_length(unit::LengthUnit, x::ValidDistance)
to_length(unit::LengthUnit)

Warn

This function is deprecated now, consider using the more explicit form enforce_unit(unit, float(x)) (or enforce_unit(unit) ∘ float for the single-argument method) instead.

Take one scalar value representing a length and convert it to floating point Unitful quantities with the specified LengthUnit unit.

The single-argument method taking a single LengthUnit argument is equivalent to Base.Fix1(to_length, unit).

See also: to_meters, to_radians, to_degrees

source
BasicTypes.to_meters Method
julia
to_meters(x::ValidDistance)

Warn

This function is deprecated now, use directly the new signature enforce_unit(u"m", x) instead.

Take one scalar value representing a length and convert it to floating point Unitful quantities with the m unit.

See also: to_length, to_radians, to_degrees

source
BasicTypes.to_radians Method
julia
to_radians(x::ValidAngle)
to_radians(x::ValidAngle, rounding::RoundingMode)
to_radians(rounding::RoundingMode)

Take one scalar value representing an angle and convert it to floating point Unitful quantities with radian (rad) units.

Note

The input angles provided as unitless numbers are treated as degrees.

The 2-arg method can be used to also wrap (using rem) the angle provided as first argument using the rounding mode specified as second argument.

The last method taking a single RoundingMode argument is equivalent to Base.Fix2(to_radians, rounding).

See also: to_degrees, enforce_unit

source
BasicTypes.unwrap_optional Method
julia
unwrap_optional(::Type)

Function used to unwrap the type T from Optional{T}. If the provided type is not of the form Optional{T}, it simply returns it unchanged.

Note

When calling this function with simply Optional as input, the function throws an error.

julia
julia> using BasicTypes: BasicTypes, unwrap_optional, Optional

julia> unwrap_optional(Optional{Float32})
Float32

julia> unwrap_optional(Float64)
Float64
source
BasicTypes.valuetype Function
julia
valuetype(x)

Return the type of the underlying value contained in x.

For primitive types like Number, this is the type of x itself. For container types like AbstractArray{T}, this is T.

source
BasicTypes.@add_kwargs_defaults Macro
julia
@add_kwargs_defaults [defaults_variable_name] function_definition

This macro is a helper macro to add keyword arguments defaults to a function definition, useful when multiple functions need to share the same keyword arguments defaults and one wants to define them only once within the codebase.

By explicitly defining each keyword argument (rather than relying on the catchall kwargs...) the user of the function can have autocomplete functionality also for keyword arguments in the REPL.

This macro will simply cycle through the keyword arguments parsed from the function definition and add defaults to any of the kwargs that do not have a specified default value within the signature. It will only add defaults for kwargs that have a default specified in the NamedTuple object reachable within the caller module's scope with the variable name provided as the optional first argument of the macro.

If a custom name is not provided, the macro will look for default assignments in a variable named DEFAULT_KWARGS.

The macro will return the modified function definition.

See the @define_kwargs_defaults macro for a convenience way of defining the kwargs defaults within a module.

source
BasicTypes.@define_kwargs_defaults Macro
julia
@define_kwargs_defaults [defaults_variable_name] begin
    kw1 = default_value1
    kw2 = default_value2
    ...
end

This macro is a helper macro to define keyword arguments defaults to be used in conjuction with the @add_kwargs_defaults macro.

Its main argument is a begin...end block that will define the keyword arguments defaults in the form defined in the signature and will assign these defaults to a const NamedTuple variable in the caller module's scope.

If only the begin...end block is provided, the macro will assign the resulting NamedTuple to a const variable named DEFAULT_KWARGS. Alternatively, a custom variable name can be provided as the first argument of the macro.

Note

The default values to the RHS of each expression in the begin...end block are simply stored as parsed by the macro, so for any non-literal value, the resulting expression will be stored in the NamedTuple.

Example

julia
module TestKwargs
using BasicTypes

@define_kwargs_defaults begin
    boresight = true
    check_blocking = false
end

@add_kwargs_defaults f(; boresight, check_blocking) = return boresight, check_blocking
@add_kwargs_defaults g(; boresight, check_blocking = 3) = return boresight, check_blocking
end

TestKwargs.f() === (true, false)
TestKwargs.g() === (true, 3)
source
BasicTypes.@fallback Macro
julia
@fallback(x...)

Short-circuiting version of fallback.

Examples

julia> x = NotProvided()
julia> y = NotSimulated()
julia> z = 1.0
julia> @fallback x, y, z
1.0
source