////////////////////////////////////////////////////////////////////// // LibFile: linalg.scad // This file provides linear algebra, with support for matrix construction, // solutions to linear systems of equations, QR and Cholesky factorizations, and // matrix inverse. // Includes: // include // FileGroup: Math // FileSummary: Linear Algebra: solve linear systems, construct and modify matrices. // FileFootnotes: STD=Included in std.scad ////////////////////////////////////////////////////////////////////// // Section: Matrices // The matrix, a rectangular array of numbers which represents a linear transformation, // is the fundamental object in linear algebra. In OpenSCAD a matrix is a list of lists of numbers // with a rectangular structure. Because OpenSCAD treats all data the same, most of the functions that // index matrices or construct them will work on matrices (lists of lists) whose elements are not numbers but may be // arbitrary data: strings, booleans, or even other lists. It may even be acceptable in some cases if the structure is non-rectangular. // Of course, linear algebra computations and solutions require true matrices with rectangular structure, where all the entries are // finite numbers. // . // Matrices in OpenSCAD are lists of row vectors. However, a potential source of confusion is that OpenSCAD // treats vectors as either column vectors or row vectors as demanded by // context. Thus both `v*M` and `M*v` are valid if `M` is square and `v` has the right length. If you want to multiply // `M` on the left by `v` and `w` you can do this with `[v,w]*M` but if you want to multiply on the right side with `v` and `w` as // column vectors, you now need to use {{transpose()}} because OpenSCAD doesn't adjust matrices // contextually: `A=M*transpose([v,w])`. The solutions are now columns of A and you must extract // them with {{column()}} or take the transpose of `A`. // Section: Matrix testing and display // Function: is_matrix() // Usage: // test = is_matrix(A, [m], [n], [square]) // Description: // Returns true if A is a numeric matrix of height m and width n with finite entries. If m or n // are omitted or set to undef then true is returned for any positive dimension. // Arguments: // A = The matrix to test. // m = If given, requires the matrix to have this height. // n = Is given, requires the matrix to have this width. // square = If true, matrix must have height equal to width. Default: false function is_matrix(A,m,n,square=false) = is_list(A) && (( is_undef(m) && len(A) ) || len(A)==m) && (!square || len(A) == len(A[0])) && is_vector(A[0],n) && is_consistent(A); // Function: is_matrix_symmetric() // Usage: // b = is_matrix_symmetric(A, [eps]) // Description: // Returns true if the input matrix is symmetric, meaning it approximately equals its transpose. // The matrix can have arbitrary entries. // Arguments: // A = matrix to test // eps = epsilon for comparing equality. Default: 1e-12 function is_matrix_symmetric(A,eps=1e-12) = approx(A,transpose(A), eps); // Function: is_rotation() // Usage: // b = is_rotation(A, [dim], [centered]) // Description: // Returns true if the input matrix is a square affine matrix that is a rotation around any point, // or around the origin if `centered` is true. // The matrix must be 3x3 (representing a 2d transformation) or 4x4 (representing a 3d transformation). // You can set `dim` to 2 to require a 2d transform (3x3 matrix) or to 3 to require a 3d transform (4x4 matrix). // Arguments: // A = matrix to test // dim = if set, specify dimension in which the transform operates (2 or 3) // centered = if true then require rotation to be around the origin. Default: false function is_rotation(A,dim,centered=false) = let(n=len(A)) is_matrix(A,square=true) && ( n==3 || n==4 && (is_undef(dim) || dim==n-1)) && ( let( rotpart = [for(i=[0:n-2]) [for(j=[0:n-2]) A[j][i]]] ) approx(determinant(rotpart),1) ) && (!centered || [for(row=[0:n-2]) if (!approx(A[row][n-1],0)) row]==[]); // Function&Module: echo_matrix() // Usage: // echo_matrix(M, [description], [sig], [sep], [eps]); // dummy = echo_matrix(M, [description], [sig], [sep], [eps]), // Description: // Display a numerical matrix in a readable columnar format with `sig` significant // digits. Values smaller than eps display as zero. If you give a description // it is displayed at the top. You can change the space between columns by // setting `sep` to a number of spaces, which will use wide figure spaces the same // width as digits, or you can set it to any string to separate the columns. // Values that are NaN or INF will display as "nan" and "inf". Values which are // otherwise non-numerica display as two dashes. Note that this includes lists, so // a 3D array will display as a list of dashes. // Arguments: // M = matrix to display, which should be numerical // description = optional text to print before the matrix // sig = number of digits to display. Default: 4 // sep = number of spaces between columns or a text string to separate columns. Default: 1 // eps = numbers smaller than this display as zero. Default: 1e-9 function echo_matrix(M,description,sig=4,sep=1,eps=1e-9) = let( horiz_line = chr(8213), matstr = _format_matrix(M,sig=sig,sep=sep,eps=eps), separator = str_join(repeat(horiz_line,10)), dummy=echo(str(separator,is_def(description) ? str(" ",description) : "")) [for(row=matstr) echo(row)] ) echo(separator); module echo_matrix(M,description,sig=4,sep=1,eps=1e-9) { dummy = echo_matrix(M,description,sig,sep,eps); } // Section: Matrix indexing // Function: column() // Usage: // list = column(M, i); // Topics: Matrices, List Handling // See Also: select(), slice() // Description: // Extracts entry `i` from each list in M, or equivalently column i from the matrix M, and returns it as a vector. // This function will return `undef` at all entry positions indexed by i not found in M. // Arguments: // M = The given list of lists. // i = The index to fetch // Example: // M = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]; // a = column(M,2); // Returns [3, 7, 11, 15] // b = column(M,0); // Returns [1, 5, 9, 13] // N = [ [1,2], [3], [4,5], [6,7,8] ]; // c = column(N,1); // Returns [1,undef,5,7] // data = [[1,[3,4]], [3, [9,3]], [4, [3,1]]]; // Matrix with non-numeric entries // d = column(data,0); // Returns [1,3,4] // e = column(data,1); // Returns [[3,4],[9,3],[3,1]] function column(M, i) = assert( is_list(M), "The input is not a list." ) assert( is_int(i) && i>=0, "Invalid index") [for(row=M) row[i]]; // Function: submatrix() // Usage: // mat = submatrix(M, idx1, idx2); // Topics: Matrices // See Also: column(), block_matrix(), submatrix_set() // Description: // The input must be a list of lists (a matrix or 2d array). Returns a submatrix by selecting the rows listed in idx1 and columns listed in idx2. // Arguments: // M = Given list of lists // idx1 = rows index list or range // idx2 = column index list or range // Example: // M = [[ 1, 2, 3, 4, 5], // [ 6, 7, 8, 9,10], // [11,12,13,14,15], // [16,17,18,19,20], // [21,22,23,24,25]]; // submatrix(M,[1:2],[3:4]); // Returns [[9, 10], [14, 15]] // submatrix(M,[1], [3,4])); // Returns [[9,10]] // submatrix(M,1, [3,4])); // Returns [[9,10]] // submatrix(M,1,3)); // Returns [[9]] // submatrix(M, [3,4],1); // Returns [[17],[22]]); // submatrix(M, [1,3],[2,4]); // Returns [[8,10],[18,20]]); // A = [[true, 17, "test"], // [[4,2], 91, false], // [6, [3,4], undef]]; // submatrix(A,[0,2],[1,2]); // Returns [[17, "test"], [[3, 4], undef]] function submatrix(M,idx1,idx2) = [for(i=idx1) [for(j=idx2) M[i][j] ] ]; // Section: Matrix construction and modification // Function: ident() // Usage: // mat = ident(n); // Topics: Affine, Matrices // Description: // Create an `n` by `n` square identity matrix. // Arguments: // n = The size of the identity matrix square, `n` by `n`. // Example: // mat = ident(3); // // Returns: // // [ // // [1, 0, 0], // // [0, 1, 0], // // [0, 0, 1] // // ] // Example: // mat = ident(4); // // Returns: // // [ // // [1, 0, 0, 0], // // [0, 1, 0, 0], // // [0, 0, 1, 0], // // [0, 0, 0, 1] // // ] function ident(n) = [ for (i = [0:1:n-1]) [ for (j = [0:1:n-1]) (i==j)? 1 : 0 ] ]; // Function: diagonal_matrix() // Usage: // mat = diagonal_matrix(diag, [offdiag]); // Topics: Matrices // See Also: column(), submatrix() // Description: // Creates a square matrix with the items in the list `diag` on // its diagonal. The off diagonal entries are set to offdiag, // which is zero by default. // Arguments: // diag = A list of items to put in the diagnal cells of the matrix. // offdiag = Value to put in non-diagonal matrix cells. function diagonal_matrix(diag, offdiag=0) = assert(is_list(diag) && len(diag)>0) [for(i=[0:1:len(diag)-1]) [for(j=[0:len(diag)-1]) i==j?diag[i] : offdiag]]; // Function: transpose() // Usage: // M = transpose(M, [reverse]); // Topics: Matrices // See Also: submatrix(), block_matrix(), hstack(), flatten() // Description: // Returns the transpose of the given input matrix. The input can be a matrix with arbitrary entries or // a numerical vector. If you give a vector then transpose returns it unchanged. // When reverse=true, the transpose is done across to the secondary diagonal. (See example below.) // By default, reverse=false. // Example: // M = [ // [1, 2, 3], // [4, 5, 6], // [7, 8, 9] // ]; // t = transpose(M); // // Returns: // // [ // // [1, 4, 7], // // [2, 5, 8], // // [3, 6, 9] // // ] // Example: // M = [ // [1, 2, 3], // [4, 5, 6] // ]; // t = transpose(M); // // Returns: // // [ // // [1, 4], // // [2, 5], // // [3, 6], // // ] // Example: // M = [ // [1, 2, 3], // [4, 5, 6], // [7, 8, 9] // ]; // t = transpose(M, reverse=true); // // Returns: // // [ // // [9, 6, 3], // // [8, 5, 2], // // [7, 4, 1] // // ] // Example: Transpose on a list of numbers returns the list unchanged // transpose([3,4,5]); // Returns: [3,4,5] // Example: Transpose on non-numeric input // arr = [ // [ "a", "b", "c"], // [ "d", "e", "f"], // [[1,2],[3,4],[5,6]] // ]; // t = transpose(arr); // // Returns: // // [ // // ["a", "d", [1,2]], // // ["b", "e", [3,4]], // // ["c", "f", [5,6]], // // ] function transpose(M, reverse=false) = assert( is_list(M) && len(M)>0, "Input to transpose must be a nonempty list.") is_list(M[0]) ? let( len0 = len(M[0]) ) assert([for(a=M) if(!is_list(a) || len(a)!=len0) 1 ]==[], "Input to transpose has inconsistent row lengths." ) reverse ? [for (i=[0:1:len0-1]) [ for (j=[0:1:len(M)-1]) M[len(M)-1-j][len0-1-i] ] ] : [for (i=[0:1:len0-1]) [ for (j=[0:1:len(M)-1]) M[j][i] ] ] : assert( is_vector(M), "Input to transpose must be a vector or list of lists.") M; // Function: outer_product() // Usage: // x = outer_product(u,v); // Description: // Compute the outer product of two vectors, a matrix. // Usage: // M = outer_product(u,v); function outer_product(u,v) = assert(is_vector(u) && is_vector(v), "The inputs must be vectors.") [for(ui=u) ui*v]; // Function: submatrix_set() // Usage: // mat = submatrix_set(M, A, [m], [n]); // Topics: Matrices // See Also: column(), submatrix() // Description: // Sets a submatrix of M equal to the matrix A. By default the top left corner of M is set to A, but // you can specify offset coordinates m and n. If A (as adjusted by m and n) extends beyond the bounds // of M then the extra entries are ignored. You can pass in A=[[]], a null matrix, and M will be // returned unchanged. This function works on arbitrary lists of lists and the input M need not be rectangular in shape. // Arguments: // M = Original matrix. // A = Submatrix of new values to write into M // m = Row number of upper-left corner to place A at. Default: 0 // n = Column number of upper-left corner to place A at. Default: 0 function submatrix_set(M,A,m=0,n=0) = assert(is_list(M)) assert(is_list(A)) assert(is_int(m)) assert(is_int(n)) let( badrows = [for(i=idx(A)) if (!is_list(A[i])) i]) assert(badrows==[], str("Input submatrix malformed rows: ",badrows)) [for(i=[0:1:len(M)-1]) assert(is_list(M[i]), str("Row ",i," of input matrix is not a list")) [for(j=[0:1:len(M[i])-1]) i>=m && i =n && jj ? 0 : ri[j] ] ] ) [qr[0], Rzero, qr[2]]; function _qr_factor(A,Q,P, pivot, col, m, n) = col >= min(m-1,n) ? [Q,A,P] : let( swap = !pivot ? 1 : _swap_matrix(n,col,col+max_index([for(i=[col:n-1]) sqr([for(j=[col:m-1]) A[j][i]])])), A = pivot ? A*swap : A, x = [for(i=[col:1:m-1]) A[i][col]], alpha = (x[0]<=0 ? 1 : -1) * norm(x), u = x - concat([alpha],repeat(0,m-1)), v = alpha==0 ? u : u / norm(u), Qc = ident(len(x)) - 2*outer_product(v,v), Qf = [for(i=[0:m-1]) [for(j=[0:m-1]) i=0 && j>=0, "Swap indices out of bounds") [for(y=[0:n-1]) [for (x=[0:n-1]) x==i ? (y==j ? 1 : 0) : x==j ? (y==i ? 1 : 0) : x==y ? 1 : 0]]; // Function: back_substitute() // Usage: // x = back_substitute(R, b, [transpose]); // Description: // Solves the problem Rx=b where R is an upper triangular square matrix. The lower triangular entries of R are // ignored. If transpose==true then instead solve transpose(R)*x=b. // You can supply a compatible matrix b and it will produce the solution for every column of b. Note that if you want to // solve Rx=b1 and Rx=b2 you must set b to transpose([b1,b2]) and then take the transpose of the result. If the matrix // is singular (e.g. has a zero on the diagonal) then it returns []. function back_substitute(R, b, transpose = false) = assert(is_matrix(R, square=true)) let(n=len(R)) assert(is_vector(b,n) || is_matrix(b,n),str("R and b are not compatible in back_substitute ",n, len(b))) transpose ? reverse(_back_substitute(transpose(R, reverse=true), reverse(b))) : _back_substitute(R,b); function _back_substitute(R, b, x=[]) = let(n=len(R)) len(x) == n ? x : let(ind = n - len(x) - 1) R[ind][ind] == 0 ? [] : let( newvalue = len(x)==0 ? b[ind]/R[ind][ind] : (b[ind]-list_tail(R[ind],ind+1) * x)/R[ind][ind] ) _back_substitute(R, b, concat([newvalue],x)); // Function: cholesky() // Usage: // L = cholesky(A); // Description: // Compute the cholesky factor, L, of the symmetric positive definite matrix A. // The matrix L is lower triangular and `L * transpose(L) = A`. If the A is // not symmetric then an error is displayed. If the matrix is symmetric but // not positive definite then undef is returned. function cholesky(A) = assert(is_matrix(A,square=true),"A must be a square matrix") assert(is_matrix_symmetric(A),"Cholesky factorization requires a symmetric matrix") _cholesky(A,ident(len(A)), len(A)); function _cholesky(A,L,n) = A[0][0]<0 ? undef : // Matrix not positive definite len(A) == 1 ? submatrix_set(L,[[sqrt(A[0][0])]], n-1,n-1): let( i = n+1-len(A) ) let( sqrtAii = sqrt(A[0][0]), Lnext = [for(j=[0:n-1]) [for(k=[0:n-1]) j