BasicTypes.jl
Documentation for BasicTypes.jl
.
BasicTypes.Optional Type
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.
BasicTypes.Point Type
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}}}
BasicTypes.ValidAngle Type
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.
BasicTypes.ValidDistance Type
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.
sourceBasicTypes.EmptyIterator Type
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.
BasicTypes.ExtraOutput Type
ExtraOutput
Singleton type used for dispatch, and specifically to create function methods that return more than one output.
sourceBasicTypes.NoTrait Type
struct NoTrait end
Singleton type used to indicate that a trait is not implemented, resorting the eventual default behavior.
sourceBasicTypes.NotProvided Type
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.
BasicTypes.NotSimulated Type
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
).
BasicTypes.PropertyOrNothing Type
PropertyOrNothing{name}
Singleton structure that can be used as a functor of the form:
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
.
BasicTypes.SkipChecks Type
struct SkipChecks end
Singleton type used for dispatch to indicate that a certain check should be skipped.
sourceBasicTypes.asdeg Method
asdeg(x::Real)
Convert the provided value assumed to be in radians to Unitful degrees.
The stripdeg
function performs the inverse operation.
julia> using BasicTypes
julia> asdeg(π)
180.0°
BasicTypes.basetype Method
basetype(t)
Returns the type of t
, removing type parameters if for parametric types (thus returning the more generic UnionAll type for typeof(t)
)
basetype(rand(Complex{Float64})) === Complex
BasicTypes.change_valuetype Function
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
.
BasicTypes.common_valuetype Function
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 ofBaseType
.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
.
BasicTypes.constructor_without_checks Function
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
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
BasicTypes.enforce_unit Method
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 convertvalue
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 aQuantity
with the providedreference
unit.
Examples
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
BasicTypes.enforce_unitless Method
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> 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
BasicTypes.fallback Function
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
BasicTypes.getproperty_oftype Function
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> 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"
BasicTypes.isnotset Method
isnotset(x)
Return true
if x
is not set to a value. (That is, x
is either NotProvided
or NotSimulated
)
BasicTypes.isprovided Method
isprovided(x) -> Bool
Check if the value x
is not of type NotProvided
. Returns true
if x
is provided, otherwise false
.
BasicTypes.issimulated Method
issimulated(x) -> Bool
Check if x
is simulated by verifying its type is not NotSimulated
. Returns true
if x
is simulated, false
otherwise.
BasicTypes.progress_logger Method
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.
sourceBasicTypes.promote_valuetype Function
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 ofBaseType
.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
.
BasicTypes.sa_type Method
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 theStructArray
for.N::Union{Int, TypeVar}
: Specifies the dimensions of the array stored within the resultingStructArray
type
Examples
struct ASD{G}
a::sa_type(Complex{G}, 3)
end
is equivalent to
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.
@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
BasicTypes.stripdeg Method
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> using BasicTypes
julia> stripdeg(180.0°)
3.141592653589793
BasicTypes.terminal_logger Method
terminal_logger()
Returns the global TerminalLogger
to be used for logging progress bars via ProgressLogging.jl
in the REPL.
BasicTypes.to_degrees Method
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
BasicTypes.to_length Method
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
BasicTypes.to_meters Method
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
BasicTypes.to_radians Method
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
BasicTypes.unwrap_optional Method
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> using BasicTypes: BasicTypes, unwrap_optional, Optional
julia> unwrap_optional(Optional{Float32})
Float32
julia> unwrap_optional(Float64)
Float64
BasicTypes.valuetype Function
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
.
BasicTypes.@add_kwargs_defaults Macro
@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.
BasicTypes.@define_kwargs_defaults Macro
@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
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)
BasicTypes.@fallback Macro
@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