System matrix assembly
Assembling a sparse system matrix from element, cell or particle contributions can be done two ways, and EdelweissFE provides both. Which one is appropriate is a memory question far more than a speed one, so this page describes what each costs as well as what each does.
Both paths are in edelweissfe.numerics.csrgeneratorv2, backed by the C++ header
edelweissfe/numerics/_csrcore.h.
The two paths
Stage, then gather (CSRGenerator). Every entity writes
its dense block into its own slice of one long VIJ (COO triplet) value array. Contributions to the
same matrix entry land in different slots, and a second pass then sums the duplicates into CSR. The
addressing is a gather: for each of the nnz output entries, read the value-array positions that
feed it.
Scatter directly (DirectCSRAssembler). Each entity’s
block is pushed straight into the CSR data array, because every COO pair knows its destination slot in
advance – indptr[row] + offset, where offset is the position of the column within that row. No
value array is ever materialised.
Array |
Stage-then-gather |
Direct |
|---|---|---|
|
4 + 4 bytes / pair |
4 + 4 bytes / pair |
VIJ value array |
8 bytes / pair |
– |
|
4 bytes / pair |
– |
|
4 bytes / nnz |
– |
|
– |
2 bytes / pair |
CSR pattern and data |
4 + 8 bytes / nnz |
4 + 8 bytes / nnz |
The two entries in bold on the left are why this matters: the more duplicate contributions land on
the same matrix entry – which grows with the number of entities touching a DOF, not with the DOF
count itself – the larger the value array and gather_sources become relative to the CSR result
they produce. Their size is set by the number of COO pairs; the CSR pattern’s is set by nnz. A
discretisation where many entities contribute to the same entries (a wide stencil, or overlapping
supports) can have the staging array and gather map dwarf the actual result by a wide margin.
In the implicit solvers
The implicit solvers assemble their tangent through one interface,
SystemMatrixAssembly, so that neither the solver nor
an element, constraint or load knows which path is in use. Every entity asks for its block –
Ke = K[element] – and writes it; the solver then asks for the assembled matrix. The solver option
systemMatrixAssembly selects the path:
*solver, solver=NISTParallel, name=theSolver
systemMatrixAssembly=direct
vij (the default) is VIJSystemMatrixAssembly,
stage then gather; direct is
DirectCSRSystemMatrixAssembly, scatter directly.
NIST, NISTParallel and NISTPArcLength support both. NonlinearImplicitDynamic (and
NIDParallel) assemble on the VIJ path only, since they add the mass entry by entry to the VIJ value
array, and so does NEST.
What the direct path has to know about the entities and the solvers:
Sparse blocks. An entity may declare a VIJ pattern of its own, sparser than its dense
nDof x nDofblock (seeVIJEntityBase): a constraint that couples only some of its degrees of freedom. Its block is then the list of values of its own(I, J)pairs, which the scatter places entry by entry. The entity says so (couplesAllItsDofsisFalse); the number of its entries cannot tell, since a sparse pattern can have exactlynDof**2of them, as a rigid body contact with a single slave node in 3D has.Worker threads. Each thread of the parallel element loop writes through blocks of its own (
blocksOfWorker()), a scratch array, and adds every block to the one CSR matrix of the assembly with atomic additions, see One CSR array, atomic additions. The loop deals the elements out to the workers in a fixed way (mapChunksOnWorkers()), so that no two threads use the same scratch array at the same time.More than one matrix. The arc length method needs the tangents of its dead load and its reference load besides the tangent of the elements. It adds them to the tangent of the increment as blocks scaled by \(1 - \lambda\) and \(\lambda\) (
scaledBy()), on both paths, so that no further matrix is held.The complete pattern. The multi-point-constraint condensation adds entries to the CSR pattern. The assembly is built after them, on the complete pattern, whenever the equation system is (re)built.
Every block of the direct path is a zeroed scratch array, so an entity that is handed its block twice in one assembly (an element, and a body load on it) has each scattered on its own; on the VIJ path the second adds to the first in the same slice. Either way, an entity only adds to or overwrites its block, and never reads it.
Why the direct path is also faster
Three effects:
Nothing has to be cleared. The staging array must be zeroed every Newton iteration; that cost scales with the number of COO pairs, not with
nnz. The direct path clears only the CSR data array, sized bynnz.Nothing has to be re-read. The gather random-accesses the staging array, which can be many times larger than the CSR data the scatter touches instead.
The evaluation itself is not slower, because each entity writes into a small reused scratch block that stays in cache instead of a slab of a much larger array.
The relative sizes of these three effects depend on how many duplicate contributions land per matrix entry for a given discretisation and thread count – measure on the model at hand rather than assuming a fixed ratio.
The one definition of the pattern
DirectCSRAssembler borrows its pattern from an existing
CSRGenerator rather than deriving its own. This is
deliberate: there is exactly one definition of what the CSR pattern is, and the two assembly paths
cannot drift apart. The generator must outlive the assembler.
The offset map is built by binary-searching each (row, col) pair in the borrowed pattern, and stores
the within-row position, which is why 2 bytes suffice: row length is set by the stencil, not by the
problem size, so it stays well within a uint16 even for a wide stencil. A pair that cannot be
mapped, or an offset that does not fit, raises rather than being silently misplaced.
Building only the pattern
CSRGenerator(systemMatrix, patternOnly=True) builds indptr and indices and nothing else.
Two reasons, and the second is the one that decides how large a model can be:
The sort payload halves. With the gather map, the sort element is a key plus an origin index, which pads to 16 bytes per pair; without it, a bare 8-byte key. That array is the largest single allocation in the build.
It removes every 32-bit pair index.
gather_sources,assembly_ptrand the sort element’s origin field all index into the COO list, which is why a full build refuses more thanINT32_MAXpairs. For a discretisation with many duplicate contributions per matrix entry, that pair-count limit can bite well before memory does. WithpatternOnlythe only remaining 32-bit quantity isnnz, which grows only with the CSR result, not with the number of contributions.
A generator built this way, or one that has given its map back via
releaseGatherMap(), raises if asked to
gather. That is deliberate: the alternative is a nogil loop reading released vectors, and a matrix
that is quietly wrong is worse than one that is loudly unavailable.
Dropping the gather map lowers peak memory and shortens the pattern build, since half the sort payload and the 32-bit index arrays it removes never need writing in the first place.
One CSR array, atomic additions
All threads scatter into the one CSR data array of the matrix being assembled, and every addition to an
entry is atomic (#pragma omp atomic), so threads that add to the same entry at the same time cannot
lose a contribution. Nothing else is held per thread but a scratch array the size of one block.
The alternative, a private copy of the CSR data per thread summed at the end, needs no synchronisation,
but it holds nThreads x nnz x 8 bytes and sums all copies once per assembly. Measured on real
assemblies, it was not faster than the atomic additions, and its memory grows with the number of threads
until it exceeds what the direct path saves by not staging the values. So there is one way, the atomic
one:
The cost of an atomic addition is the instruction, not contention. Threads rarely add to the same entry at the same time, so the cost does not grow with the number of threads.
What the atomic additions give up is bit-reproducibility, not correctness. The order in which the threads add to an entry depends on their timing, so the same assembly repeated with more than one thread agrees with itself to round-off, not bit for bit. A Newton iteration whose convergence hinges on the last bit (e.g., a frictional contact that sticks or slips by a hair) may take a different path than the VIJ path does.
Validation
The addressing is validated exactly, without a floating-point tolerance, using an integer trick:
set every value in the staging array to 1 so each CSR entry becomes the count of contributing
pairs, then to its own index k so it becomes the sum of their indices. Both are integers far
inside 253, so a bitwise comparison against
updateCSR() validates the grouping exactly
rather than approximately. A transposition or an off-by-one shows up as an unmistakable mismatch instead
of a judgement call about how large a deviation is acceptable. Sums of such integers are exact in any
order, so the check stays exact with the threads adding in an order set by their timing.
assembleFromVIJ() exists for this purpose:
it pushes a whole staging array through the offset map, so the two paths can be compared on identical
values with the physics held fixed.
Reference
The assembly of the system matrix: where every element, constraint and load writes its block of the tangent, and how the blocks become the global matrix in CSR format.
An implicit solver assembles the tangent from the blocks of all entities: Ke = K[element] hands out the array the
element writes its block into, and SystemMatrixAssembly.assembledMatrix() sums all blocks into the global
matrix. Two ways of summing are implemented behind this one interface, so that neither the solvers nor the entities
know which is in use (see System matrix assembly):
VIJSystemMatrixAssemblyEvery block has its own slice of one long value array (VIJ, or COO, layout), and the duplicates are gathered into CSR afterwards.
DirectCSRSystemMatrixAssemblyEvery block is scattered into CSR right after it was computed; no value array exists.
- class edelweissfe.numerics.systemmatrixassembly.DirectCSRSystemMatrixAssembly(csrGenerator, dofManager, numberOfWorkers)[source]
Scatter directly: every block is scattered into CSR as soon as it is committed, through a map that knows the CSR position of every entry of the VIJ pattern (
DirectCSRAssembler). No value array of the VIJ pattern’s length exists.Every worker writes its blocks into a scratch array of its own, and all workers add them to the one CSR matrix, each addition atomic. The order in which the workers add to an entry depends on their timing, so with more than one worker the matrix agrees from run to run to round-off, not bit for bit.
Every block is a zeroed scratch array: an entity that is handed its block more than once in an assembly (an element, then a body load on it) has each one scattered on its own. Entities with a sparse VIJ pattern of their own (constraints that couple only some of their degrees of freedom, which say so through
couplesAllItsDofs) are scattered entry by entry.- Parameters:
csrGenerator (CSRGenerator) – The CSR pattern, complete (with the entries the multi-point-constraint condensation adds); its gather map is not needed.
dofManager (DofManager) – The DOF manager of the equation system, with its VIJ pattern.
numberOfWorkers (int) – How many threads may write blocks at the same time; one scratch array each.
- Attributes:
- vijArray
Methods
Commit every block, and return the global matrix in CSR format.
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
blocksOfWorker(worker)The blocks worker thread
workerwrites into, while other workers write into theirs.flush()Commit the block handed out last to the matrix, if any.
scaledBy(factor)Blocks that enter this matrix scaled by
factor, seeScaledSystemMatrixBlocks.- assembledMatrix()[source]
Commit every block, and return the global matrix in CSR format.
The matrix is the assembly’s own: the next assembly overwrites its values. Its values may be changed (the Dirichlet boundary conditions, the multi-point-constraint condensation), its pattern must not.
- Returns:
The system matrix.
- Return type:
csr_matrix
- beginAssembly()[source]
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
- blocksOfWorker(worker)[source]
The blocks worker thread
workerwrites into, while other workers write into theirs.- Parameters:
worker (int) – The number of the worker,
0 <= worker <numberOfWorkers.- Returns:
The blocks of this worker.
- Return type:
- assembler
The scatter, for a compiled entity loop that scatters from its own threads.
- needsGatherMap = False
Whether the CSR generator of the pattern must keep its gather map for this assembly (see
CSRGenerator).
- class edelweissfe.numerics.systemmatrixassembly.ScaledSystemMatrixBlocks(target, factor)[source]
Blocks that enter another
SystemMatrixBlocksscaled by a factor: every block is handed out as a zeroed scratch array, and is added, times the factor, to the entity’s block of the target when it is committed.The arc length method assembles the tangents of its dead and its reference load this way into the tangent of the increment, see
NISTPArcLength. Serial only: one scratch array serves all entities.- Parameters:
target (SystemMatrixBlocks) – The blocks the scaled blocks enter.
factor (float) – The factor.
Methods
flush()Commit the block handed out last to the matrix, if any.
- class edelweissfe.numerics.systemmatrixassembly.SystemMatrixAssembly(numberOfWorkers)[source]
The system matrix of an implicit solver while its entities assemble it, and the CSR matrix it becomes.
One assembly per Newton iteration:
beginAssembly(), then every entity writes its block (K[entity], or from a worker thread,K.blocksOfWorker(worker)[entity]), thenassembledMatrix()returns the global matrix. It is built per equation system, after its CSR pattern is complete, seecreateSystemMatrixAssembly().K[entity]hands out the blocks of worker 0, for the entity loops in the calling thread.- Parameters:
numberOfWorkers (int) – How many threads may write blocks at the same time, each through its own
blocksOfWorker().- Attributes:
- vijArray
Methods
Commit every block, and return the global matrix in CSR format.
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
blocksOfWorker(worker)The blocks worker thread
workerwrites into, while other workers write into theirs.flush()Commit the block handed out last to the matrix, if any.
scaledBy(factor)Blocks that enter this matrix scaled by
factor, seeScaledSystemMatrixBlocks.- abstractmethod assembledMatrix()[source]
Commit every block, and return the global matrix in CSR format.
The matrix is the assembly’s own: the next assembly overwrites its values. Its values may be changed (the Dirichlet boundary conditions, the multi-point-constraint condensation), its pattern must not.
- Returns:
The system matrix.
- Return type:
csr_matrix
- abstractmethod beginAssembly()[source]
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
- abstractmethod blocksOfWorker(worker)[source]
The blocks worker thread
workerwrites into, while other workers write into theirs.- Parameters:
worker (int) – The number of the worker,
0 <= worker <numberOfWorkers.- Returns:
The blocks of this worker.
- Return type:
- scaledBy(factor)[source]
Blocks that enter this matrix scaled by
factor, seeScaledSystemMatrixBlocks.- Parameters:
factor (float) – The factor.
- Returns:
The scaled blocks.
- Return type:
- needsGatherMap = True
Whether the CSR generator of the pattern must keep its gather map for this assembly (see
CSRGenerator).
- numberOfWorkers
How many threads may write blocks at the same time.
- vijArray = None
The VIJ value array, for code that works on it directly (e.g., the mass term of a dynamic solver, or a compiled entity loop); None on a path without one.
- class edelweissfe.numerics.systemmatrixassembly.SystemMatrixBlocks[source]
Hands out the blocks of the system matrix:
K[entity]returns the array an entity writes its block of the tangent into, shaped by the entity (seeshapeVIJContribution()). A block that is handed out must be committed to the matrix withflush(); handing out the next block commits the previous one, so whoever loops over entities flushes once after the loop.A block is either the entity’s own place in the matrix, which already holds what was assembled for the entity before, or a zeroed scratch array. So an entity adds its block to the array it is given or overwrites it, and never reads it.
Methods
flush()Commit the block handed out last to the matrix, if any.
- class edelweissfe.numerics.systemmatrixassembly.VIJSystemMatrixAssembly(csrGenerator, dofManager, numberOfWorkers)[source]
Stage, then gather: every block is the entity’s own slice of one value array in VIJ (COO) layout, which is gathered into CSR, summing the duplicates, once all blocks are written.
The blocks of all workers are slices of the same array, and no two entities share a slice, so the workers need nothing of their own. An entity that is handed its block more than once in an assembly (an element, then a body load on it) adds to what is there.
- Parameters:
csrGenerator (CSRGenerator) – The CSR pattern and the gather map.
dofManager (DofManager) – The DOF manager of the equation system, with its VIJ pattern.
numberOfWorkers (int) – How many threads may write blocks at the same time.
- Attributes:
- vijArray
Methods
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
blocksOfWorker(worker)The blocks worker thread
workerwrites into, while other workers write into theirs.flush()Commit the block handed out last to the matrix, if any.
scaledBy(factor)Blocks that enter this matrix scaled by
factor, seeScaledSystemMatrixBlocks.assembledMatrix
- assembledMatrix()[source]
Commit every block, and return the global matrix in CSR format.
The matrix is the assembly’s own: the next assembly overwrites its values. Its values may be changed (the Dirichlet boundary conditions, the multi-point-constraint condensation), its pattern must not.
- Returns:
The system matrix.
- Return type:
csr_matrix
- beginAssembly()[source]
Start a new assembly: drop everything assembled before, and any block that was handed out but not committed (an assembly that was abandoned must not leak into the next).
- blocksOfWorker(worker)[source]
The blocks worker thread
workerwrites into, while other workers write into theirs.- Parameters:
worker (int) – The number of the worker,
0 <= worker <numberOfWorkers.- Returns:
The blocks of this worker.
- Return type:
- needsGatherMap = True
Whether the CSR generator of the pattern must keep its gather map for this assembly (see
CSRGenerator).
CSRGenerator and the C++ engine behind it are described
under Utilities; only the direct-scatter side is documented here.
- class edelweissfe.numerics.csrgeneratorv2.DirectCSRAssembler
Scatters entity blocks straight into a CSR data array, with no VIJ staging array.
The alternative to
CSRGenerator’s stage-then-gather. It borrows an existing pattern rather than deriving its own, so there is exactly one definition of the CSR pattern and the two paths cannot drift apart – andassembleFromVIJ()exists so the addressing can be checked againstCSRGenerator.updateCSRon real models rather than argued about.It assembles into the CSR data array of the borrowed pattern,
csrMatrix, itself: all threads scatter into that one array, each addition atomic. The order in which the threads add to an entry depends on their timing, so the values agree with a serial assembly to round-off, not bit for bit.- Parameters:
generator – A
CSRGeneratorwhose pattern is borrowed. It must outlive this object.systemMatrix – The VIJ system matrix supplying the
I/Jindex arrays the map is built from.numThreads – Threads used for the map build and the zeroing, and how many may scatter at the same time (
0 <= tid < numThreadsinscatterBlock()).
- Attributes:
corePointerAddress of the underlying
CSRDirectAssembler, for a threaded caller in another extension.- csrMatrix
memoryBytesBytes held by the offset map and the entity tables.
Methods
Scatter a VIJ value array into CSR through the map, and return the CSR matrix.
Zero the values of
csrMatrix.registerEntities(mapStarts, nDofs, vijSizes, ...)Give each entity its slice of the offset map, once per connectivity change.
scatterBlock(tid, entity, block)Add one entity's block -- dense or sparse, as registered -- from a scratch buffer to
csrMatrix.- assembleFromVIJ(V)
Scatter a VIJ value array into CSR through the map, and return the CSR matrix.
Equivalence path for validation and measurement. The fused assembly hands each entity’s block in directly and never builds
V.
- beginAssembly()
Zero the values of
csrMatrix. Call once before the entity loop.
- registerEntities(mapStarts, nDofs, vijSizes, couplesAllItsDofs)
Give each entity its slice of the offset map, once per connectivity change.
mapStarts[e]is entity e’s offset into the VIJ ordering – the same value the DofManager already records inidcsOfHigherOrderEntitiesInVIJ–,nDofs[e]its local DOF count,vijSizes[e]the number of entries it contributes (getVIJContributionSize()), andcouplesAllItsDofs[e]the layout of its block it declares (couplesAllItsDofs): nonzero for a dense block, column-major, ofnDofs[e]**2entries; zero for a sparse one, the values of the (I, J) pairs the entity declared, whichscatterBlock()scatters entry by entry. The layout is not inferred from the number of entries, since a sparse pattern can have exactlynDofs[e]**2of them.
- scatterBlock(tid, entity, block)
Add one entity’s block – dense or sparse, as registered – from a scratch buffer to
csrMatrix.Every addition is atomic, so any number of threads scatter at the same time, as long as no two concurrent callers pass the same
tid(0 <= tid < numThreads), which selects the caller’s own row scratch. Releases the GIL, so the workers of a threaded entity loop scatter side by side; seeDirectCSRSystemMatrixAssembly.
- corePointer
Address of the underlying
CSRDirectAssembler, for a threaded caller in another extension.EdelweissMeshfree’s particle kernel calls
scatterBlockfrom inside itsprange, which cannot go through Python. It re-declares the C++ class (fromedelweissfe.numerics.get_include()) and casts this address back, so the scatter – including the column-major traversal and its loop order – exists in exactly one place.The assembler must outlive any caller holding this.
- memoryBytes
Bytes held by the offset map and the entity tables.
The CSR pattern and data array are not counted: they belong to the borrowed generator, whose
CSRGenerator.memoryBytescounts them.
- class edelweissfe.numerics.csrgeneratorv2.AliasedCSRMatrix(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)
The csr_matrix returned by
CSRGenerator.updateInPlace().Its
data/indices/indptrbuffers are owned by the generator’s C++ core, which rewritesdatain place on every subsequentupdateInPlacecall via a gather/scatter map fixed once at construction time. Structurally mutating this matrix (eliminate_zeros(),prune(),sum_duplicates(),resize(), or reassigning.data/.indices/.indptrto arrays of a different length) would silently desynchronize that fixed map from the (now compacted/reshaped) matrix – every subsequent update would then write numerically correct values into the wrong(row, col)slots, with no error or warning. See GitHub issue #72.This subclass turns that into a loud failure instead of silent corruption. If you need to reduce/reshape the pattern for a one-off use, copy the matrix first –
.copy()(here and viaCSRGenerator.updateCSR()) always returns a plain, unrestrictedcsr_matrix.The guard only applies once
CSRGeneratormarks construction complete (_locked = True): scipy’s owncsr_matrix.__init__callsself.prune()internally as part of its format check, which must go through unhindered.- Attributes:
TTranspose.
- dtype
formatFormat string for matrix.
has_canonical_formatWhether the array/matrix has sorted indices and no duplicates
has_sorted_indicesWhether the indices are sorted
- imag
mTMatrix transpose.
- ndim
nnzNumber of stored values, including explicit zeros.
- real
shapeShape of the matrix
sizeNumber of stored values.
Methods
arcsin()Element-wise arcsin.
arcsinh()Element-wise arcsinh.
arctan()Element-wise arctan.
arctanh()Element-wise arctanh.
argmax([axis, out, explicit])Return indices of maximum elements along an axis.
argmin([axis, out, explicit])Return indices of minimum elements along an axis.
asformat(format[, copy])Return this array/matrix in the passed format.
asfptype()Upcast matrix to a floating point format (if necessary)
astype(dtype[, casting, copy])Cast the array/matrix elements to a specified type.
ceil()Element-wise ceil.
check_format([full_check])Check whether the array/matrix respects the CSR or CSC format.
conj([copy])Element-wise complex conjugation.
conjugate([copy])Element-wise complex conjugation.
count_nonzero([axis])Number of non-zero entries.
deg2rad()Element-wise deg2rad.
diagonal([k])Returns the kth diagonal of the array/matrix.
dot(other)Ordinary dot product.
expm1()Element-wise expm1.
floor()Element-wise floor.
getH()Return the Hermitian transpose of this matrix.
get_shape()Get the shape of the matrix
getcol(j)Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).
getformat()Matrix storage format
getmaxprint()Maximum number of elements to display when printed.
getnnz([axis])Number of stored values, including explicit zeros.
getrow(i)Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).
log1p()Element-wise log1p.
max([axis, out, explicit])Return the maximum of the array/matrix or maximum along an axis.
maximum(other)Element-wise maximum between this and another array/matrix.
mean([axis, dtype, out])Compute the arithmetic mean along the specified axis.
min([axis, out, explicit])Return the minimum of the array/matrix or maximum along an axis.
minimum(other)Element-wise minimum between this and another array/matrix.
multiply(other)Element-wise multiplication by another array/matrix.
nanmax([axis, out, explicit])Return the maximum, ignoring any Nans, along an axis.
nanmin([axis, out, explicit])Return the minimum, ignoring any Nans, along an axis.
nonzero()Nonzero indices of the array/matrix.
power(n[, dtype])This function performs element-wise power.
rad2deg()Element-wise rad2deg.
reshape(self, shape[, order, copy])Gives a new shape to a sparse array/matrix without changing its data.
rint()Element-wise rint.
set_shape(shape)Set the shape of the matrix in-place
setdiag(values[, k])Set diagonal or off-diagonal elements of the array/matrix.
sign()Element-wise sign.
sin()Element-wise sin.
sinh()Element-wise sinh.
sort_indices()Sort the indices of this array/matrix in place.
sorted_indices()Return a copy of this array/matrix with sorted indices.
sqrt()Element-wise sqrt.
sum([axis, dtype, out])Sum the array/matrix elements over a given axis.
tan()Element-wise tan.
tanh()Element-wise tanh.
toarray([order, out])Return a dense ndarray representation of this sparse array/matrix.
tobsr([blocksize, copy])Convert this array/matrix to Block Sparse Row format.
tocoo([copy])Convert this array/matrix to COOrdinate format.
tocsc([copy])Convert this array/matrix to Compressed Sparse Column format.
tocsr([copy])Convert this array/matrix to Compressed Sparse Row format.
todense([order, out])Return a dense representation of this sparse matrix.
todia([copy])Convert this array/matrix to sparse DIAgonal format.
todok([copy])Convert this array/matrix to Dictionary Of Keys format.
tolil([copy])Convert this array/matrix to List of Lists format.
trace([offset])Returns the sum along diagonals of the sparse array/matrix.
transpose([axes, copy])Reverses the dimensions of the sparse array/matrix.
trunc()Element-wise trunc.
copy
eliminate_zeros
prune
resize
sum_duplicates
- copy()
Returns a copy of this array/matrix.
No data/indices will be shared between the returned value and current array/matrix.
- Returns:
A copy of this array/matrix.
- Return type:
sparse array/matrix
- eliminate_zeros()
Remove zero entries from the array/matrix.
This is an in place operation.
- prune()
Remove empty space after all non-zero elements.
- resize(*shape)
Resize the array/matrix in-place to dimensions given by
shape.Any elements that lie within the new shape will remain at the same indices, while non-zero elements lying outside the new shape are removed.
- Parameters:
*shape (int) – number of rows and columns in the new array/matrix
Notes
The semantics are not identical to numpy.ndarray.resize or numpy.resize. Here, the same data will be maintained at each index before and after reshape, if that index is within the new bounds. In numpy, resizing maintains contiguity of the array, moving elements around in the logical array but not within a flattened representation.
We give no guarantees about whether the underlying data attributes (arrays, etc.) will be modified in place or replaced with new objects.
- sum_duplicates()
Eliminate duplicate entries by adding them together.
This is an in place operation.