Documentation ¶
Overview ¶
Package utils contains all utility functions that currently have no better home than here. Consider moving them to go.viam.com/utils.
Index ¶
- Constants
- Variables
- func AbsInt(n int) int
- func AbsInt64(n int64) int64
- func AngleDiffDeg(a1, a2 float64) float64
- func AntiCWDeg(deg float64) float64
- func AssertType[T any](from interface{}) (T, error)
- func BytesFromFloat32BE(v float32) []byte
- func BytesFromFloat32LE(v float32) []byte
- func BytesFromFloat64BE(v float64) []byte
- func BytesFromFloat64LE(v float64) []byte
- func BytesFromUint32BE(v uint32) []byte
- func BytesFromUint32LE(v uint32) []byte
- func CheckLazyMIMEType(mimeType string) (string, bool)
- func Clamp(value, min, max float64) float64
- func ComputeDistance(p1, p2 []float64, distType DistanceType) (float64, error)
- func CubeRoot(x float64) float64
- func CycleIntSliceByN(s []int, n int) []int
- func DegToRad(degrees float64) float64
- func ErrInvalidName(name string) error
- func EuclideanDistance(p1, p2 []float64) (float64, error)
- func Float32FromBytesBE(bytes []byte) float32
- func Float32FromBytesLE(bytes []byte) float32
- func Float64AlmostEqual(a, b, epsilon float64) bool
- func Float64FromBytesBE(bytes []byte) float64
- func Float64FromBytesLE(bytes []byte) float64
- func FlushChan[T any](c chan T)
- func GetArgMinDistancesPerRow(distances *mat.Dense) []int
- func GetArgMinDistancesPerRowInt(distances [][]int) []int
- func GetDeviceInfo(modelName string) (utils.StringSet, error)
- func GetInParallel(ctx context.Context, fs []FloatFunc) (time.Duration, []float64, error)
- func GetResourceConfigurationTimeout(logger golog.Logger) time.Duration
- func GroupWorkParallel(ctx context.Context, totalSize int, before BeforeParallelGroupWorkFunc, ...) error
- func HammingDistance(p1, p2 []float64) (float64, error)
- func Int16FromBytesBE(bytes []byte) int16
- func Int16FromBytesLE(bytes []byte) int16
- func IsTrustedEnvironment(ctx context.Context) bool
- func MaxInt(a, b int) int
- func MaxUint8(a, b uint8) uint8
- func Median(values ...float64) float64
- func MinInt(a, b int) int
- func MinUint8(a, b uint8) uint8
- func ModAngDeg(ang float64) float64
- func NewFilePathDebugLogger(filepath, name string) (*zap.SugaredLogger, error)
- func NewRemoteResourceClashError(name string) error
- func NewUnexpectedTypeError[ExpectedT any](actual interface{}) error
- func PairwiseDistance(pts1, pts2 [][]float64, distType DistanceType) (*mat.Dense, error)
- func ParallelForEachPixel(size image.Point, f func(x, y int))
- func RadToDeg(radians float64) float64
- func RemoveFileNoError(path string)
- func ResolveFile(fn string) string
- func RunInParallel(ctx context.Context, fs []SimpleFunc) (time.Duration, error)
- func SampleNIntegersNormal(n int, vMin, vMax float64) []int
- func SampleNIntegersUniform(n int, vMin, vMax float64) []int
- func SampleNRegularlySpaced(n int, vMin, vMax float64) []int
- func SampleRandomIntRange(min, max int, r *rand.Rand) int
- func ScaleByPct(n int, pct float64) int
- func SelectNIndicesWithoutReplacement(nSamples, nMax int) ([]int, error)
- func Single(dim int, x []float64) [][]float64
- func Square(n float64) float64
- func SquareInt(n int) int
- func SubFor(sub []int, idx int, dims []int) []int
- func Transpose(slice [][]int) [][]int
- func TypeStr[T any]() string
- func Uint32FromBytesBE(bytes []byte) uint32
- func Uint32FromBytesLE(bytes []byte) uint32
- func ValidateBaudRate(validBaudRates []uint, baudRate int) bool
- func Walk(middleX, middleY, maxRadius int, f WalkCallback) error
- func WithLazyMIMEType(mimeType string) string
- func WithTrustedEnvironment(ctx context.Context, trusted bool) (context.Context, error)
- type AttributeMap
- func (am AttributeMap) Bool(name string, def bool) bool
- func (am AttributeMap) BoolSlice(name string, def bool) []bool
- func (am AttributeMap) Float64(name string, def float64) float64
- func (am AttributeMap) Float64Slice(name string) []float64
- func (am AttributeMap) Has(name string) bool
- func (am AttributeMap) Int(name string, def int) int
- func (am AttributeMap) IntSlice(name string) []int
- func (am AttributeMap) String(name string) string
- func (am AttributeMap) StringSlice(name string) []string
- func (am AttributeMap) Walk(visitor Visitor) (interface{}, error)
- type BeforeParallelGroupWorkFunc
- type CLFBaseMessage
- type CLFMessage
- type CLFMessageType
- type CLFOdometryMessage
- type CLFOldLaserMessage
- type CLFParamMessage
- type CLFReader
- type DistanceType
- type FloatFunc
- type GroupWorkDoneFunc
- type GroupWorkFunc
- type MemberWorkFunc
- type RollingAverage
- type SimpleFunc
- type TypedName
- type Vec2Fs
- type Vec2Matrix
- type Visitor
- type WalkCallback
- type Walker
Constants ¶
const ( // CredentialsTypeRobotSecret is for credentials used against the cloud managing this robot. CredentialsTypeRobotSecret = "robot-secret" // CredentialsTypeRobotLocationSecret is for credentials used against the cloud managing this robot's location. CredentialsTypeRobotLocationSecret = "robot-location-secret" )
const ( CLFMessageTypeParam = CLFMessageType("PARAM") CLFMessageTypeComment = CLFMessageType("COMMENT") CLFMessageTypeSync = CLFMessageType("SYNC") CLFMessageTypeOdometry = CLFMessageType("ODOM") CLFMessageTypeTruePos = CLFMessageType("TRUEPOS") CLFMessageTypeRawLaser1 = CLFMessageType("RAWLASER1") CLFMessageTypeRawLaser2 = CLFMessageType("RAWLASER2") CLFMessageTypeRawLaser3 = CLFMessageType("RAWLASER3") CLFMessageTypeRawLaser4 = CLFMessageType("RAWLASER4") CLFMessageTypePositionLaser = CLFMessageType("POSITIONLASER") CLFMessageTypeRobotLaser1 = CLFMessageType("ROBOTLASER1") CLFMessageTypeRobotLaser2 = CLFMessageType("ROBOTLASER2") CLFMessageTypeNMEAGGA = CLFMessageType("NMEAGGA") CLFMessageTypeNMEARMC = CLFMessageType("NMEARMC") CLFMessageTypeSonar = CLFMessageType("SONAR") CLFMessageTypeBumper = CLFMessageType("BUMPER") CLFMessageTypeScanMark = CLFMessageType("SCANMARK") CLFMessageTypeIMU = CLFMessageType("IMU") CLFMessageTypeVectorMove = CLFMessageType("VECTORMOVE") CLFMessageTypeRobotVelocity = CLFMessageType("ROBOTVELOCITY") CLFMessageTypeFollowTrajectory = CLFMessageType("FOLLOWTRAJECTORY") CLFMessageTypeBaseVelocity = CLFMessageType("BASEVELOCITY") CLFMessageTypeOld = CLFMessageType("OLD") CLFMessageTypeFrontLaser = CLFMessageType("FLASER") CLFMessageTypeRearLaser = CLFMessageType("RLASER") CLFMessageTypeLaser3 = CLFMessageType("LASER3") CLFMessageTypeLaser4 = CLFMessageType("LASER4") CLFMessageTypeRemissionFLaser = CLFMessageType("REMISSIONFLASER") CLFMessageTypeRemissionRLaser = CLFMessageType("REMISSIONRLASER") CLFMessageTypeRemissionLaser3 = CLFMessageType("REMISSIONLASER3") CLFMessageTypeRemissionLaser4 = CLFMessageType("REMISSIONLASER4") )
known message types.
const ( // DefaultResourceConfigurationTimeout is the default resource configuration // timeout. DefaultResourceConfigurationTimeout = time.Minute // ResourceConfigurationTimeoutEnvVar is the environment variable that can // be set to override defaultResourceConfigurationTimeout as the duration // that resources and modules are allowed to (re)configure and startup // respectively. ResourceConfigurationTimeoutEnvVar = "VIAM_RESOURCE_CONFIGURATION_TIMEOUT" )
const ( // MimeTypeSuffixLazy is used to indicate a lazy loading of data. MimeTypeSuffixLazy = "lazy" // MimeTypeRawRGBA is for go's internal image.NRGBA. This uses the custom header as // explained in the comments for rimage.DecodeImage and rimage.EncodeImage. MimeTypeRawRGBA = "image/vnd.viam.rgba" // MimeTypeRawRGBALazy is a lazy MimeTypeRawRGBA. MimeTypeRawRGBALazy = MimeTypeRawRGBA + "+" + MimeTypeSuffixLazy // MimeTypeRawDepth is for depth images. MimeTypeRawDepth = "image/vnd.viam.dep" // MimeTypeJPEG is regular jpgs. MimeTypeJPEG = "image/jpeg" // MimeTypePNG is regular pngs. MimeTypePNG = "image/png" // MimeTypePCD is for .pcd pountcloud files. MimeTypePCD = "pointcloud/pcd" // MimeTypeQOI is for .qoi "Quite OK Image" for lossless, fast encoding/decoding. MimeTypeQOI = "image/qoi" // MimeTypeTabular used to indicate tabular data, this is used mainly for filtering data. MimeTypeTabular = "x-application/tabular" // MimeTypeDefault used if mimetype cannot be inferred. MimeTypeDefault = "application/octet-stream" )
Variables ¶
var ParallelFactor = runtime.GOMAXPROCS(0)
ParallelFactor controls the max level of parallelization. This might be useful to set in tests where too much parallelism actually slows tests down in aggregate.
var ValidNameRegex = regexp.MustCompile(`^[a-zA-Z][-\w]*$`)
ValidNameRegex is the pattern that matches to a valid name. The name must begin with a letter i.e. [a-zA-Z], and the body can only contain 0 or more numbers, letters, dashes and underscores i.e. [-\w]*.
Functions ¶
func AngleDiffDeg ¶
AngleDiffDeg returns the closest difference from the two given angles. The arguments are commutative.
func AntiCWDeg ¶
AntiCWDeg flips the given degrees as if you were to start at 0 and go counter-clockwise or vice versa.
func AssertType ¶ added in v0.2.36
AssertType attempts to assert that the given interface argument is the given type parameter.
func BytesFromFloat32BE ¶
BytesFromFloat32BE converts a float32 to an array of bytes ordered in big-endian.
func BytesFromFloat32LE ¶
BytesFromFloat32LE converts a float32 to an array of bytes ordered in little-endian.
func BytesFromFloat64BE ¶
BytesFromFloat64BE converts a float64 to an array of bytes ordered in big-endian.
func BytesFromFloat64LE ¶
BytesFromFloat64LE converts a float64 to an array of bytes ordered in little-endian.
func BytesFromUint32BE ¶
BytesFromUint32BE converts a uint32 to an array of bytes ordered in big-endian.
func BytesFromUint32LE ¶
BytesFromUint32LE converts a uint32 to an array of bytes ordered in little-endian.
func CheckLazyMIMEType ¶ added in v0.0.8
CheckLazyMIMEType checks the lazy suffix of a MIME.
func Clamp ¶
Clamp returns min if value is lesser than min, max if value is greater them max or value if the input value is between min and max.
func ComputeDistance ¶
func ComputeDistance(p1, p2 []float64, distType DistanceType) (float64, error)
ComputeDistance computes the distance between two vectors stored in a slice of floats.
func CycleIntSliceByN ¶
CycleIntSliceByN cycles the list to the right by n steps.
func ErrInvalidName ¶ added in v0.2.36
ErrInvalidName returns a human-readable error for when ValidNameRegex doesn't match.
func EuclideanDistance ¶
EuclideanDistance computes the euclidean distance between 2 vectors.
func Float32FromBytesBE ¶
Float32FromBytesBE converts an array of byte ordered in big-endian to a float32.
func Float32FromBytesLE ¶
Float32FromBytesLE converts an array of byte ordered in little-endian to a float32.
func Float64AlmostEqual ¶
Float64AlmostEqual compares two float64s and returns if the difference between them is less than epsilon.
func Float64FromBytesBE ¶
Float64FromBytesBE converts an array of byte ordered in big-endian to a float64.
func Float64FromBytesLE ¶
Float64FromBytesLE converts an array of byte ordered in little-endian to a float64.
func FlushChan ¶ added in v0.9.0
func FlushChan[T any](c chan T)
FlushChan is a function that takes a generic chanel and completely empties it.
func GetArgMinDistancesPerRow ¶
GetArgMinDistancesPerRow returns in a slice of int the index of the point with minimum distance for each row.
func GetArgMinDistancesPerRowInt ¶ added in v0.0.9
GetArgMinDistancesPerRowInt returns in a slice of int the index of the point with minimum distance for each row.
func GetDeviceInfo ¶ added in v0.2.47
GetDeviceInfo returns the device information in stringset.
func GetInParallel ¶ added in v0.8.0
GetInParallel runs all functions in parallel, return is elapsed time, a list of floats, and an error.
func GetResourceConfigurationTimeout ¶ added in v0.5.1
GetResourceConfigurationTimeout calculates the resource configuration timeout (env variable value if set, defaultResourceConfigurationTimeout otherwise).
func GroupWorkParallel ¶
func GroupWorkParallel(ctx context.Context, totalSize int, before BeforeParallelGroupWorkFunc, groupWork GroupWorkFunc) error
GroupWorkParallel parallelizes the given size of work over multiple workers.
func HammingDistance ¶
HammingDistance computes the hamming distance between two vectors that only contain zeros and ones.
func Int16FromBytesBE ¶ added in v0.2.5
Int16FromBytesBE converts an array of bytes ordered in big-endian to a (signed) int16.
func Int16FromBytesLE ¶ added in v0.2.5
Int16FromBytesLE converts an array of bytes ordered in little-endian to a (signed) int16.
func IsTrustedEnvironment ¶ added in v0.2.36
IsTrustedEnvironment is used to check the trusted state of the runtime. Note: by default, if no context is set up, trust is assumed; be careful.
func Median ¶
Median returns the median value of the given values. If there are no values, NaN is returned.
func NewFilePathDebugLogger ¶ added in v0.10.0
func NewFilePathDebugLogger(filepath, name string) (*zap.SugaredLogger, error)
NewFilePathDebugLogger is intended as a debug only tool & should not be used in prod logs using debug configuration to log to both stderr, stdout & a filepath.
func NewRemoteResourceClashError ¶
NewRemoteResourceClashError is used when you are more than one resource with the same name exist.
func NewUnexpectedTypeError ¶
NewUnexpectedTypeError is used when there is a type mismatch.
func PairwiseDistance ¶
func PairwiseDistance(pts1, pts2 [][]float64, distType DistanceType) (*mat.Dense, error)
PairwiseDistance computes the pairwise distances between 2 sets of points.
func ParallelForEachPixel ¶
ParallelForEachPixel loops through the image and calls f functions for each [x, y] position. The image is divided into N * N blocks, where N is the number of available processor threads. For each block a parallel Goroutine is started.
func RemoveFileNoError ¶ added in v0.2.47
func RemoveFileNoError(path string)
RemoveFileNoError will remove the file at the given path if it exists. Any errors will be suppressed.
func ResolveFile ¶
ResolveFile returns the path of the given file relative to the root of the codebase. For example, if this file currently lives in utils/file.go and ./foo/bar/baz is given, then the result is foo/bar/baz. This is helpful when you don't want to relatively refer to files when you're not sure where the caller actually lives in relation to the target file.
func RunInParallel ¶
RunInParallel runs all functions in parallel, return is elapsed time and an error.
func SampleNIntegersNormal ¶
SampleNIntegersNormal samples n integers from normal distribution centered around (vMax+vMin) / 2 and in range [vMin, vMax].
func SampleNIntegersUniform ¶
SampleNIntegersUniform samples n integers uniformly in [vMin, vMax].
func SampleNRegularlySpaced ¶
SampleNRegularlySpaced returns the same set of evenly divided numbers every time, and is mostly used for testing purposes.
func SampleRandomIntRange ¶
SampleRandomIntRange samples a random integer within a range given by [min, max] using the given rand.Rand.
func ScaleByPct ¶
ScaleByPct scales a max number by a floating point percentage between two bounds [0, n].
func SelectNIndicesWithoutReplacement ¶
SelectNIndicesWithoutReplacement select N random indices from [0,nMax] without replacement (no duplicate indices).
func Single ¶
Single generates an n-dimensional Grid using a single set of values. dim specifies the number of dimensions, the entries in x specify the gridded values.
func Square ¶
Square returns the square of the given value. Math.pow( x, 2 ) is slow, this is faster.
func SquareInt ¶
SquareInt returns the square of the given value. Math.pow( x, 2 ) is slow, this is faster.
func SubFor ¶
SubFor constructs the multi-dimensional subscript for the input linear index. dims specify the maximum size in each dimension. If sub is non-nil the result is stored in-place into sub. If it is nil a new slice of the appropriate length is allocated.
func TypeStr ¶ added in v0.2.36
TypeStr returns the a human readable type string of the given value.
func Uint32FromBytesBE ¶
Uint32FromBytesBE converts an array of bytes ordered in big-endian to a uint32.
func Uint32FromBytesLE ¶
Uint32FromBytesLE converts an array of bytes ordered in little-endian to a uint32.
func ValidateBaudRate ¶ added in v0.2.49
ValidateBaudRate validates that the baudrate is in the list of valid values.
func Walk ¶
func Walk(middleX, middleY, maxRadius int, f WalkCallback) error
Walk starts at the given middle point and walks around increasingly bigger squares based on the given radius growing outwards.
func WithLazyMIMEType ¶ added in v0.0.8
WithLazyMIMEType attaches the lazy suffix to a MIME.
Types ¶
type AttributeMap ¶ added in v0.2.36
type AttributeMap map[string]interface{}
An AttributeMap is a convenience wrapper for pulling out typed information from a map.
func (AttributeMap) Bool ¶ added in v0.2.36
func (am AttributeMap) Bool(name string, def bool) bool
Bool attempts to return a boolean present in the map with the given name; returns the given default otherwise.
func (AttributeMap) BoolSlice ¶ added in v0.2.36
func (am AttributeMap) BoolSlice(name string, def bool) []bool
BoolSlice attempts to return a slice of bools present in the map with the given name; returns an empty slice otherwise.
func (AttributeMap) Float64 ¶ added in v0.2.36
func (am AttributeMap) Float64(name string, def float64) float64
Float64 attempts to return a float64 present in the map with the given name; returns the given default otherwise.
func (AttributeMap) Float64Slice ¶ added in v0.2.36
func (am AttributeMap) Float64Slice(name string) []float64
Float64Slice attempts to return a slice of ints present in the map with the given name; returns an empty slice otherwise.
func (AttributeMap) Has ¶ added in v0.2.36
func (am AttributeMap) Has(name string) bool
Has returns whether or not the given name is in the map.
func (AttributeMap) Int ¶ added in v0.2.36
func (am AttributeMap) Int(name string, def int) int
Int attempts to return an integer present in the map with the given name; returns the given default otherwise.
func (AttributeMap) IntSlice ¶ added in v0.2.36
func (am AttributeMap) IntSlice(name string) []int
IntSlice attempts to return a slice of ints present in the map with the given name; returns an empty slice otherwise.
func (AttributeMap) String ¶ added in v0.2.36
func (am AttributeMap) String(name string) string
String attempts to return a string present in the map with the given name; returns an empty string otherwise.
func (AttributeMap) StringSlice ¶ added in v0.2.36
func (am AttributeMap) StringSlice(name string) []string
StringSlice attempts to return a slice of strings present in the map with the given name; returns an empty slice otherwise.
func (AttributeMap) Walk ¶ added in v0.2.36
func (am AttributeMap) Walk(visitor Visitor) (interface{}, error)
Walk implements the Walker interface.
type BeforeParallelGroupWorkFunc ¶
type BeforeParallelGroupWorkFunc func(groupSize int)
BeforeParallelGroupWorkFunc executes before any work starts with the calculated group size.
type CLFBaseMessage ¶
type CLFBaseMessage struct { MessageType CLFMessageType IPCTimestamp float64 IPCHostname string LoggerTimestamp float64 }
CLFBaseMessage is used by all messages and contains basic information about the message.
func (CLFBaseMessage) Base ¶
func (b CLFBaseMessage) Base() CLFBaseMessage
Base returns the base part of the message.
func (CLFBaseMessage) Type ¶
func (b CLFBaseMessage) Type() CLFMessageType
Type returns the type of message this is.
type CLFMessage ¶
type CLFMessage interface { Base() CLFBaseMessage Type() CLFMessageType }
CLFMessage is a specific type of CLF message that always has a base message.
type CLFMessageType ¶
type CLFMessageType string
CLFMessageType describes a specific type of message.
type CLFOdometryMessage ¶
type CLFOdometryMessage struct { CLFMessage X float64 Y float64 Theta float64 TranslationalVelocity float64 RotationalVelocity float64 Acceleration float64 }
CLFOdometryMessage represents odometry data.
type CLFOldLaserMessage ¶
type CLFOldLaserMessage struct { CLFMessage RangeReadings []float64 X float64 Y float64 Theta float64 OdomX float64 OdomY float64 OdomTheta float64 }
CLFOldLaserMessage represents legacy lidar scan data.
type CLFParamMessage ¶
type CLFParamMessage struct { CLFMessage Name, Value string }
CLFParamMessage conveys parameters being set for the whole CLF.
type CLFReader ¶
type CLFReader struct {
// contains filtered or unexported fields
}
A CLFReader can read in CARMEN Logfiles.
func NewCLFReader ¶
NewCLFReader returns a CLF reader based on the given reader.
type DistanceType ¶
type DistanceType int
DistanceType defines the type of distance used in a function.
const ( // Euclidean is DistanceType 0. Euclidean DistanceType = iota // Hamming is DistanceType 1. Hamming )
type GroupWorkDoneFunc ¶
type GroupWorkDoneFunc func()
GroupWorkDoneFunc runs when a single group's work is done; helpful for merge stages.
type GroupWorkFunc ¶
type GroupWorkFunc func(groupNum, groupSize, from, to int) (MemberWorkFunc, GroupWorkDoneFunc)
GroupWorkFunc runs to determine what work members should do, if any.
type MemberWorkFunc ¶
type MemberWorkFunc func(memberNum, workNum int)
MemberWorkFunc runs for each work item (member) of a group.
type RollingAverage ¶
type RollingAverage struct {
// contains filtered or unexported fields
}
RollingAverage computes an average in a moving window of a certain size. It is goroutine-safe but should be used for statistical purposes only due to the use of atomics and not mutexes.
func NewRollingAverage ¶
func NewRollingAverage(windowSize int) *RollingAverage
NewRollingAverage returns a rolling average computed on the given window size.
func (*RollingAverage) Add ¶
func (ra *RollingAverage) Add(x int)
Add adds the given value to the samples.
func (*RollingAverage) Average ¶
func (ra *RollingAverage) Average() int
Average recomputes and returns the current rolling average.
func (*RollingAverage) NumSamples ¶
func (ra *RollingAverage) NumSamples() int
NumSamples returns the number of samples currently collected.
type Vec2Fs ¶
type Vec2Fs [][]float64
Vec2Fs is a series of two dimensional vectors that are float based.
type Vec2Matrix ¶
Vec2Matrix is a wrapper around a mat.Dense intended for a series of 2D vectors.
func (*Vec2Matrix) DistanceMSETo ¶
func (v2m *Vec2Matrix) DistanceMSETo(to *Vec2Matrix) float64
DistanceMSETo returns the mean squared error between this matrix and the given matrix. This is helpful for calculating how "far off" two matrices are.
func (*Vec2Matrix) RotateMatrixAbout ¶
func (v2m *Vec2Matrix) RotateMatrixAbout(x, y, theta float64) *Vec2Matrix
RotateMatrixAbout rotates every vector by the given theta about a given point.
type Visitor ¶ added in v0.2.36
type Visitor interface { // Visit visits a node and returns a new node, with or without modifications. Visit(interface{}) (interface{}, error) }
Visitor defines an interface for visiting and potentially modifying portions of the config.
type WalkCallback ¶
WalkCallback is to be called for each point visited by Walk.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package contextutils provides utilities for dealing with contexts such as adding and retrieving metadata to/from a context, and handling context timeouts.
|
Package contextutils provides utilities for dealing with contexts such as adding and retrieving metadata to/from a context, and handling context timeouts. |