blt::vector(3tcl)
๐ blt::vector โ the vector era ๐
okay bestie, welcome to blt::vector(3tcl), aka the BLT Built-In Commands page about vectors โ the data type that's about to change your whole Tcl life. grab a boba, we're going in ๐งโจ
โจ NAME โจ
vector โ Vector data type for Tcl ๐ฆ
๐ธ SYNOPSIS ๐ธ
vector configure option value ...
vector create vecName ?vecName...? ?switches?
vector destroy vecName ?vecName...?
vector expr expression
vector names ?pattern...?
vector op operation vecName ?arg?...
๐ DESCRIPTION ๐
The vector command creates a vector of floating point values. and the way you can mess with the vector's components? three whole lanes, pick your fave:
- through a Tcl array variable
- through a Tcl command
- through the C API
no cap, all three are valid. ๐
๐ INTRODUCTION ๐
okay so. a vector is literally just an ordered set of numbers. that's it. the components are real numbers, indexed by counting numbers. simple. iconic. ๐
Vectors are common data structures for many applications. like, imagine a graph โ it might use two vectors to represent the X-Y coordinates of the data being plotted. and here's the slay part: the graph will automatically be redrawn when the vectors are updated or changed. by using vectors, you can separate data analysis from the graph widget, which makes it easier (for example) to add data transformations, like splines. and you can plot the same data into multiple graphs, where each graph presents a different view or scale of the data. main character behavior fr fr ๐
๐ญ not me using Tcl's associative arrays as vectors ๐ญ
You could try to use Tcl's associative arrays as vectors. Tcl arrays are easy to use, ngl โ you can access individual elements randomly by specifying the index, or set the entire array by providing a list of index and value pairs for each element. but bestie, the disadvantages of associative arrays as vectors lie in the fact they are implemented as hash tables. and that's giving... problems:
- There's no implied ordering to the associative arrays. If you used vectors for plotting, you would want to insure the second component comes after the first, and so on. This isn't possible since arrays are actually hash tables. For example, you can't get a range of values between two indices. Nor can you sort an array. ๐
- Arrays consume lots of memory when the number of elements becomes large (tens of thousands). This is because each element's index and value are stored as strings in the hash table. the memory usage is not giving minimalist ๐ซ
- The C programming interface is unwieldy. Normally with vectors, you would like to view the Tcl array as you do a C array, as an array of floats or doubles. But with hash tables, you must convert both the index and value to and from decimal strings, just to access an element in the array. This makes it cumbersome to perform operations on the array as a whole. ๐
The vector command tries to overcome these disadvantages while still retaining the ease of use of Tcl arrays. The vector command creates both a new Tcl command and an associate array which are linked to the vector components. You can randomly access vector components through the elements of the array. Not all indices are generated for the array, so printing the array (using the parray procedure) does not print out all the component values. You can use the Tcl command to access the array as a whole. You can copy, append, or sort a vector using its command. And if you need greater performance, or customized behavior, you can write your own C code to manage vectors. periodt. ๐
๐ EXAMPLE ๐
You create vectors using the vector command and its create operation.
# Create a new vector.
vector create y(50)
This creates a new vector named y. It has fifty components, by default, initialized to 0.0. In addition, both a Tcl command and array variable, both named y, are created. You can use either the command or variable to query or modify components of the vector.
# Set the first value.
set y(0) 9.25
puts "y has [y length] components"
The array y can be used to read or set individual components of the vector. Vector components are indexed from zero. The array index must be a number less than the number of components. For example, it's an error if you try to set the 51st element of y.
# This is an error. The vector only has 50 components.
set y(50) 0.02
โ ๏ธ yeah bestie that one's an error, don't do it.
You can also specify a range of indices using a colon (:) to separate the first and last indices of the range.
# Set the first six components of y
set y(0:5) 25.2
If you don't include an index, then it will default to the first and/or last component of the vector.
# Print out all the components of y
puts "y = $y(:)"
๐ฆ the special indices ๐ฆ
There are special non-numeric indices. The index end, specifies the last component of the vector. It's an error to use this index if the vector is empty (length is zero). The index ++end can be used to extend the vector by one component and initialize it to a specific value. You can't read from the array using this index, though.
# Extend the vector by one component.
set y(++end) 0.02
The other special indices are min and max. They return the current smallest and largest components of the vector.
# Print the bounds of the vector
puts "min=$y(min) max=$y(max)"
๐ธ deleting components ๐ธ
To delete components from a vector, simply unset the corresponding array element. In the following example, the first component of y is deleted. All the remaining components of y will be moved down by one index as the length of the vector is reduced by one.
# Delete the first component
unset y(0)
puts "new first element is $y(0)"
๐ the Tcl command era ๐
The vector's Tcl command can also be used to query or set the vector.
# Create and set the components of a new vector
vector create x
x set { 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20 }
Here we've created a vector x without a initial length specification. In this case, the length is zero. The set operation resets the vector, extending it and setting values for each new component.
There are several operations for vectors. The range operation lists the components of a vector between two indices.
# List the components
puts "x = [x range 0 end]"
You can search for a particular value using the search operation. It returns a list of indices of the components with the same value. If no component has the same value, it returns "".
# Find the index of the biggest component
set indices [x search $x(max)]
Other operations copy, append, or sort vectors. You can append vectors or new values onto an existing vector with the append operation.
# Append assorted vectors and values to x
x append x2 x3 { 2.3 4.5 } x4
The sort operation sorts the vector. If any additional vectors are specified, they are rearranged in the same order as the vector. For example, you could use it to sort data points represented by x and y vectors.
# Sort the data points
x sort y
The vector x is sorted while the components of y are rearranged so that the original x,y coordinate pairs are retained. cute, right? the pairs stay together ๐ซถ
The expr operation lets you perform arithmetic on vectors. The result is stored in the vector.
# Add the two vectors and a scalar
x expr { x + y }
x expr { x * 2 }
๐ notifications, aka the drama ๐
When a vector is modified, resized, or deleted, it may trigger call-backs to notify the clients of the vector. For example, when a vector used in the graph widget is updated, the vector automatically notifies the widget that it has changed. The graph can then redraw itself at the next idle point. By default, the notification occurs when Tk is next idle. This way you can modify the vector many times without incurring the penalty of the graph redrawing itself for each change. You can change this behavior using the notify operation.
# Make vector x notify after every change
x notify always
...
# Never notify
x notify never
...
# Force notification now
x notify now
# Set Tcl callback for update of Tktable widget .t.
x notify callback {.t conf -padx [.t cget -padx]; .t reread}
๐ deleting ๐
To delete a vector, use the vector delete command. Both the vector and its corresponding Tcl command are destroyed.
# Remove vector x
vector destroy x
โจ the pseudo vector last โจ
The psuedo vector last can be used at the end of an expression to implement running totals. During execution it resolves to the result from the previous vector element evaluation. running totals? we love her ๐
vector create A(10)
vector create B(10)
vector create S(10)
vector create T(10)
S expr A+B
T expr S+last; # Running total
โจ SYNTAX โจ
Okay bestie, so how do you actually make a vector? You use the vector create operation, and it comes in โ and I quote โ one of three forms. (There are four listed below. We don't ask questions, we just vibe. ๐
)
vector create vecNameโ baby's first vector! This makes a brand-new vector calledvecNamethat literally has no components yet. Empty. Blank canvas. Main character before her glow-up. ๐vector create vecName(size)โ now we're talking. This one makes a vector holdingsizecomponents, indexed starting from zero (0). Every component starts out as0.0. So like, zeroed out but ready. โจvector create vecName(rows,columns)โ matrix time, queen ๐. This creates a matrix with the columns you asked for androws*columnselements. Peep the matrix section for the whole story.vector create vecName(first:last)โ this form makes a new vector indexed fromfirstthroughlast.firstandlastcan be any integer value, as long asfirstis less thanlast. That's the rule, fr fr.
Also, vector names have a dress code: they must start with a letter, and after that they're just letters, digits, or underscores. No exceptions, no shortcuts. ๐
# Error: must start with letter
vector create 1abc
And here's the cute part โ you can let the computer name your vector for you using the #auto vector name. The create operation will generate a unique vector name, like it's picking a username for you. ๐ฆ
set vec [vector create #auto]
puts "$vec has [$vec length] components"
๐ง VECTOR INDICES ๐ง
Vectors are indexed by integers, periodt. You can get at individual vector components through its array variable or its Tcl command. And the string that represents the index? It can be an integer, a numeric expression, a range, or a special keyword. So many options, so much power. ๐
Heads up: the index must lie within the current range of the vector, otherwise you get an error message back. No reaching outside the range, bestie, that's not it.
Normally a vector's indices start from 0. But โ plot twist โ you can use the offset operation to change a vector's indices on the fly. Slay. ๐
puts $vecName(0)
vecName offset -5
puts $vecName(-5)
When matrix numcols is greater than 1, 2D indexes are supported using the ROW,COL form. Two dimensions, twice the fun. โจ
vecName matrix numcols 3
puts vecName(0,2)
You can also use numeric expressions as indices. The result of the expression has to be an integer value though โ no decimals sneaking in. ๐
set n 21
set vecName($n+3) 50.2
Now for the special non-numeric indices, the VIP section: min, max, end, and ++end. Iconic lineup honestly. ๐
puts "min = $vecName($min)"
set vecName(end) -1.2
Let me break those down for you:
minandmaxโ they return the minimum and maximum values of the vector. Also available in this little squad:prod,sum, andmean. All the math besties. ๐endโ returns the value of the last component in the vector. Classic.end,0โ returns the value of the last row in column0of the vector. Matrix edition.++endโ the glow-up index. It appends a new value onto the vector, and it automatically extends the vector bynumcolsand sets its value. Grow, girl. ๐ธ
# Append an new component to the end
set vecName(++end) 3.2
And you can indicate a range of indices with a colon (:). So much more efficient than doing it one by one, ngl. ๐
# Set the first six components to 1.0
set vecName(0:5) 1.0
Oh and โ if you supply no index at all, the first or last component is assumed. The vector just picks for you. Generous. ๐ซถ
# Print the values of all the components
puts $vecName(:)
โจ VECTOR OPERATIONS โจ
okay bestie, so like, these are the operations you can do on vectors. let's get into it ๐ no cap.
vector configure
vector configure ? -flush bool -watchunset bool -oldcreate bool -maxsize
int -novariable bool -nocommand bool?
So like, the configure operation sets the default options used in creating vectors. These options are global to the interpreter, meaning they affect everything, fr fr. The -maxsize option, when it's non-zero, limits creation size. The -oldcreate enables the creation shortcut: vector vec1 vec2 .... For details on the others, check the create command. By default, they're all disabled or zero. โจ
vector create
vector create vecName?(size)?... ?switches?
bestie, this is where you make a new vector. The create operation creates a new vector vecName. The size may be an integer, a START:END range or ROW,COL (see matrix). This creates both a Tcl command and array variable called vecName. The name vecName must be unique, so another Tcl command or array variable can not already exist in the current scope. You may access the components of the vector using the variable. If you change a value in the array, or unset an array element, the vector is updated to reflect the changes. When the variable vecName is unset, the vector and its Tcl command are also destroyed. ๐ซถ
The vector has optional switches that affect how the vector is created. They are as follows:
-variablevarName โ Specifies the name of a Tcl variable to be mapped to the vector. If the variable already exists, it is first deleted, then recreated. If varName is the empty string, then no variable will be mapped. You can always map a variable back to the vector using the vector'svariableoperation.-commandcmdName โ Maps a Tcl command to the vector. The vector can be accessed using cmdName and one of the vector instance operations. A Tcl command by that name cannot already exist. If cmdName is the empty string, no command mapping will be made.-watchunsetboolean โ Indicates that the vector should automatically delete itself if the variable associated with the vector is unset. By default, the vector will not be deleted. This is different from previous releases. Set boolean to"true"to get the old behavior.-flushboolean โ Indicates that the vector should automatically flush the cached variable elements which unsets all the elements of the Tcl array variable associated with the vector, freeing memory associated with the variable. This includes both the hash table and the hash keys. The down side is that this effectively flushes the caching of vector elements in the array. This means that the subsequent reads of the array will require a decimal to string conversion. By default, flushing is disabled.
vector destroy
vector destroy vecName ?vecName...?
Destroy vectors. poof, gone ๐จ no more vector, bestie.
vector expr
vector expr expression
All binary operators take vectors as operands (remember that numbers are treated as one-component vectors). The exact action of binary operators depends upon the length of the second operand. If the second operand has only one component, then each element of the first vector operand is computed by that value. For example, the expression x * 2 multiples all elements of the vector x by 2. If the second operand has more than one component, both operands must be the same length. Each pair of corresponding elements are computed. So x + y adds the first components of x and y together, the second, and so on.
The valid operators are listed below, grouped in decreasing order of precedence:
-,!โ Unary minus and logical NOT. The unary minus flips the sign of each component in the vector. The logical not operator returns a vector of whose values are 0.0 or 1.0. For each non-zero component 1.0 is returned, 0.0 otherwise.^โ Exponentiation.*,/,%โ Multiply, divide, remainder.+,-โ Add and subtract.<<,>>โ Left and right shift. Circularly shifts the values of the vector<,>,<=,>=โ Boolean less, greater, less than or equal, and greater than or equal. Each operator returns a vector of ones and zeros. If the condition is true, 1.0 is the component value, 0.0 otherwise.==,!=โ Boolean equal and not equal. Each operator returns a vector of ones and zeros. If the condition is true, 1.0 is the component value, 0.0 otherwise.&&โ Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise.||โ Logical OR. Produces a 0 result if both operands are zero, 1 otherwise.x?y:zโ If-then-else, as in C.
See the C manual for more details on the results produced by each operator. All of the binary operators group left-to-right within the same precedence level.
Several mathematical functions are supported for vectors. Each of the following functions invokes the math library function of the same name; see the manual entries for the library functions for details on what they do. The operation is applied to all elements of the vector returning the results. All functions take a vector operand. If no vector operand is used in the call, the current vector is assumed. eg.
vector create aVec
aVec seq 0 100
aVec expr {2*abs(aVec)-1}
aVec length 100
aVec expr {2*row()}
vector expr {2*row()} ; # ERROR!
acos cos hypot sinh
asin cosh log sqrt
atan exp log10 tan
ceil floor sin tanh
Additional functions are:
absโ Returns the absolute value of each component.randomโ Returns a vector of non-negative values uniformly distributed between [0.0, 1.0) using drand48. The seed comes from the internal clock of the machine or may be set manual with the srandom function.roundโ Rounds each component of the vector.srandomโ Initializes the random number generator using srand48. The high order 32-bits are set using the integral portion of the first vector component. All other components are ignored. The low order 16-bits are set to an arbitrary value.
The following functions return a single value.
adevโ Returns the average deviation (defined as the sum of the absolute values of the differences between component and the mean, divided by the length of the vector).kurtosisโ Returns the degree of peakedness (fourth moment) of the vector.lengthโ Returns the number of components in the vector.maxโ Returns the vector's maximum value.meanโ Returns the mean value of the vector.medianโ Returns the median of the vector.minโ Returns the vector's minimum value.q1โ Returns the first quartile of the vector.q3โ Returns the third quartile of the vector.prodโ Returns the product of the components.sdevโ Returns the standard deviation (defined as the square root of the variance) of the vector.skewโ Returns the skewness (or third moment) of the vector. This characterizes the degree of asymmetry of the vector about the mean.sumโ Returns the sum of the components.varโ Returns the variance of the vector. The sum of the squared differences between each component and the mean is computed. The variance is the sum divided by the length of the vector minus 1.
This last set of functions returns a vector of the same length as the argument.
invertโ Returns vector with elements in reversed order.normโ Scales the values of the vector to lie in the range [0.0..1.0].rowโ Pseudo function to get the current row.sortโ Returns the vector components sorted in ascending order.shift(nVec,N)โ This is the only function taking a second arg. It provides a version of nvec shifted by N places. When N is a scalar or vector with only one element, shift fills vacant area with 0. Otherwise the second element of nVec is used for the fill value. One use for this is providing running totals.
vector names
vector names ?pattern?
Return names of all defined vectors. so you can see what you got, bestie.
vector op
vector op operation vecName ?arg?...
Invoke instance operation. Supported operations are defined in the next section. Op is the only way to invoke instance operation sub-commands when -command is defined as empty in a vector. It also allows writing vector code that is checkable by a syntax checkers. eg.
vector create v1
v1 op append {1 2 3}
v1 op modify 1 2.1
๐ฆ INSTANCE OPERATIONS ๐ฆ
You can also use the vector's Tcl command to query or modify it. The general form is vecName operation ?arg?... Note this is equivalent to the form: vector op operation vecName ?arg?... Both operation and its arguments determine the exact behavior of the command. The operations available for vectors are listed below.
vecName + item
vecName + item
vecName - item
vecName * item
vecName / item
Perform binary op and return result as a list.
vecName append
vecName append item ?item?...
Appends the component values from item to vecName. Item can be either the name of a vector or a list of numeric values.
vecName binread channel ?length? ?switches?โ bestie, this one pulls binary values straight out of a Tcl channel ๐ซถ. The values either get tacked onto the end of the vector, or dropped at a specific index (that's the-atoption doing its thing), which means they overwrite whatever was already chillin' there. Reading goes on until EOF shows up on the channel, or until you've read the number of values you said in length โ and no cap, that is not necessarily the same as the number of bytes ๐. Here's the switch lineup:-swapโ Swaps bytes and words around. The default endian is whatever your host machine is vibing with.-at indexโ The new values start at vector index index. Heads up: this will overwrite any current values. ๐-format formatโ Tells us the format of the data. format can be one of:"i1","i2","i4","i8","u1,"u2","u4","u8","r4","r8", or"r16". The number = how many bytes each value needs. The letter = the type:"i"for signed,"u"for unsigned,"r"for real. The default format is"r16"โจ.
vecName binwrite channel ?length? ?-at index?โ literally the same energy asbinread, except it writes the data instead. โ๏ธvecName clearโ Nukes the element indices from the array variable that's attached tovecName. And bestie, this does not touch the components of the vector, okay, don't panic ๐. By default, the number of entries in the Tcl array doesn't match the number of components in the vector โ and why? because it's way too expensive to maintain decimal strings for both the index and the value of every single component ๐ญ. So instead, the index and value only get saved when you read or write an element with a new index. This command yeets the index and value strings out of the array, and it's genuinely useful when the vector is huge. ๐vecName delete index ?index?...โ Deletes the indexth component from the vectorvecName. Index is the index of the element to be deleted. It's the same as unsetting the array variable element index. The vector gets compacted after all the indices have been deleted, so everything slides back together ๐ง.vecName dup destNameโ CopiesvecNameintodestName.DestNameis the name of a destination vector. If a vector calleddestNamealready exists, it gets overwritten with the components ofvecName. Otherwise a brand new vector is created. โจvecName expr expressionโ Computes the expression and resets the values of the vector accordingly. Both scalar and vector math operations are allowed ๐งฎ. Every value in an expression is either a real number or the name of a vector. And here's the fun bit: all numbers are treated as one-component vectors. ๐vecName index index ?value?...โ Get/set individual vector values. This is the move for element updating when-variableis set to empty. ๐vecName insert index item ?item?...โ Inserts the component values from item intovecNameat index. Item can be either the name of a vector or a list of numeric values. ๐ธvecName length ?newSize?โ Queries or resets the number of components invecName. NewSize is a number specifying the new size of the vector. If newSize is smaller than the current size ofvecName, thenvecNamegets truncated โ๏ธ. If newSize is greater, the vector gets extended and the new components are initialized to0.0. If you don't pass a newSize argument at all, you just get the current length of the vector back. ๐vecName matrix ...โ Okay somatrixgives you a 2D array view into 1D data ๐. It provides indexing operations inROW,COLform, which makes it chef's kiss suitable for use with TkTable. And no, the data storage doesn't change one bit: vectors are still just a single long array, periodt. For example, here are two ways to create a 3 column by 10 row matrix:
vector create aVec(10,3)
vector create bVec(30)
bVec matrix numcols 3
set aVec(0,0) 99
set bVec(29,2) -99
aVec append {5 6 7}; # aVec now has 11 rows.
aVec append 1 2; # Now aVec has 13 rows!
Note that data is appended only in increments of numcols. Elements 0-2 make up the first row, 3-5 the second, etc. Elements will appear only in increments of the column size. ๐ฅ
vecName matrix copy dstcolumn srccolumn ?srcVec?โ Copies a column of element values into column dstcolumn from srccolumn. If vector srcVec is given, and it's not the same asvecName, then the columns numbers must be different. If the srcVec column is longer,vecNamewill be extended. If it's shorter, the remaining destination values are just not overwritten, no biggie. ๐ซถvecName matrix delete column.โ Deletes elements in a column. Note that numcols, which must be greater than 1, will be decremented. ๐vecName matrix get columnโ Gets the element in a column: this number must be less than numcols. And note that numcols must be non-zero, okay? ๐vecName matrix insert column ?initvalue? .โ Inserts a new column of elements at column (default0). The new column is initialized with initvalue, or0.0if it's not specified. Note that numcols will be incremented. ๐vecName matrix multiply srcVec ?dstVec?โ Performs matrix multiplication using srcVec, placing results either in dstVec, or returned as a list. The numrows of srcVec must equal numcols invecName. One application formultiplyis coordinate transformation, iykyk ๐งฎ.vecName matrix numcols ?size?โ Get or set the number of columns for a vector's data. Values>1enable array variables to accept 2d matrix indexes. For example with a numcols of10,$vec1(1,2)refers to the 13th element in the vector. A vector's size is also constrained to multiples of numcols, as is its offset. By default, numcols is1. ๐vecName matrix numrows ?size?โ Get or set the length of rows in a columns for a vector. By default, this is just the vector length divided by numcols. Setting this value is simply a convenient way to increase or decrease the vector size by multiples of numcols. ๐vecName matrix set column ?valuelist?โ Set value elements in a column: this number must be less than numcols. The valuelist is a list of values. If this list is shorter than the column, its last value is used for all remaining columns. The column gets set to the values of item, or0.0by default. โจvecName matrix shift column amount ?startoffset?โ Shifts the values of a column by integer inamount. A negative value shifts upward. The startoffset indicates where to start shifting from. ๐vecName matrix sort column ?-reverse?โ Sorts the vector by the given column. ๐งvecName matrix transposeโ Transposes all columns with rows in the matrix. Note that this is a no-op if numcols is1. Otherwise, numcols will change tovectorLength/numcols. ๐
vecName merge srcName ?srcName?...โ Merges the named vectors into a single vector. The resulting vector is formed by merging the components of each source vector one index at a time. ๐vecName notify ?keyword? ?script?โ Queries or controls how vector clients get notified about changes to the vector. It also lets you set a notifier callback. The exact behavior is decided by keyword:alwaysโ Clients are to be notified immediately whenever the vector is updated. โกneverโ No clients are to be notified. ๐whenidleโ Clients are to be notified at the next idle point whenever the vector is updated. ๐ดnowโ If any client notifications are currently pending, they get notified immediately. ๐cancelโ Cancels pending notifications of clients using the vector. ๐ซpendingโ Returns1if a client notification is pending, and0otherwise. ๐callback ?script?โ Query or set a Tcl callback script that gets evaluated when a vector is updated. ๐ซถ
vecName populate destName ?density?โ Creates a vectordestNamewhich is a superset ofvecName.DestNamewill include all the components ofvecName, and on top of that, the interval between each of the original components will contain a density number of new components, whose values are evenly distributed between the original components' values. This is super useful for generating abscissas to be interpolated along a spline ๐ธ.vecName range firstIndex ?lastIndex?...โ Returns a list of numeric values representing the vector components between two indices. Both firstIndex and lastIndex are indices representing the range of components to be returned. If lastIndex is less than firstIndex, the components are listed in reverse order. ๐vecName search value ?value?โ Searches for a value, or a range of values, among the components ofvecName. If one value argument is given, you get back a list of indices of the components which equal value. If a second value is also provided, then you get the indices of all components which lie within the range of the two values. If no components are found, then""is returned. ๐ต๏ธvecName set itemโ Resets the components of the vector to item. Item can be either a list of numeric expressions or another vector. โจvecName seq start ?finish? ?step?โ Generates a sequence of values starting with the value start. Finish indicates the terminating value of the sequence. The vector is automatically resized to contain just the sequence. If three arguments are present, step designates the interval.
With only two arguments (no finish argument), the sequence will continue until the vector is filled. With one argument, the interval defaults to 1.0. ๐
vecName sort ?-reverse? ?argName?...โ Sorts the vectorvecNamein increasing order. If the-reverseflag is present, the vector is sorted in decreasing order. If other argumentsargNameare present, they are the names of vectors which will be rearranged in the same manner asvecName. Each vector must be the same length asvecName. You could use this to sort the x vector of a graph, while still retaining the same x,y coordinate pairs in a y vector. ๐ฆvecName split dstName ?dstName?...โ Split the vector into a multiple vectors. The resulting N vectors each contain the mod-Nth element from source. โจvecName variable varNameโ Maps a Tcl variable to the vector, creating another means for accessing the vector. The variablevarNamecan't already exist. This overrides any current variable mapping the vector may have. ๐
๐ง C LANGUAGE API ๐ง
You can create, modify, and destroy vectors from C code, using library routines. You need to include the header file blt.h. It contains the definition of the structure Blt_Vector, which represents the vector. It appears below. ๐
typedef struct {
double *valueArr;
int numValues;
int arraySize;
double min, max;
} Blt_Vector;
The field valueArr points to memory holding the vector components. The components are stored in a double precision array, whose size size is represented by arraySize. NumValues is the length of vector. The size of the array is always equal to or larger than the length of the vector. Min and max are minimum and maximum component values. ๐ธ
๐ LIBRARY ROUTINES ๐
The following routines are available from C to manage vectors. Vectors are identified by the vector name. ๐
๐ Blt_CreateVector
๐ Synopsis
int Blt_CreateVector (interp, vecName, length, vecPtrPtr)
Tcl_Interp *interp;
char *vecName;
int length;
Blt_Vector **vecPtrPtr;
๐ Description
Creates a new vector vecName with a length of length. Blt_CreateVector creates both a new Tcl command and array variable vecName. Neither a command nor variable named vecName can already exist. A pointer to the vector is placed into vecPtrPtr. โจ
โจ Results
Returns TCL_OK if the vector is successfully created. If length is negative, a Tcl variable or command vecName already exists, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐
๐ Blt_DeleteVectorByName
๐ Synopsis
int Blt_DeleteVectorByName (interp, vecName)
Tcl_Interp *interp;
char *vecName;
๐ Description
Removes the vector vecName. VecName is the name of a vector which must already exist. Both the Tcl command and array variable vecName are destroyed. All clients of the vector will be notified immediately that the vector has been destroyed. ๐ซถ
โจ Results
Returns TCL_OK if the vector is successfully deleted. If vecName is not the name of a vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐ญ
๐ Blt_DeleteVector
๐ Synopsis
int Blt_DeleteVector (vecPtr)
Blt_Vector *vecPtr;
๐ Description
Removes the vector pointed to by vecPtr. VecPtr is a pointer to a vector, typically set by Blt_GetVector or Blt_CreateVector. Both the Tcl command and array variable of the vector are destroyed. All clients of the vector will be notified immediately that the vector has been destroyed. ๐ฅ
โจ Results
Returns TCL_OK if the vector is successfully deleted. If vecName is not the name of a vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐
๐ Blt_GetVector
๐ Synopsis
int Blt_GetVector (interp, vecName, vecPtrPtr)
Tcl_Interp *interp;
char *vecName;
Blt_Vector **vecPtrPtr;
๐ Description
Retrieves the vector vecName. VecName is the name of a vector which must already exist. VecPtrPtr will point be set to the address of the vector. ๐
โจ Results
Returns TCL_OK if the vector is successfully retrieved. If vecName is not the name of a vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐
๐ Blt_ResetVector
๐ Synopsis
int Blt_ResetVector (vecPtr, dataArr,
numValues, arraySize, freeProc)
Blt_Vector *vecPtr;
double *dataArr;
int *numValues;
int *arraySize;
Tcl_FreeProc *freeProc;
๐ Description
Resets the components of the vector pointed to by vecPtr. Calling Blt_ResetVector will trigger the vector to dispatch notifications to its clients. DataArr is the array of doubles which represents the vector data. NumValues is the number of elements in the array. ArraySize is the actual size of the array (the array may be bigger than the number of values stored in it). FreeProc indicates how the storage for the vector component array (dataArr) was allocated. It is used to determine how to reallocate memory when the vector is resized or destroyed. It must be TCL_DYNAMIC, TCL_STATIC, TCL_VOLATILE, or a pointer to a function to free the memory allocated for the vector array. If freeProc is TCL_VOLATILE, it indicates that dataArr must be copied and saved. If freeProc is TCL_DYNAMIC, it indicates that dataArr was dynamically allocated and that Tcl should free dataArr if necessary. Static indicates that nothing should be done to release storage for dataArr. ๐ง
โจ Results
Returns TCL_OK if the vector is successfully resized. If newSize is negative, a vector vecName does not exist, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐ญ
๐ Blt_ResizeVector
๐ Synopsis
int Blt_ResizeVector (vecPtr, newSize)
Blt_Vector *vecPtr;
int newSize;
๐ Description
Resets the length of the vector pointed to by vecPtr to newSize. If newSize is smaller than the current size of the vector, it is truncated. If newSize is greater, the vector is extended and the new components are initialized to 0.0. Calling Blt_ResetVector will trigger the vector to dispatch notifications. ๐
โจ Results
Returns TCL_OK if the vector is successfully resized. If newSize is negative or memory can not be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message. ๐
๐ Blt_VectorExists
๐ Synopsis
int Blt_VectorExists (interp, vecName)
Tcl_Interp *interp;
char *vecName;
๐ Description
Indicates if a vector named vecName exists in interp. ๐
โจ Results
Returns 1 if a vector vecName exists and 0 otherwise. โ
If your application needs to be notified when a vector changes, it can allocate a unique client identifier for itself. Using this identifier, you can then register a call-back to be made whenever the vector is updated or destroyed. By default, the call-backs are made at the next idle point. This can be changed to occur at the time the vector is modified. An application can allocate more than one identifier for any vector. When the client application is done with the vector, it should free the identifier. ๐ฃ
The call-back routine must be of the following type. ๐ฆ
typedef void (Blt_VectorChangedProc) (Tcl_Interp *interp,
ClientData clientData, Blt_VectorNotify notify);
ClientData is passed to this routine whenever it is called. You can use this to pass information to the call-back. The notify argument indicates whether the vector has been updated or destroyed. It is an enumerated type. โจ
typedef enum {
BLT_VECTOR_NOTIFY_UPDATE=1,
BLT_VECTOR_NOTIFY_DESTROY=2
} Blt_VectorNotify;
๐ง Blt_AllocVectorId
๐ Synopsis
Blt_VectorId Blt_AllocVectorId (interp, vecName)
Tcl_Interp *interp;
char *vecName;
๐ Description
Allocates a client identifier for with the vector vecName. This identifier can be used to specify a call-back which is triggered when the vector is updated or destroyed. ๐
โจ Results
Returns a client identifier if successful. If vecName is not the name of a vector, then NULL is returned and interp->result will contain an error message. ๐ญ
๐ Blt_GetVectorById
๐ Synopsis
int Blt_GetVector (interp, clientId, vecPtrPtr)
Tcl_Interp *interp;
Blt_VectorId clientId;
Blt_Vector **vecPtrPtr;
๐ Description
Retrieves the vector used by clientId. ClientId is a valid vector client identifier allocated by Blt_AllocVectorId. VecPtrPtr will point be set to the address of the vector. ๐
โจ Results
Returns TCL_OK if the vector is successfully retrieved. ๐
๐ Blt_SetVectorChangedProc
๐ Synopsis
void Blt_SetVectorChangedProc (clientId, proc, clientData);
Blt_VectorId clientId;
Blt_VectorChangedProc *proc;
ClientData *clientData;
okay so last stretch of the LIBRARY ROUTINES โจ bestie we're so close, keep scrolling ๐
the rest of this one, fr
Description: this is where you tell BLT who to yell at when stuff happens ๐ฌ it specifies a call-back routine that gets called whenever the vector associated with clientId is updated or deleted. Proc is a pointer to that call-back routine and it must be of the type Blt_VectorChangedProc. ClientData is a one-word value that gets passed to the routine when it's invoked. And if proc is NULL, then the client justโฆ isn't notified. no texts, no calls, ghosted ๐ป
Results: the designated call-back procedure will be invoked when the vector is updated or destroyed. that's it, that's the whole vibe ๐ซถ
๐ Blt_FreeVectorId
Synopsis:
void Blt_FreeVectorId (clientId);
Blt_VectorId clientId;
Description: frees the client identifier ๐งน the memory allocated for the identifier is released. and once it's gone, the client will no longer be notified when the vector is modified. it's giving "we don't talk anymore" ๐ญ
Results: the designated call-back procedure will be no longer be invoked when the vector is updated or destroyed.
๐ฆ Blt_NameOfVectorId
Synopsis:
char *Blt_NameOfVectorId (clientId);
Blt_VectorId clientId;
Description: retrieves the name of the vector associated with the client identifier clientId. lowkey the easiest one here ๐ธ
Results: returns the name of the vector associated with clientId. If clientId is not an identifier or the vector has been destroyed, NULL is returned. (yes, that means you check it. yes, every time. iykyk ๐)
๐ Blt_InstallIndexProc
Synopsis:
void Blt_InstallIndexProc (indexName, procPtr)
char *indexName;
Blt_VectorIndexProc *procPtr;
Description: registers a function to be called to retrieved the index indexName from the vector's array variable. so you're teaching the vector a whole new way to be indexed, main character energy fr ๐
typedef double Blt_VectorIndexProc(Vector *vecPtr);
The function will be passed a pointer to the vector. The function must return a double representing the value at the index. no returning vibes, it needs an actual number bestie ๐ฅ
Results: the new index is installed into the vector.
๐ C API EXAMPLE ๐
okay this one is iconic, get comfy ๐ The following example opens a file of binary data and stores it in an array of doubles. The array size is computed from the size of the file. If the vector "data" exists, calling Blt_VectorExists, Blt_GetVector is called to get the pointer to the vector. Otherwise the routine Blt_CreateVector is called to create a new vector and returns a pointer to it. Just like the Tcl interface, both a new Tcl command and array variable are created when a new vector is created. It doesn't make any difference what the initial size of the vector is since it will be reset shortly. The vector is updated when lt_ResetVector is called. Blt_ResetVector makes the changes visible to the Tcl interface and other vector clients (such as a graph widget). โจ
#include <tcl.h>
#include <blt.h>
...
Blt_Vector *vecPtr;
double *newArr;
FILE *f;
struct stat statBuf;
int numBytes, numValues;
f = fopen("binary.dat", "r");
fstat(fileno(f), &statBuf);
numBytes = (int)statBuf.st_size;
/* Allocate an array big enough to hold all the data */
newArr = (double *)malloc(numBytes);
numValues = numBytes / sizeof(double);
fread((void *)newArr, numValues, sizeof(double), f);
fclose(f);
if (Blt_VectorExists(interp, "data")) {
if (Blt_GetVector(interp, "data", &vecPtr) != TCL_OK) {
return TCL_ERROR;
}
} else {
if (Blt_CreateVector(interp, "data", 0, &vecPtr) != TCL_OK) {
return TCL_ERROR;
}
}
/*
* Reset the vector. Clients will be notified when Tk is idle.
* TCL_DYNAMIC tells the vector to free the memory allocated
* if it needs to reallocate or destroy the vector.
*/
if (Blt_ResetVector(vecPtr, newArr, numValues, numValues,
TCL_DYNAMIC) != TCL_OK) {
return TCL_ERROR;
}
๐ INCOMPATIBILITIES ๐
okay this is the part where we talk about the glow-up that broke people's code, and honestly? iconic but also ouch ๐ญ
In previous versions, if the array variable isn't global (i.e. local to a Tcl procedure), the vector is automatically destroyed when the procedure returns.
proc doit {} {
# Temporary vector x
vector x(10)
set x(9) 2.0
...
}
This has changed. Variables are not automatically destroyed when their variable is unset. You can restore the old behavior by setting the "-watchunset" switch. ๐ซถ
โ ๏ธ bestie if your old code leaned on that auto-destroy, it will not lean anymore. flip "-watchunset" if you want the old energy back. no cap.
โญ KEYWORDS โญ
vectorgraphwidget
and that's the whole page, we ate and left absolutely no crumbs ๐ this was BLT version 2.5, sitting pretty in section 3tcl as blt::vector(3tcl). go forth and vector responsibly, bestie ๐โจ๐ฆ
๐ฆ where this page comes from
- debian bookworm: blt-dev 2.5.3+dfsg-4.1
- debian trixie: blt-dev 2.5.3+dfsg-8
- ubuntu jammy: blt-dev 2.5.3+dfsg-4.1build2
- ubuntu noble: blt-dev 2.5.3+dfsg-7build1
- ubuntu questing: blt-dev 2.5.3+dfsg-8
- ubuntu resolute: blt-dev 2.5.3+dfsg-8build1
- ubuntu stonking: blt-dev 2.5.3+dfsg-9
- Copyright 1991-1997 by Lucent Technologies, Inc
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms