github.com/gopherd/gonum@v0.0.4/mat/band.go (about)

     1  // Copyright ©2017 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package mat
     6  
     7  import (
     8  	"github.com/gopherd/gonum/blas"
     9  	"github.com/gopherd/gonum/blas/blas64"
    10  	"github.com/gopherd/gonum/lapack"
    11  	"github.com/gopherd/gonum/lapack/lapack64"
    12  )
    13  
    14  var (
    15  	bandDense *BandDense
    16  	_         Matrix      = bandDense
    17  	_         allMatrix   = bandDense
    18  	_         denseMatrix = bandDense
    19  	_         Banded      = bandDense
    20  	_         RawBander   = bandDense
    21  
    22  	_ NonZeroDoer    = bandDense
    23  	_ RowNonZeroDoer = bandDense
    24  	_ ColNonZeroDoer = bandDense
    25  )
    26  
    27  // BandDense represents a band matrix in dense storage format.
    28  type BandDense struct {
    29  	mat blas64.Band
    30  }
    31  
    32  // Banded is a band matrix representation.
    33  type Banded interface {
    34  	Matrix
    35  	// Bandwidth returns the lower and upper bandwidth values for
    36  	// the matrix. The total bandwidth of the matrix is kl+ku+1.
    37  	Bandwidth() (kl, ku int)
    38  
    39  	// TBand is the equivalent of the T() method in the Matrix
    40  	// interface but guarantees the transpose is of banded type.
    41  	TBand() Banded
    42  }
    43  
    44  // A RawBander can return a blas64.Band representation of the receiver.
    45  // Changes to the blas64.Band.Data slice will be reflected in the original
    46  // matrix, changes to the Rows, Cols, KL, KU and Stride fields will not.
    47  type RawBander interface {
    48  	RawBand() blas64.Band
    49  }
    50  
    51  // A MutableBanded can set elements of a band matrix.
    52  type MutableBanded interface {
    53  	Banded
    54  
    55  	// SetBand sets the element at row i, column j to the value v.
    56  	// It panics if the location is outside the appropriate region of the matrix.
    57  	SetBand(i, j int, v float64)
    58  }
    59  
    60  var (
    61  	_ Matrix            = TransposeBand{}
    62  	_ Banded            = TransposeBand{}
    63  	_ UntransposeBander = TransposeBand{}
    64  )
    65  
    66  // TransposeBand is a type for performing an implicit transpose of a band
    67  // matrix. It implements the Banded interface, returning values from the
    68  // transpose of the matrix within.
    69  type TransposeBand struct {
    70  	Banded Banded
    71  }
    72  
    73  // At returns the value of the element at row i and column j of the transposed
    74  // matrix, that is, row j and column i of the Banded field.
    75  func (t TransposeBand) At(i, j int) float64 {
    76  	return t.Banded.At(j, i)
    77  }
    78  
    79  // Dims returns the dimensions of the transposed matrix.
    80  func (t TransposeBand) Dims() (r, c int) {
    81  	c, r = t.Banded.Dims()
    82  	return r, c
    83  }
    84  
    85  // T performs an implicit transpose by returning the Banded field.
    86  func (t TransposeBand) T() Matrix {
    87  	return t.Banded
    88  }
    89  
    90  // Bandwidth returns the lower and upper bandwidth values for
    91  // the transposed matrix.
    92  func (t TransposeBand) Bandwidth() (kl, ku int) {
    93  	kl, ku = t.Banded.Bandwidth()
    94  	return ku, kl
    95  }
    96  
    97  // TBand performs an implicit transpose by returning the Banded field.
    98  func (t TransposeBand) TBand() Banded {
    99  	return t.Banded
   100  }
   101  
   102  // Untranspose returns the Banded field.
   103  func (t TransposeBand) Untranspose() Matrix {
   104  	return t.Banded
   105  }
   106  
   107  // UntransposeBand returns the Banded field.
   108  func (t TransposeBand) UntransposeBand() Banded {
   109  	return t.Banded
   110  }
   111  
   112  // NewBandDense creates a new Band matrix with r rows and c columns. If data == nil,
   113  // a new slice is allocated for the backing slice. If len(data) == min(r, c+kl)*(kl+ku+1),
   114  // data is used as the backing slice, and changes to the elements of the returned
   115  // BandDense will be reflected in data. If neither of these is true, NewBandDense
   116  // will panic. kl must be at least zero and less r, and ku must be at least zero and
   117  // less than c, otherwise NewBandDense will panic.
   118  // NewBandDense will panic if either r or c is zero.
   119  //
   120  // The data must be arranged in row-major order constructed by removing the zeros
   121  // from the rows outside the band and aligning the diagonals. For example, the matrix
   122  //    1  2  3  0  0  0
   123  //    4  5  6  7  0  0
   124  //    0  8  9 10 11  0
   125  //    0  0 12 13 14 15
   126  //    0  0  0 16 17 18
   127  //    0  0  0  0 19 20
   128  // becomes (* entries are never accessed)
   129  //     *  1  2  3
   130  //     4  5  6  7
   131  //     8  9 10 11
   132  //    12 13 14 15
   133  //    16 17 18  *
   134  //    19 20  *  *
   135  // which is passed to NewBandDense as []float64{*, 1, 2, 3, 4, ...} with kl=1 and ku=2.
   136  // Only the values in the band portion of the matrix are used.
   137  func NewBandDense(r, c, kl, ku int, data []float64) *BandDense {
   138  	if r <= 0 || c <= 0 || kl < 0 || ku < 0 {
   139  		if r == 0 || c == 0 {
   140  			panic(ErrZeroLength)
   141  		}
   142  		panic(ErrNegativeDimension)
   143  	}
   144  	if kl+1 > r || ku+1 > c {
   145  		panic(ErrBandwidth)
   146  	}
   147  	bc := kl + ku + 1
   148  	if data != nil && len(data) != min(r, c+kl)*bc {
   149  		panic(ErrShape)
   150  	}
   151  	if data == nil {
   152  		data = make([]float64, min(r, c+kl)*bc)
   153  	}
   154  	return &BandDense{
   155  		mat: blas64.Band{
   156  			Rows:   r,
   157  			Cols:   c,
   158  			KL:     kl,
   159  			KU:     ku,
   160  			Stride: bc,
   161  			Data:   data,
   162  		},
   163  	}
   164  }
   165  
   166  // NewDiagonalRect is a convenience function that returns a diagonal matrix represented by a
   167  // BandDense. The length of data must be min(r, c) otherwise NewDiagonalRect will panic.
   168  func NewDiagonalRect(r, c int, data []float64) *BandDense {
   169  	return NewBandDense(r, c, 0, 0, data)
   170  }
   171  
   172  // Dims returns the number of rows and columns in the matrix.
   173  func (b *BandDense) Dims() (r, c int) {
   174  	return b.mat.Rows, b.mat.Cols
   175  }
   176  
   177  // Bandwidth returns the upper and lower bandwidths of the matrix.
   178  func (b *BandDense) Bandwidth() (kl, ku int) {
   179  	return b.mat.KL, b.mat.KU
   180  }
   181  
   182  // T performs an implicit transpose by returning the receiver inside a Transpose.
   183  func (b *BandDense) T() Matrix {
   184  	return Transpose{b}
   185  }
   186  
   187  // TBand performs an implicit transpose by returning the receiver inside a TransposeBand.
   188  func (b *BandDense) TBand() Banded {
   189  	return TransposeBand{b}
   190  }
   191  
   192  // RawBand returns the underlying blas64.Band used by the receiver.
   193  // Changes to elements in the receiver following the call will be reflected
   194  // in returned blas64.Band.
   195  func (b *BandDense) RawBand() blas64.Band {
   196  	return b.mat
   197  }
   198  
   199  // SetRawBand sets the underlying blas64.Band used by the receiver.
   200  // Changes to elements in the receiver following the call will be reflected
   201  // in the input.
   202  func (b *BandDense) SetRawBand(mat blas64.Band) {
   203  	b.mat = mat
   204  }
   205  
   206  // IsEmpty returns whether the receiver is empty. Empty matrices can be the
   207  // receiver for size-restricted operations. The receiver can be zeroed using Reset.
   208  func (b *BandDense) IsEmpty() bool {
   209  	return b.mat.Stride == 0
   210  }
   211  
   212  // Reset empties the matrix so that it can be reused as the
   213  // receiver of a dimensionally restricted operation.
   214  //
   215  // Reset should not be used when the matrix shares backing data.
   216  // See the Reseter interface for more information.
   217  func (b *BandDense) Reset() {
   218  	b.mat.Rows = 0
   219  	b.mat.Cols = 0
   220  	b.mat.KL = 0
   221  	b.mat.KU = 0
   222  	b.mat.Stride = 0
   223  	b.mat.Data = b.mat.Data[:0]
   224  }
   225  
   226  // DiagView returns the diagonal as a matrix backed by the original data.
   227  func (b *BandDense) DiagView() Diagonal {
   228  	n := min(b.mat.Rows, b.mat.Cols)
   229  	return &DiagDense{
   230  		mat: blas64.Vector{
   231  			N:    n,
   232  			Inc:  b.mat.Stride,
   233  			Data: b.mat.Data[b.mat.KL : (n-1)*b.mat.Stride+b.mat.KL+1],
   234  		},
   235  	}
   236  }
   237  
   238  // DoNonZero calls the function fn for each of the non-zero elements of b. The function fn
   239  // takes a row/column index and the element value of b at (i, j).
   240  func (b *BandDense) DoNonZero(fn func(i, j int, v float64)) {
   241  	for i := 0; i < min(b.mat.Rows, b.mat.Cols+b.mat.KL); i++ {
   242  		for j := max(0, i-b.mat.KL); j < min(b.mat.Cols, i+b.mat.KU+1); j++ {
   243  			v := b.at(i, j)
   244  			if v != 0 {
   245  				fn(i, j, v)
   246  			}
   247  		}
   248  	}
   249  }
   250  
   251  // DoRowNonZero calls the function fn for each of the non-zero elements of row i of b. The function fn
   252  // takes a row/column index and the element value of b at (i, j).
   253  func (b *BandDense) DoRowNonZero(i int, fn func(i, j int, v float64)) {
   254  	if i < 0 || b.mat.Rows <= i {
   255  		panic(ErrRowAccess)
   256  	}
   257  	for j := max(0, i-b.mat.KL); j < min(b.mat.Cols, i+b.mat.KU+1); j++ {
   258  		v := b.at(i, j)
   259  		if v != 0 {
   260  			fn(i, j, v)
   261  		}
   262  	}
   263  }
   264  
   265  // DoColNonZero calls the function fn for each of the non-zero elements of column j of b. The function fn
   266  // takes a row/column index and the element value of b at (i, j).
   267  func (b *BandDense) DoColNonZero(j int, fn func(i, j int, v float64)) {
   268  	if j < 0 || b.mat.Cols <= j {
   269  		panic(ErrColAccess)
   270  	}
   271  	for i := 0; i < min(b.mat.Rows, b.mat.Cols+b.mat.KL); i++ {
   272  		if i-b.mat.KL <= j && j < i+b.mat.KU+1 {
   273  			v := b.at(i, j)
   274  			if v != 0 {
   275  				fn(i, j, v)
   276  			}
   277  		}
   278  	}
   279  }
   280  
   281  // Zero sets all of the matrix elements to zero.
   282  func (b *BandDense) Zero() {
   283  	m := b.mat.Rows
   284  	kL := b.mat.KL
   285  	nCol := b.mat.KU + 1 + kL
   286  	for i := 0; i < m; i++ {
   287  		l := max(0, kL-i)
   288  		u := min(nCol, m+kL-i)
   289  		zero(b.mat.Data[i*b.mat.Stride+l : i*b.mat.Stride+u])
   290  	}
   291  }
   292  
   293  // Norm returns the specified norm of the receiver. Valid norms are:
   294  //  1 - The maximum absolute column sum
   295  //  2 - The Frobenius norm, the square root of the sum of the squares of the elements
   296  //  Inf - The maximum absolute row sum
   297  //
   298  // Norm will panic with ErrNormOrder if an illegal norm is specified and with
   299  // ErrZeroLength if the matrix has zero size.
   300  func (b *BandDense) Norm(norm float64) float64 {
   301  	if b.IsEmpty() {
   302  		panic(ErrZeroLength)
   303  	}
   304  	lnorm := normLapack(norm, false)
   305  	if lnorm == lapack.MaxColumnSum || lnorm == lapack.MaxRowSum {
   306  		return lapack64.Langb(lnorm, b.mat)
   307  	}
   308  	return lapack64.Langb(lnorm, b.mat)
   309  }
   310  
   311  // Trace returns the trace of the matrix.
   312  //
   313  // Trace will panic with ErrSquare if the matrix is not square and with
   314  // ErrZeroLength if the matrix has zero size.
   315  func (b *BandDense) Trace() float64 {
   316  	r, c := b.Dims()
   317  	if r != c {
   318  		panic(ErrSquare)
   319  	}
   320  	if b.IsEmpty() {
   321  		panic(ErrZeroLength)
   322  	}
   323  	rb := b.RawBand()
   324  	var tr float64
   325  	for i := 0; i < r; i++ {
   326  		tr += rb.Data[rb.KL+i*rb.Stride]
   327  	}
   328  	return tr
   329  }
   330  
   331  // MulVecTo computes B⋅x or Bᵀ⋅x storing the result into dst.
   332  func (b *BandDense) MulVecTo(dst *VecDense, trans bool, x Vector) {
   333  	m, n := b.Dims()
   334  	if trans {
   335  		m, n = n, m
   336  	}
   337  	if x.Len() != n {
   338  		panic(ErrShape)
   339  	}
   340  	dst.reuseAsNonZeroed(m)
   341  
   342  	t := blas.NoTrans
   343  	if trans {
   344  		t = blas.Trans
   345  	}
   346  
   347  	xMat, _ := untransposeExtract(x)
   348  	if xVec, ok := xMat.(*VecDense); ok {
   349  		if dst != xVec {
   350  			dst.checkOverlap(xVec.mat)
   351  			blas64.Gbmv(t, 1, b.mat, xVec.mat, 0, dst.mat)
   352  		} else {
   353  			xCopy := getVecDenseWorkspace(n, false)
   354  			xCopy.CloneFromVec(xVec)
   355  			blas64.Gbmv(t, 1, b.mat, xCopy.mat, 0, dst.mat)
   356  			putVecDenseWorkspace(xCopy)
   357  		}
   358  	} else {
   359  		xCopy := getVecDenseWorkspace(n, false)
   360  		xCopy.CloneFromVec(x)
   361  		blas64.Gbmv(t, 1, b.mat, xCopy.mat, 0, dst.mat)
   362  		putVecDenseWorkspace(xCopy)
   363  	}
   364  }