[vset VERSION 2.2]
[comment {-*- tcl -*-}]
[manpage_begin struct::matrix n [vset VERSION]]
[keywords matrix]
[copyright {2002-2013,2019,2022 Andreas Kupries <andreas.kupries@gmail.com>}]
[moddesc   {Tcl Data Structures}]
[titledesc {Create and manipulate matrix objects}]
[category  {Data structures}]
[require Tcl "8.5 9"]
[require struct::matrix [opt [vset VERSION]]]
[description]
[para]

A matrix is a rectangular collection of cells, i.e. organized in rows
and columns. Each cell contains exactly one value of arbitrary
form. The cells in the matrix are addressed by pairs of integer
numbers, with the first (left) number in the pair specifying the
column and the second (right) number specifying the row the cell is
in. These indices are counted from 0 upward. The special non-numeric
index [const end] refers to the last row or column in the matrix,
depending on the context. Indices of the form

[const end]-[var number] are counted from the end of the row or
column, like they are for standard Tcl lists. Trying to access
non-existing cells causes an error.

[para]

The matrices here are created empty, i.e. they have neither rows nor
columns. The user then has to add rows and columns as needed by his
application. A specialty of this structure is the ability to export an
array-view onto its contents. Such can be used by tkTable, for
example, to link the matrix into the display.

[para]

The main command of the package is:

[list_begin definitions]

[call [cmd ::struct::matrix] [opt [arg matrixName]] [opt "[const =]|[const :=]|[const as]|[const deserialize] [arg source]"]]

The command creates a new matrix object with an associated global Tcl
command whose name is [arg matrixName].  This command may be used to
invoke various operations on the matrix.  It has the following general
form:

[list_begin definitions]
[call [cmd matrixName] [arg option] [opt [arg "arg arg ..."]]]

[arg Option] and the [arg arg]s determine the exact behavior of the
command.

[list_end]
[para]

If [arg matrixName] is not specified a unique name will be generated
by the package itself. If a [arg source] is specified the new matrix
will be initialized to it. For the operators [const =], [const :=],
and [const as] the argument [arg source] is interpreted as the name of
another matrix object, and the assignment operator [method =] will be
executed. For [const deserialize] the [arg source] is a serialized
matrix object and [method deserialize] will be executed.

[para]

In other words
[para]
[example {
    ::struct::matrix mymatrix = b
}]
[para]
is equivalent to
[para]
[example {
    ::struct::matrix mymatrix
    mymatrix = b
}]
[para]
and
[para]
[example {
    ::struct::matrix mymatrix deserialize $b
}]
[para]
is equivalent to
[para]
[example {
    ::struct::matrix mymatrix
    mymatrix deserialize $b
}]

[list_end]

[para]

The following commands are possible for matrix objects:

[list_begin definitions]

[call [arg matrixName] [method =] [arg sourcematrix]]

This is the assignment operator for matrix objects. It copies the matrix
contained in the matrix object [arg sourcematrix] over the matrix data in
[arg matrixName]. The old contents of [arg matrixName] are deleted by
this operation.

[para]

This operation is in effect equivalent to
[para]
[example_begin]
    [arg matrixName] [method deserialize] [lb][arg sourcematrix] [method serialize][rb]
[example_end]

[call [arg matrixName] [method -->] [arg destmatrix]]

This is the reverse assignment operator for matrix objects. It copies
the matrix contained in the matrix object [arg matrixName] over the matrix
data in the object [arg destmatrix].

The old contents of [arg destmatrix] are deleted by this operation.

[para]

This operation is in effect equivalent to
[para]
[example_begin]
    [arg destmatrix] [method deserialize] [lb][arg matrixName] [method serialize][rb]
[example_end]

[call [arg matrixName] [method {add column}] [opt [arg values]]]

Extends the matrix by one column and then acts like [method {set column}]
(see below) on this new column if there were [arg values]
supplied. Without [arg values] the new cells will be set to the empty
string. The new column is appended immediately behind the last
existing column.

[call [arg matrixName] [method {add row}] [opt [arg values]]]

Extends the matrix by one row and then acts like [method {set row}] (see
below) on this new row if there were [arg values] supplied. Without
[arg values] the new cells will be set to the empty string. The new
row is appended immediately behind the last existing row.

[call [arg matrixName] [method {add columns}] [arg n]]

Extends the matrix by [arg n] columns. The new cells will be set to
the empty string. The new columns are appended immediately behind the
last existing column. A value of [arg n] equal to or smaller than 0 is
not allowed.

[call [arg matrixName] [method {add rows}] [arg n]]

Extends the matrix by [arg n] rows. The new cells will be set to the
empty string. The new rows are appended immediately behind the last
existing row. A value of [arg n] equal to or smaller than 0 is not
allowed.

[call [arg matrixName] [method cells]]

Returns the number of cells currently managed by the matrix. This is
the product of [method rows] and [method columns].

[call [arg matrixName] [method cellsize] [arg {column row}]]

Returns the length of the string representation of the value currently
contained in the addressed cell.

[call [arg matrixName] [method columns]]

Returns the number of columns currently managed by the matrix.

[call [arg matrixName] [method columnwidth] [arg column]]

Returns the length of the longest string representation of all the
values currently contained in the cells of the addressed column if
these are all spanning only one line. For cell values spanning
multiple lines the length of their longest line goes into the
computation.

[para][emph Note:] The command recognizes ANSI color control sequences
and excludes them from the width of a line, as they are logically of
zero width.

[para][emph Note:] The command properly recognizes and accounts for Asian double-wide characters.

[para][emph {In other words}], the returned length is the number of terminal columns taken by the
string, and not the number of characters.

[call [arg matrixName] [method {delete column}] [arg column]]

Deletes the specified column from the matrix and shifts all columns
with higher indices one index down.

[call [arg matrixName] [method {delete columns}] [arg n]]

Deletes [arg n] columns from the right of the matrix. The value of
[arg n] has to satisfy the constraint

"0 < [arg n] < [lb][cmd matrixName] [method columns][rb]"

[call [arg matrixName] [method {delete row}] [arg row]]

Deletes the specified row from the matrix and shifts all row with
higher indices one index down.

[call [arg matrixName] [method {delete rows}] [arg n]]

Deletes [arg n] rows from the bottom of the matrix. The value of
[arg n] has to satisfy the constraint

"0 < [arg n] < [lb][cmd matrixName] [method rows][rb]"

[call [arg matrixName] [method deserialize] [arg serialization]]

This is the complement to [method serialize]. It replaces matrix data
in [arg matrixName] with the matrix described by the [arg serialization]
value. The old contents of [arg matrixName] are deleted by this
operation.

[call [arg matrixName] [method destroy]]

Destroys the matrix, including its storage space and associated
command.

[call [arg matrixName] [method {format 2string}] [opt [arg report]]]

Formats the matrix using the specified report object and returns the
string containing the result of this operation. The report has to
support the [method printmatrix] method. If no [arg report] is
specified the system will use an internal report definition to format
the matrix.

[call [arg matrixName] [method {format 2chan}] [opt "[opt [arg report]] [arg channel]"]]

Formats the matrix using the specified report object and writes the
string containing the result of this operation into the channel. The
report has to support the [method printmatrix2channel] method.  If no
[arg report] is specified the system will use an internal report
definition to format the matrix. If no [arg channel] is specified the
system will use [const stdout].

[call [arg matrixName] [method {get cell}] [arg {column row}]]

Returns the value currently contained in the cell identified by row
and column index.

[call [arg matrixName] [method {get column}] [arg column]]

Returns a list containing the values from all cells in the column
identified by the index. The contents of the cell in row 0 are stored
as the first element of this list.

[call [arg matrixName] [method {get rect}] [arg {column_tl row_tl column_br row_br}]]

Returns a list of lists of cell values. The values stored in the
result come from the sub-matrix whose top-left and bottom-right cells
are specified by [arg {column_tl, row_tl}] and

[arg {column_br, row_br}] resp. Note that the following equations have
to be true: "[arg column_tl] <= [arg column_br]" and "[arg row_tl] <=
[arg row_br]". The result is organized as follows: The outer list is
the list of rows, its elements are lists representing a single
row. The row with the smallest index is the first element of the outer
list. The elements of the row lists represent the selected cell
values. The cell with the smallest index is the first element in each
row list.

[call [arg matrixName] [method {get row}] [arg row]]

Returns a list containing the values from all cells in the row
identified by the index. The contents of the cell in column 0 are
stored as the first element of this list.

[call [arg matrixName] [method {insert column}] [arg column] [opt [arg values]]]

Extends the matrix by one column and then acts like [method {set column}]
(see below) on this new column if there were [arg values]
supplied. Without [arg values] the new cells will be set to the empty
string. The new column is inserted just before the column specified by
the given index. This means, if [arg column] is less than or equal to
zero, then the new column is inserted at the beginning of the matrix,
before the first column. If [arg column] has the value [const end],
or if it is greater than or equal to the number of columns in the
matrix, then the new column is appended to the matrix, behind the last
column. The old column at the chosen index and all columns with higher
indices are shifted one index upward.

[call [arg matrixName] [method {insert row}] [arg row] [opt [arg values]]]

Extends the matrix by one row and then acts like [method {set row}] (see
below) on this new row if there were [arg values] supplied. Without
[arg values] the new cells will be set to the empty string. The new
row is inserted just before the row specified by the given index. This
means, if [arg row] is less than or equal to zero, then the new row is
inserted at the beginning of the matrix, before the first row. If

[arg row] has the value [const end], or if it is greater than or
equal to the number of rows in the matrix, then the new row is
appended to the matrix, behind the last row. The old row at that index
and all rows with higher indices are shifted one index upward.

[call [arg matrixName] [method link] [opt -transpose] [arg arrayvar]]

Links the matrix to the specified array variable. This means that the
contents of all cells in the matrix is stored in the array too, with
all changes to the matrix propagated there too. The contents of the
cell [arg (column,row)] is stored in the array using the key

[arg column,row]. If the option [option -transpose] is specified the
key [arg row,column] will be used instead. It is possible to link the
matrix to more than one array. Note that the link is bidirectional,
i.e. changes to the array are mirrored in the matrix too.

[call [arg matrixName] [method links]]

Returns a list containing the names of all array variables the matrix
was linked to through a call to method [method link].

[call [arg matrixName] [method rowheight] [arg row]]

Returns the height of the specified row in lines. This is the highest
number of lines spanned by a cell over all cells in the row.

[call [arg matrixName] [method rows]]

Returns the number of rows currently managed by the matrix.

[call [arg matrixName] [method search] [opt -nocase] [opt -exact|-glob|-regexp] [method all] [arg pattern]]

Searches the whole matrix for cells matching the [arg pattern] and
returns a list with all matches. Each item in the aforementioned list
is a list itself and contains the column and row index of the matching
cell, in this order. The results are ordered by column first and row
second, both times in ascending order. This means that matches to the
left and the top of the matrix come before matches to the right and
down.

[para]

The type of the pattern (string, glob, regular expression) is
determined by the option after the [method search] keyword. If no
option is given it defaults to [option -exact].

[para]

If the option [option -nocase] is specified the search will be
case-insensitive.

[call [arg matrixName] [method search] [opt -nocase] [opt -exact|-glob|-regexp] [method column] [arg {column pattern}]]

Like [method {search all}], but the search is restricted to the
specified column.

[call [arg matrixName] [method search] [opt -nocase] [opt -exact|-glob|-regexp] [method row] [arg {row pattern}]]

Like [method {search all}], but the search is restricted to the
specified row.

[call [arg matrixName] [method search] [opt -nocase] [opt -exact|-glob|-regexp] [method rect] [arg {column_tl row_tl column_br row_br pattern}]]

Like [method {search all}], but the search is restricted to the
specified rectangular area of the matrix.

[call [arg matrixName] [method serialize] [opt [arg {column_tl row_tl column_br row_br}]]]

This method serializes the sub-matrix spanned up by the rectangle
specification. In other words it returns a tcl [emph value] completely
describing that matrix. If no rectangle is specified the whole matrix
will be serialized.

This allows, for example, the transfer of matrix objects (or parts
thereof) over arbitrary channels, persistence, etc.

This method is also the basis for both the copy constructor and the
assignment operator.

[para]

The result of this method has to be semantically identical over all
implementations of the matrix interface. This is what will enable us
to copy matrix data between different implementations of the same
interface.

[para]

The result is a list containing exactly three items.

[para]

The first two elements of the list specify the number of rows and
columns of the matrix, in that order. The values integer numbers
greater than or equal to zero.

[para]

The last element of the list contains the values of the matrix cells
we have serialized, in the form of a value like it is returned by the
[method {get rect}]. However empty cells to the right and bottom of
the matrix can be left out of that value as the size information in
the serialization allows the receiver the creation of a matrix with
the proper size despite the missing values.

[example {
    # A possible serialization for the matrix structure
    #
    # | a b d g |
    # | c e     |
    # | f       |
    #
    # is
    #
    # 3 4 {{a b d g} {c e} {f}}
}]
[para]

[call [arg matrixName] [method {set cell}] [arg {column row value}]]

Sets the value in the cell identified by row and column index to the
data in the third argument.

[call [arg matrixName] [method {set column}] [arg {column values}]]

Sets the values in the cells identified by the column index to the
elements of the list provided as the third argument. Each element of
the list is assigned to one cell, with the first element going into
the cell in row 0 and then upward. If there are less values in the
list than there are rows the remaining rows are set to the empty
string. If there are more values in the list than there are rows the
superfluous elements are ignored. The matrix is not extended by this
operation.

[call [arg matrixName] [method {set rect}] [arg {column row values}]]

Takes a list of lists of cell values and writes them into the
submatrix whose top-left cell is specified by the two indices. If the
sublists of the outerlist are not of equal length the shorter sublists
will be filled with empty strings to the length of the longest
sublist. If the submatrix specified by the top-left cell and the
number of rows and columns in the [arg values] extends beyond the
matrix we are modifying the over-extending parts of the values are
ignored, i.e. essentially cut off. This subcommand expects its input
in the format as returned by [method {get rect}].

[call [arg matrixName] [method {set row}] [arg {row values}]]

Sets the values in the cells identified by the row index to the
elements of the list provided as the third argument. Each element of
the list is assigned to one cell, with the first element going into
the cell in column 0 and then upward. If there are less values in the
list than there are columns the remaining columns are set to the empty
string. If there are more values in the list than there are columns
the superfluous elements are ignored. The matrix is not extended by
this operation.

[call [arg matrixName] [method {sort columns}] [opt [option -increasing]|[option -decreasing]] [arg row]]

Sorts the columns in the matrix using the data in the specified
[arg row] as the key to sort by. The options [option -increasing]
and [option -decreasing] have the same meaning as for [cmd lsort].
If no option is specified [option -increasing] is assumed.

[call [arg matrixName] [method {sort rows}] [opt [option -increasing]|[option -decreasing]] [arg column]]

Sorts the rows in the matrix using the data in the specified
[arg column] as the key to sort by. The options [option -increasing]
and [option -decreasing] have the same meaning as for [cmd lsort].
If no option is specified [option -increasing] is assumed.

[call [arg matrixName] [method {swap columns}] [arg {column_a column_b}]]

Swaps the contents of the two specified columns.

[call [arg matrixName] [method {swap rows}] [arg {row_a row_b}]]

Swaps the contents of the two specified rows.

[call [arg matrixName] [method transpose]]

Transposes the contents of the matrix, i.e. swaps rows for columns and
vice versa.

[call [arg matrixName] [method unlink] [arg arrayvar]]

Removes the link between the matrix and the specified arrayvariable,
if there is one.

[list_end]

[section EXAMPLES]
[para]

The examples below assume a 5x5 matrix M with the first row containing
the values 1 to 5, with 1 in the top-left cell. Each other row
contains the contents of the row above it, rotated by one cell to the
right.

[para]
[example {
 % M get rect 0 0 4 4
 {{1 2 3 4 5} {5 1 2 3 4} {4 5 1 2 3} {3 4 5 1 2} {2 3 4 5 1}}
}]

[para]
[example {
 % M set rect 1 1 {{0 0 0} {0 0 0} {0 0 0}}
 % M get rect 0 0 4 4
 {{1 2 3 4 5} {5 0 0 0 4} {4 0 0 0 3} {3 0 0 0 2} {2 3 4 5 1}}
}]

[para]

Assuming that the style definitions in the example section of the
manpage for the package [package report] are loaded into the
interpreter now an example which formats a matrix into a tabular
report. The code filling the matrix with data is not shown.  contains
useful data.

[para]

[example {
    % ::struct::matrix m
    % # ... fill m with data, assume 5 columns
    % ::report::report r 5 style captionedtable 1
    % m format 2string r
    +---+-------------------+-------+-------+--------+
    |000|VERSIONS:          |2:8.4a3|1:8.4a3|1:8.4a3%|
    +---+-------------------+-------+-------+--------+
    |001|CATCH return ok    |7      |13     |53.85   |
    |002|CATCH return error |68     |91     |74.73   |
    |003|CATCH no catch used|7      |14     |50.00   |
    |004|IF if true numeric |12     |33     |36.36   |
    |005|IF elseif          |15     |47     |31.91   |
    |   |true numeric       |       |       |        |
    +---+-------------------+-------+-------+--------+
    %
    % # alternate way of doing the above
    % r printmatrix m
}]

[vset CATEGORY {struct :: matrix}]
[include ../common-text/feedback.inc]
[manpage_end]
