package
1.2.12
Repository: https://github.com/cpmech/gosl.git
Documentation: pkg.go.dev

# README

Gosl. utl. Utilities. Lists. Dictionaries. Simple Numerics

Go Reference

This package implements functions for simplifying numeric calculations such as finding the maximum and minimum of lists (i.e. slices), allocation of deep structures such as slices of slices, and generation of arrays. It also contains functions for sorting quantities and updating dictionaries (i.e. maps).

This package does not aim for high performance linear algebra computations. For that purpose, we have the la package. Nonetheless, utl package is OK for small computations such as for vectors in the 3D space. It also tries to use the best algorithms for sorting that are implemented in the standard Go library and others.

Example of what the functions here can do:

  • Generate lists of integers
  • Generate lists of float64s
  • Cumulative sums
  • Handling tables of float64s
  • Pareto fronts
  • Slices and deep (nested) slices up to the 4th depth
  • Allocate deep slices
  • Serialization of deep slices
  • Sorting
  • Maps and dictionaries
  • Append to maps of slices of float64
  • Find the best square for given size = numberOfRows * numberOfColumns
  • ...

API

Please see the documentation here

# Functions

AllFalse returns true if all values are false.
Alloc allocates a slice of slices of float64.
AllTrue returns true if all values are true.
ArgMinMax finds the indices of min and max arguments.
BestSquare finds the best square for given size=Nrows * Ncolumns.
BestSquareApprox finds the best square for given size=Nrows * Ncolumns.
BuildQuadruples initialize Quadruples with i, x, y, and z Note: i, x, y, or z can be nil; but at least one of them must be non nil.
Clone allocates and clones a matrix of float64.
Cross3d computes the cross product of two 3D vectors u and w w = u cross v Note: w must be pre-allocated.
CumSum returns the cumulative sum of the elements in p Input: p -- values Output: cs -- cumulated sum; pre-allocated with len(cs) == len(p).
Deep2checkSize checks if dimensions of Deep2 slice are correct.
Deep2transpose returns the transpose of a deep2 slice.
Deep3alloc allocates a slice of slice of slice.
Deep3checkSize checks if dimensions of Deep3 slice are correct.
Deep3GetInfo returns information of serialized array of array of array.
Deep3set sets deep slice of slice of slice with v values.
Deep4alloc allocates a slice of slice of slice of slice.
Deep4set sets deep slice of slice of slice of slice with v values.
DeserializeDeep2 converts a column-major array to a matrix.
DeserializeDeep3 deserializes an array of array of array in column-compressed format.
Digits returns the nubmer of digits.
Dot3d returns the dot product between two 3D vectors.
DurSum sums all seconds in v NOTE: this is not efficient and should be used for small slices only.
Expon returns the exponent.
Fill fills a slice of float64.
FlipCoin generates a Bernoulli variable; throw a coin with probability p.
FromFloat64s returns a new slice of int from a slice of float64.
FromInts returns a new slice of float64 from a slice of ints.
FromString splits a string with numbers separeted by spaces into float64.
FromStrings converts a slice of strings to a slice of float64.
GetColumn returns the column of a matrix of float64.
GetCopy gets a copy of slice of float64.
GetITout returns indices and output times Input: all_output_times -- array with all output times.
GetMapped returns a new slice such that: Y[i] = filter(X[i]).
GetMapped2 returns a new slice of slice such that: Y[i][j] = filter(X[i][j]) NOTE: each row in X may have different number of columns; i.e.
GetReversed return a copy with reversed items.
GetSorted returns a sorted (increasing) copy of 'A'.
GetStrides returns nReq indices from 0 (inclusive) to nTotal (inclusive) Input: nTotal -- total number of intices nReq -- required indices Example: GetStrides(2001, 5) => [0 400 800 1200 1600 2000 2001] NOTE: GetStrides will always include nTotal as the last item in I .
GtePenalty implements a 'greater than or equal' penalty function where x must be greater than b or equal to be; otherwise the error is magnified.
GtPenalty implements a 'greater than' penalty function where x must be greater than b; otherwise the error is magnified.
Iabs performs the absolute operation with ints.
Imax returns the maximum between two integers.
Imin returns the minimum between two integers.
IntAddScalar adds a scalar to all values in a slice of integers.
IntAlloc allocates a matrix of integers.
IntBoolMapSort returns sorted keys of map[int]bool.
IntClone allocates and clones a matrix of integers.
IntCopy returns a copy of slice of ints.
IntFill fills a slice of integers.
IntFilter filters out components in slice NOTE: this function is not efficient and should be used with small slices only.
IntGetSorted returns a sorted (increasing) copy of 'A'.
IntIndexSmall finds the index of an item in a slice of ints NOTE: this function is not efficient and should be used with small slices only; say smaller than 20.
IntIntsMapAppend appends a new item to a map of slice.
IntMinMax returns the maximum and minimum elements in v NOTE: this is not efficient and should be used for small slices only.
IntNegOut filters out negative components in slice NOTE: this function is not efficient and should be used with small slices only.
IntPy returns a Python string representing a slice of integers.
IntRange generates a slice of integers from 0 to n-1.
IntRange2 generates slice of integers from start to stop (but not stop).
IntRange3 generates a slice of integers from start to stop (but not stop), afer each 'step'.
IntSort3 sorts 3 values in ascending order.
IntSort4 sort four values in ascending order.
IntUnique returns a unique and sorted slice of integers.
IntVals allocates a slice of integers with size==n, filled with val.
IsPowerOfTwo checks if n is power of 2; i.e.
L2norm returns the Euclidean distance between p and q.
LinSpace returns evenly spaced numbers over a specified closed interval.
LinSpaceOpen returns evenly spaced numbers over a specified open interval.
Max returns the maximum between two float point numbers.
MeshGrid2d creates a grid with x-y coordinates X, Y -- [ny][nx].
MeshGrid2dF creates a grid with x-y coordinates and evaluates z=f(x,y) X, Y, Z -- [ny][nx].
MeshGrid2dFG creates a grid with x-y coordinates and evaluates (z,u,v)=fg(x,y) X, Y, Z, U, V -- [ny][nx].
MeshGrid2dV creates a grid with x-y coordinates given x and y values X, Y -- [len(yVals)][len(xVals)].
Min returns the minimum between two float point numbers.
MinMax returns the maximum and minimum elements in v NOTE: this is not efficient and should be used for small slices only.
NewOutputter creates a new Outputter dt -- time step dtOut -- time step for output tmax -- final time (of simulation) outFcn -- callback function to perform output (may be nil) NOTE: a first output will be processed if outFcn != nil.
NewParams returns a set of parameters This is an alternative to initializing Params by setting slice items A set of Params can be initialized as follows: params := NewParams( &P{N: "P1", V: 1}, &P{N: "P2", V: 2}, &P{N: "P3", V: 3}, ) Alternatively, you may set slice components directly (see Params definition) .
NonlinSpace generates N points such that the ratio between the last segment (or the middle segment) to the first one is equal to a given constant R.
Ones generates a slice of float64 with ones.
ParetoFront computes the Pareto optimal front Input: Ovs -- [nsamples][ndim] objective values Output: front -- indices of pareto front Note: this function is slow for large sets.
ParetoMin compares two vectors using Pareto's optimal criterion Note: minimum dominates (is better).
ParetoMinProb compares two vectors using Pareto's optimal criterion φ ∃ [0,1] is a scaling factor that helps v win even if it's not smaller.
PrintDeep3 prints an array of array of array.
PrintDeep4 prints an array of array of array.
PrintMemStat prints memory statistics.
ProbContestSmall computes the probability for a contest between u and v where u wins if it's the smaller value.
Prof runs either CPU profiling or MEM profiling INPUT: mem -- memory profiling instead of CPU profiling silent -- hide messages OUTPUT: returns a "stop()" function to be called before exiting output files are saved to "/tmp/gosl/cpu.pprof"; or "/tmp/gosl/mem.pprof" Run analysis with: go tool pprof <binary-goes-here> /tmp/gosl/cpu.pprof or go tool pprof <binary-goes-here> /tmp/gosl/mem.pprof Example of use (notice the last parentheses): func main() { defer utl.Prof(false, false)() ..
ProfCPU activates CPU profiling OUTPUT: returns a "stop()" function to be called before exiting Example of use (notice the last parentheses): func main() { defer ProfCPU("/tmp", "cpu.pprof", true)() ..
ProfMEM activates memory profiling OUTPUT: returns a "stop()" function to be called before exiting Example of use (notice the last parentheses): func main() { defer ProfMEM("/tmp", "mem.pprof", true)() ..
Qsort sort an array arr[0..n-1] into ascending numerical order using the Quicksort algorithm.
Qsort2 sorts an array arr[0..n-1] into ascending order using Quicksort, while making the corresponding rearrangment of the array brr[0..n-1].
Scaling computes a scaled version of the input slice with results in [0.0, 1.0] Input: x -- values ds -- δs value to be added to all 's' values tol -- tolerance for capturing xmax ≅ xmin reverse -- compute reverse series; i.e.
SerializeDeep2 converts a matrix into a column-major array.
SerializeDeep3 serializes an array of array of array in column-compressed format.
Sort3 sorts 3 values in ascending order.
Sort3Desc sorts 3 values in descending order.
Sort4 sort four values in ascending order.
SortQuadruples sorts i, x, y, and z by "i", "x", "y", or "z" Note: either i, x, y, or z can be nil; i.e.
StrAlloc allocates a matrix of strings.
StrBoolMapSort returns sorted keys of map[string]bool.
StrBoolMapSortSplit returns sorted keys of map[string]bool and sorted values.
StrFltMapSort returns sorted keys of map[string]float64.
StrFltMapSortSplit returns sorted keys of map[string]float64 and sorted values.
StrFltsMapAppend appends a new item to a map of slice.
StrIndexSmall finds the index of an item in a slice of strings NOTE: this function is not efficient and should be used with small slices only; say smaller than 20.
StrIntMapSort returns sorted keys of map[string]int.
StrIntMapSortSplit returns sorted keys of map[string]int and sorted values.
StrIntsMapAppend appends a new item to a map of slice.
StrVals allocates a slice of strings with size==n, filled with val.
Sum sums all items in v NOTE: this is not efficient and should be used for small slices only.
Swap swaps two float64 numbers.
ToStrings converts a slice of float64 to a slice of strings.
Vals generates a slice of float64 filled with v.

# Constants

SQ2 = sqrt(2) [https://oeis.org/A002193].
SQ3 = sqrt(3) [https://oeis.org/A002194].
SQ5 = sqrt(5) [https://oeis.org/A002163].
SQ6 = sqrt(6) [https://oeis.org/A010464].
SQ7 = sqrt(7) [https://oeis.org/A010465].
SQ8 = sqrt(8) [https://oeis.org/A010466].

# Structs

List implements a tabular list with variable number of columns Example: Vals = [][]float64{ {0.0}, {1.0, 1.1, 1.2, 1.3}, {2.0, 2.1}, {3.0, 3.1, 3.2}, }.
Observable indicates that an object is observable; i.e.
Outputter helps with the output of (numerical) results The time loop can be something like: t := 0.0 for tidx := 0; tidx < outper.Nsteps; tidx++ { t += outper.Dt ..
P holds numeric parameters defined by a name N and a value V.
Quadruple helps to sort a quadruple of 1 int and 3 float64s.
QuadruplesByI defines struct to sort Quadruples by I.
QuadruplesByX defines struct to sort Quadruples by X.
QuadruplesByY Sort Quadruples by Y.
QuadruplesByZ defines struct to Sort Quadruples by Z.
SerialList implements a tabular list with variable number of columns using a serial representation Example: 0.0 1.0 1.1 1.2 1.3 2.0 2.1 3.0 3.1 3.2 becomes: (0) (1) 2 3 4 (5) 6 (7) 8 9 (10) Vals = 0.0 | 1.0 1.1 1.2 1.3 | 2.0 2.1 | 3.0 3.1 3.2 | Ptrs = 0 1 5 7 10 Notes: len(Ptrs) = nrows + 1 Ptrs[len(Ptrs)-1] = len(Vals).
Sorter builds an index list to sort arrays of any type.

# Interfaces

Observer is an interface to objects that need to observe something.

# Type aliases

OutFcnType is a function that sets the "u" array with an output @ time "t".
Params holds many parameters A set of Params can be initialized as follows: var params Params params = []*P{ {N: "klx", V: 1.0}, {N: "kly", V: 2.0}, {N: "klz", V: 3.0}, } Alternatively, see NewParams function .
Quadruples helps to sort quadruples.