Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

r""" 

Sparse Matrices over a general ring 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: M = MatrixSpace(QQ['x'],2,3,sparse=True); M 

Full MatrixSpace of 2 by 3 sparse matrices over Univariate Polynomial Ring in x over Rational Field 

sage: a = M(range(6)); a 

[0 1 2] 

[3 4 5] 

sage: b = M([x^n for n in range(6)]); b 

[ 1 x x^2] 

[x^3 x^4 x^5] 

sage: a * b.transpose() 

[ 2*x^2 + x 2*x^5 + x^4] 

[ 5*x^2 + 4*x + 3 5*x^5 + 4*x^4 + 3*x^3] 

sage: pari(a)*pari(b.transpose()) 

[2*x^2 + x, 2*x^5 + x^4; 5*x^2 + 4*x + 3, 5*x^5 + 4*x^4 + 3*x^3] 

sage: c = copy(b); c 

[ 1 x x^2] 

[x^3 x^4 x^5] 

sage: c[0,0] = 5; c 

[ 5 x x^2] 

[x^3 x^4 x^5] 

sage: b[0,0] 

1 

sage: c.dict() 

{(0, 0): 5, (0, 1): x, (0, 2): x^2, (1, 0): x^3, (1, 1): x^4, (1, 2): x^5} 

sage: c.list() 

[5, x, x^2, x^3, x^4, x^5] 

sage: c.rows() 

[(5, x, x^2), (x^3, x^4, x^5)] 

sage: TestSuite(c).run() 

sage: d = c.change_ring(CC['x']); d 

[5.00000000000000 x x^2] 

[ x^3 x^4 x^5] 

sage: latex(c) 

\left(\begin{array}{rrr} 

5 & x & x^{2} \\ 

x^{3} & x^{4} & x^{5} 

\end{array}\right) 

sage: c.sparse_rows() 

[(5, x, x^2), (x^3, x^4, x^5)] 

sage: d = c.dense_matrix(); d 

[ 5 x x^2] 

[x^3 x^4 x^5] 

sage: parent(d) 

Full MatrixSpace of 2 by 3 dense matrices over Univariate Polynomial Ring in x over Rational Field 

sage: c.sparse_matrix() is c 

True 

sage: c.is_sparse() 

True 

""" 

from __future__ import absolute_import 

  

cimport sage.matrix.matrix as matrix 

cimport sage.matrix.matrix_sparse as matrix_sparse 

cimport sage.structure.element 

from sage.structure.element cimport ModuleElement 

  

import sage.misc.misc as misc 

  

cdef class Matrix_generic_sparse(matrix_sparse.Matrix_sparse): 

r""" 

Generic sparse matrix. 

  

The ``Matrix_generic_sparse`` class derives from 

:class:`~sage.matrix.matrix_sparse.Matrix_sparse`, and defines functionality 

for sparse matrices over any base ring. A generic sparse matrix is 

represented using a dictionary whose keys are pairs of integers `(i,j)` and 

values in the base ring. The values of the dictionary must never be zero. 

  

EXAMPLES:: 

  

sage: R.<a,b> = PolynomialRing(ZZ,'a,b') 

sage: M = MatrixSpace(R,5,5,sparse=True) 

sage: M({(0,0):5*a+2*b, (3,4): -a}) 

[5*a + 2*b 0 0 0 0] 

[ 0 0 0 0 0] 

[ 0 0 0 0 0] 

[ 0 0 0 0 -a] 

[ 0 0 0 0 0] 

sage: M(3) 

[3 0 0 0 0] 

[0 3 0 0 0] 

[0 0 3 0 0] 

[0 0 0 3 0] 

[0 0 0 0 3] 

sage: V = FreeModule(ZZ, 5,sparse=True) 

sage: m = M([V({0:3}), V({2:2, 4:-1}), V(0), V(0), V({1:2})]) 

sage: m 

[ 3 0 0 0 0] 

[ 0 0 2 0 -1] 

[ 0 0 0 0 0] 

[ 0 0 0 0 0] 

[ 0 2 0 0 0] 

  

.. NOTE:: 

  

The datastructure can potentially be optimized. Firstly, as noticed in 

:trac:`17663`, we lose time in using 2-tuples to store indices. 

Secondly, there is no fast way to access non-zero elements in a given 

row/column. 

""" 

def __cinit__(self, parent, entries=0, coerce=True, copy=True): 

self._entries = {} # crucial so that pickling works 

  

def __init__(self, parent, entries=None, coerce=True, copy=True): 

r""" 

Create a sparse matrix over the given base ring. 

  

INPUT: 

  

- ``parent`` -- a matrix space 

  

- ``entries`` -- can be one of the following: 

  

* a Python dictionary whose items have the 

form ``(i, j): x``, where ``0 <= i < nrows``, 

``0 <= j < ncols``, and ``x`` is coercible to 

an element of the base ring. 

The ``i,j`` entry of ``self`` is 

set to ``x``. The ``x``'s can be ``0``. 

* Alternatively, entries can be a list of *all* 

the entries of the sparse matrix, read 

row-by-row from top to bottom (so they would 

be mostly 0). 

  

- ``coerce`` (default: ``True``) -- whether the entries 

should be coerced into the base ring before being 

entered into the matrix 

  

- ``copy`` (default: ``True``) -- whether the list or 

dictionary ``entries`` (not the single entries 

themselves!) should be copied before being 

entered into the matrix 

  

TESTS:: 

  

sage: R.<a> = PolynomialRing(ZZ,'a') 

sage: M = MatrixSpace(R,2,3,sparse=True) 

sage: m = M([4,1,0,0,0,2]); m 

[4 1 0] 

[0 0 2] 

sage: m2 = copy(m) 

sage: m2[0,0] = -1 

sage: m[0,0] 

4 

sage: loads(dumps(m)) == m 

True 

  

sage: R2.<a,b> = PolynomialRing(QQ) 

sage: M2 = MatrixSpace(R2,2,3,sparse=True) 

sage: M2(m) 

[4 1 0] 

[0 0 2] 

sage: M2.has_coerce_map_from(M) 

True 

  

sage: M3 = M2.change_ring(R2.fraction_field()) 

sage: M3.has_coerce_map_from(M2) 

True 

  

  

Check that it is not possible to use wrong indices:: 

  

sage: M = MatrixSpace(R,2,2,sparse=True) 

sage: M({(3,0): 1}) 

Traceback (most recent call last): 

... 

IndexError: matrix indices (3, 0) out of range 

  

sage: M({(0,-3): 1}) 

Traceback (most recent call last): 

... 

IndexError: matrix indices (0, -3) out of range 

  

But negative indices are valid:: 

  

sage: M({(-1,-1): 1}) 

[0 0] 

[0 1] 

""" 

matrix.Matrix.__init__(self, parent) 

R = self._base_ring 

self._zero = R.zero() 

  

if entries is None or not entries: 

# be careful here. We might get entries set to be an empty list 

# because of the code implemented in matrix_space.MatrixSpace 

# So the condition 

# if entries is None or not entries: 

# ... 

# is valid. But 

# if entries is None or entries == 0: 

# ... 

# is not! 

return 

  

cdef Py_ssize_t i, j, k 

  

if not isinstance(entries, dict): 

# assume that entries is a scalar 

x = R(entries) 

entries = {} 

if self._nrows != self._ncols: 

raise TypeError("scalar matrix must be square") 

for i from 0 <= i < self._nrows: 

entries[(i,i)] = x 

  

if coerce: 

v = {} 

for key, x in entries.iteritems(): 

i,j = key 

if i < 0: i += self._nrows 

if j < 0: j += self._ncols 

if (i < 0 or i >= self._nrows or j < 0 or j >= self._ncols): 

raise IndexError("matrix indices {} out of range".format(key)) 

w = R(x) 

if w: 

v[(i,j)] = w 

entries = v 

else: 

# Here we do not pay attention to the indices. We just check that it 

# *converts* to a pair of Py_ssize_t. In particular it is possible 

# to do: 

# 

# sage: R = QQ['a','b'] 

# sage: M = MatrixSpace(R, 3, 3, sparse=True) 

# sage: m = M({(Zmod(3)(1), Zmod(6)(2)): R.one()}, coerce=False) 

# 

# and this is bad since: 

# 

# sage: list(map(type,m.dict().keys()[0])) 

# [<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>, 

# <type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>] 

# 

# But not that setting coerce=False is advanced usage and we assume 

# that in such case the user knows what he/she is doing. 

if copy: 

entries = entries.copy() 

for key in entries.keys(): 

i,j = key 

if i < 0: i += self._nrows 

if j < 0: j += self._ncols 

if (i < 0 or i >= self._nrows or j < 0 or j >= self._ncols): 

raise IndexError("matrix indices {} out of range".format(key)) 

if not entries[key]: 

del entries[key] 

  

self._entries = entries 

  

def __nonzero__(self): 

r""" 

Test wether this matrix is non-zero. 

  

TESTS:: 

  

sage: R.<a,b> = Zmod(5)['a','b'] 

sage: m = matrix(R,3,4,sparse=True) 

sage: bool(m) # indirect doctest 

False 

sage: m[0,3] = 1 

sage: bool(m) # indirect doctest 

True 

sage: m[0,3] = 0 # indirect doctest 

sage: bool(m) 

False 

sage: m.is_zero() # indirect doctest 

True 

""" 

return bool(self._entries) 

  

cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, value): 

if not value: 

try: 

del self._entries[(i,j)] 

except KeyError: 

pass 

else: 

self._entries[(i,j)] = value 

  

cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j): 

return self._entries.get((i,j), self._zero) 

  

def _pickle(self): 

version = 0 

return self._entries, version 

  

def _unpickle(self, data, int version): 

""" 

EXAMPLES:: 

  

sage: a = matrix([[1,10],[3,4]],sparse=True); a 

[ 1 10] 

[ 3 4] 

sage: loads(dumps(a)) == a 

True 

""" 

if version == 0: 

self._entries = data 

self._zero = self._base_ring(0) 

else: 

raise RuntimeError("unknown matrix version (=%s)"%version) 

  

######################################################################## 

# LEVEL 2 functionality 

# x * cdef _add_ 

# * cdef _mul_ 

# * cpdef _cmp_ 

# * __neg__ 

# * __invert__ 

# x * __copy__ 

# * _multiply_classical 

# x * _list -- copy of the list of underlying elements 

# x * _dict -- copy of the sparse dictionary of underlying elements 

######################################################################## 

  

cpdef _add_(self, _other): 

""" 

EXAMPLES:: 

  

sage: a = matrix([[1,10],[3,4]],sparse=True); a 

[ 1 10] 

[ 3 4] 

sage: a+a 

[ 2 20] 

[ 6 8] 

  

:: 

  

sage: a = matrix([[1,10,-5/3],[2/8,3,4]],sparse=True); a 

[ 1 10 -5/3] 

[ 1/4 3 4] 

sage: a+a 

[ 2 20 -10/3] 

[ 1/2 6 8] 

""" 

# Compute the sum of two sparse matrices. 

# This is complicated because of how we represent sparse matrices. 

# Algorithm: 

# 1. Sort both entry coefficient lists. 

# 2. March through building a new list, adding when the two i,j are the same. 

cdef Py_ssize_t i, j, len_v, len_w 

cdef Matrix_generic_sparse other 

other = <Matrix_generic_sparse> _other 

cdef list v = sorted(self._entries.items()) 

cdef list w = sorted(other._entries.items()) 

s = {} 

i = 0 # pointer into self 

j = 0 # pointer into other 

len_v = len(v) 

len_w = len(w) 

while i < len_v and j < len_w: 

vi = v[i][0] 

wj = w[j][0] 

if vi < wj: 

s[vi] = v[i][1] 

i += 1 

elif vi > wj: 

s[wj] = w[j][1] 

j += 1 

else: # equal 

sm = v[i][1] + w[j][1] 

if sm: 

s[vi] = sm 

i += 1 

j += 1 

while i < len(v): 

s[v[i][0]] = v[i][1] 

i += 1 

while j < len(w): 

s[w[j][0]] = w[j][1] 

j += 1 

  

cdef Matrix_generic_sparse A 

A = Matrix_generic_sparse.__new__(Matrix_generic_sparse, self._parent, 0,0,0) 

matrix.Matrix.__init__(A, self._parent) 

A._entries = s 

A._zero = self._zero 

A._base_ring = self._base_ring 

return A 

  

def __copy__(self): 

A = self.__class__(self._parent, self._entries, copy = True, coerce=False) 

if self._subdivisions is not None: 

A.subdivide(*self.subdivisions()) 

return A 

  

  

def _list(self): 

""" 

Return all entries of self as a list of numbers of rows times 

number of columns entries. 

""" 

cdef Py_ssize_t i,j 

cdef list v = self.fetch('list') 

if v is None: 

v = [self._zero]*(self._nrows * self._ncols) 

for (i,j), x in self._entries.iteritems(): 

v[i*self._ncols + j] = x 

self.cache('list', v) 

return v 

  

def _dict(self): 

""" 

Return the underlying dictionary of self. 

  

This is used in comparisons. 

  

TESTS:: 

  

sage: R.<a,b> = Zmod(6)[] 

sage: M = MatrixSpace(R, 3, 4) 

sage: m = M({(0,3): a+3*b*a, (1,1): -b}) 

sage: m == m # indirect doctest 

True 

sage: M(0) == m # indirect doctest 

False 

""" 

return self._entries 

  

######################################################################## 

# LEVEL 3 functionality -- matrix windows, etc. 

######################################################################## 

  

def _nonzero_positions_by_row(self, copy=True): 

r""" 

TESTS:: 

  

sage: R.<a> = PolynomialRing(Zmod(8), 'a') 

sage: M = MatrixSpace(R,4,3,sparse=True) 

sage: m = M({(3,0): 1, (3,1): 2*a^2 + 1, (2,0): -1, (0,1): -2}) 

sage: m._nonzero_positions_by_row() 

[(0, 1), (2, 0), (3, 0), (3, 1)] 

""" 

cdef list v = self.fetch('nonzero_positions') 

if v is None: 

v = self._entries.keys() 

v.sort() 

self.cache('nonzero_positions', v) 

if copy: 

return v[:] 

return v 

  

def _nonzero_positions_by_column(self, copy=True): 

r""" 

TESTS:: 

  

sage: R.<a> = PolynomialRing(Zmod(8), 'a') 

sage: M = MatrixSpace(R,4,3,sparse=True) 

sage: m = M({(3,0): 1, (3,1): 2*a^2 + 1, (2,0): -1, (0,1): -2}) 

sage: m._nonzero_positions_by_column() 

[(2, 0), (3, 0), (0, 1), (3, 1)] 

""" 

cdef list v = self.fetch('nonzero_positions_by_column') 

if v is None: 

v = self._entries.keys() 

v.sort(key=lambda x: (x[1], x[0])) 

self.cache('nonzero_positions_by_column', v) 

if copy: 

return v[:] 

return v 

  

  

#################################################################################### 

# Various helper functions 

#################################################################################### 

  

def Matrix_sparse_from_rows(X): 

""" 

INPUT: 

  

- ``X`` - nonempty list of SparseVector rows 

  

  

OUTPUT: Sparse_matrix with those rows. 

  

EXAMPLES:: 

  

sage: V = VectorSpace(QQ,20,sparse=True) 

sage: v = V(0) 

sage: v[9] = 4 

sage: from sage.matrix.matrix_generic_sparse import Matrix_sparse_from_rows 

sage: Matrix_sparse_from_rows([v]) 

[0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0] 

sage: Matrix_sparse_from_rows([v, v, v, V(0)]) 

[0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0] 

[0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0] 

[0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0] 

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 

""" 

cdef Py_ssize_t i, j 

  

if not isinstance(X, (list, tuple)): 

raise TypeError("X (=%s) must be a list or tuple"%X) 

if len(X) == 0: 

raise ArithmeticError("X must be nonempty") 

  

from . import matrix_space 

entries = {} 

R = X[0].base_ring() 

ncols = X[0].degree() 

for i from 0 <= i < len(X): 

for j, x in X[i].iteritems(): 

entries[(i,j)] = x 

M = matrix_space.MatrixSpace(R, len(X), ncols, sparse=True) 

return M(entries, coerce=False, copy=False)