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

""" 

Weighted Integer Vectors 

 

AUTHORS: 

 

- Mike Hansen (2007): initial version, ported from MuPAD-Combinat 

- Nicolas M. Thiery (2010-10-30): WeightedIntegerVectors(weights) + cleanup 

""" 

#***************************************************************************** 

# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com> 

# 2010 Nicolas M. Thiery <nthiery at users.sf.net> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function, absolute_import 

 

from sage.structure.unique_representation import UniqueRepresentation 

from sage.structure.parent import Parent 

from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets 

from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets 

from sage.categories.sets_with_grading import SetsWithGrading 

from sage.sets.disjoint_union_enumerated_sets import DisjointUnionEnumeratedSets 

from sage.rings.integer import Integer 

from sage.rings.all import ZZ 

from sage.combinat.integer_vector import IntegerVector 

from sage.combinat.words.word import Word 

from sage.combinat.permutation import Permutation 

 

 

class WeightedIntegerVectors(Parent, UniqueRepresentation): 

r""" 

The class of integer vectors of `n` weighted by ``weight``, that is, the 

nonnegative integer vectors `(v_1, \ldots, v_{\ell})` 

satisfying `\sum_{i=1}^{\ell} v_i w_i = n` where `\ell` is 

``length(weight)`` and `w_i` is ``weight[i]``. 

 

INPUT: 

 

- ``n`` -- a non negative integer (optional) 

 

- ``weight`` -- a tuple (or list or iterable) of positive integers 

 

EXAMPLES:: 

 

sage: WeightedIntegerVectors(8, [1,1,2]) 

Integer vectors of 8 weighted by [1, 1, 2] 

sage: WeightedIntegerVectors(8, [1,1,2]).first() 

[0, 0, 4] 

sage: WeightedIntegerVectors(8, [1,1,2]).last() 

[8, 0, 0] 

sage: WeightedIntegerVectors(8, [1,1,2]).cardinality() 

25 

sage: WeightedIntegerVectors(8, [1,1,2]).random_element() 

[1, 1, 3] 

 

sage: WeightedIntegerVectors([1,1,2]) 

Integer vectors weighted by [1, 1, 2] 

sage: WeightedIntegerVectors([1,1,2]).cardinality() 

+Infinity 

sage: WeightedIntegerVectors([1,1,2]).first() 

[0, 0, 0] 

 

TESTS:: 

 

sage: WeightedIntegerVectors(None,None) 

Traceback (most recent call last): 

... 

ValueError: the weights must be specified 

 

.. TODO:: 

 

Should the order of the arguments ``n`` and ``weight`` be 

exchanged to simplify the logic? 

""" 

@staticmethod 

def __classcall_private__(cls, n=None, weight=None): 

""" 

Normalize inputs to ensure a unique representation. 

 

TESTS:: 

 

sage: W = WeightedIntegerVectors(8, [1,1,2]) 

sage: W2 = WeightedIntegerVectors(int(8), (1,1,2)) 

sage: W is W2 

True 

""" 

if weight is None: 

if n is None: 

raise ValueError("the weights must be specified") 

if n in ZZ: 

weight = (n,) 

else: 

weight = tuple(n) 

n = None 

 

weight = tuple(weight) 

if n is None: 

return WeightedIntegerVectors_all(weight) 

 

return super(WeightedIntegerVectors, cls).__classcall__(cls, n, weight) 

 

def __init__(self, n, weight): 

""" 

TESTS:: 

 

sage: WIV = WeightedIntegerVectors(8, [1,1,2]) 

sage: TestSuite(WIV).run() 

""" 

self._n = n 

self._weights = weight 

Parent.__init__(self, category=FiniteEnumeratedSets()) 

 

Element = IntegerVector 

 

def _element_constructor_(self, lst): 

""" 

Construct an element of ``self`` from ``lst``. 

 

EXAMPLES:: 

 

sage: WIV = WeightedIntegerVectors(3, [2,1,1]) 

sage: elt = WIV([1, 2, 0]); elt 

[1, 2, 0] 

sage: elt.parent() is WIV 

True 

""" 

if isinstance(lst, IntegerVector): 

if lst.parent() is self: 

return lst 

raise ValueError("cannot convert %s into %s" % (lst, self)) 

return self.element_class(self, lst) 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: WeightedIntegerVectors(8, [1,1,2]) 

Integer vectors of 8 weighted by [1, 1, 2] 

""" 

return "Integer vectors of %s weighted by %s" % (self._n, list(self._weights)) 

 

def __contains__(self, x): 

""" 

EXAMPLES:: 

 

sage: [] in WeightedIntegerVectors(0, []) 

True 

sage: [] in WeightedIntegerVectors(1, []) 

False 

sage: [3,0,0] in WeightedIntegerVectors(6, [2,1,1]) 

True 

sage: [1] in WeightedIntegerVectors(1, [1]) 

True 

sage: [1] in WeightedIntegerVectors(2, [2]) 

True 

sage: [2] in WeightedIntegerVectors(4, [2]) 

True 

sage: [2, 0] in WeightedIntegerVectors(4, [2, 2]) 

True 

sage: [2, 1] in WeightedIntegerVectors(4, [2, 2]) 

False 

sage: [2, 1] in WeightedIntegerVectors(6, [2, 2]) 

True 

sage: [2, 1, 0] in WeightedIntegerVectors(6, [2, 2]) 

False 

sage: [0] in WeightedIntegerVectors(0, []) 

False 

""" 

if not isinstance(x, (list, IntegerVector, Permutation)): 

return False 

if len(self._weights) != len(x): 

return False 

s = 0 

for i, val in enumerate(x): 

if (not isinstance(val, (int, Integer))) and (val not in ZZ): 

return False 

s += x[i] * self._weights[i] 

return s == self._n 

 

def _recfun(self, n, l): 

""" 

EXAMPLES:: 

 

sage: w = WeightedIntegerVectors(3, [2,1,1]) 

sage: list(w._recfun(3, [1,1,2])) 

[[0, 1, 1], [1, 0, 1], [0, 3, 0], [1, 2, 0], [2, 1, 0], [3, 0, 0]] 

""" 

w = l[-1] 

l = l[:-1] 

if l == []: 

d = int(n) // int(w) 

if n % w == 0: 

yield [d] 

# Otherwise: bad branch 

return 

 

for d in range(int(n) // int(w), -1, -1): 

for x in self._recfun(n - d * w, l): 

yield x + [d] 

 

def __iter__(self): 

""" 

TESTS:: 

 

sage: WeightedIntegerVectors(7, [2,2]).list() 

[] 

sage: WeightedIntegerVectors(3, [2,1,1]).list() 

[[1, 0, 1], [1, 1, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0]] 

 

:: 

 

sage: ivw = [ WeightedIntegerVectors(k, [1,1,1]) for k in range(11) ] 

sage: iv = [ IntegerVectors(k, 3) for k in range(11) ] 

sage: all(sorted(map(list, iv[k])) == sorted(map(list, ivw[k])) for k in range(11)) 

True 

 

:: 

 

sage: ivw = [ WeightedIntegerVectors(k, [2,3,7]) for k in range(11) ] 

sage: all(i.cardinality() == len(i.list()) for i in ivw) 

True 

""" 

if not self._weights: 

if self._n == 0: 

yield self.element_class(self, []) 

return 

 

perm = Word(self._weights).standard_permutation() 

perm = [len(self._weights)-i for i in perm] 

l = [x for x in sorted(self._weights, reverse=True)] 

for x in iterator_fast(self._n, l): 

yield self.element_class(self, [x[i] for i in perm]) 

#.action(x) 

#_left_to_right_multiply_on_right(Permutation(x)) 

 

 

class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets): 

r""" 

Set of weighted integer vectors. 

 

EXAMPLES:: 

 

sage: W = WeightedIntegerVectors([3,1,1,2,1]); W 

Integer vectors weighted by [3, 1, 1, 2, 1] 

sage: W.cardinality() 

+Infinity 

 

sage: W12 = W.graded_component(12) 

sage: W12.an_element() 

[4, 0, 0, 0, 0] 

sage: W12.last() 

[0, 12, 0, 0, 0] 

sage: W12.cardinality() 

441 

sage: for w in W12: print(w) 

[4, 0, 0, 0, 0] 

[3, 0, 0, 1, 1] 

[3, 0, 1, 1, 0] 

... 

[0, 11, 1, 0, 0] 

[0, 12, 0, 0, 0] 

""" 

def __init__(self, weight): 

""" 

TESTS:: 

 

sage: C = WeightedIntegerVectors([2,1,3]) 

sage: C.category() 

Category of facade infinite enumerated sets with grading 

sage: TestSuite(C).run() 

""" 

self._weights = weight 

from sage.sets.all import Family, NonNegativeIntegers 

# Use "partial" to make the basis function (with the weights 

# argument specified) pickleable. Otherwise, it seems to 

# cause problems... 

from functools import partial 

F = Family(NonNegativeIntegers(), partial(WeightedIntegerVectors, weight=weight)) 

cat = (SetsWithGrading(), InfiniteEnumeratedSets()) 

DisjointUnionEnumeratedSets.__init__(self, F, facade=True, keepkey=False, 

category=cat) 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: WeightedIntegerVectors([2,1,3]) 

Integer vectors weighted by [2, 1, 3] 

""" 

return "Integer vectors weighted by %s" % list(self._weights) 

 

def __contains__(self, x): 

""" 

EXAMPLES:: 

 

sage: [] in WeightedIntegerVectors([]) 

True 

sage: [3,0,0] in WeightedIntegerVectors([2,1,1]) 

True 

sage: [3,0] in WeightedIntegerVectors([2,1,1]) 

False 

sage: [3,-1,0] in WeightedIntegerVectors([2,1,1]) 

False 

""" 

return (isinstance(x, (list, IntegerVector, Permutation)) 

and len(x) == len(self._weights) 

and all(i in ZZ and i >= 0 for i in x)) 

 

def subset(self, size = None): 

""" 

EXAMPLES:: 

 

sage: C = WeightedIntegerVectors([2,1,3]) 

sage: C.subset(4) 

Integer vectors of 4 weighted by [2, 1, 3] 

""" 

if size is None: 

return self 

return self._family[size] 

 

def grading(self, x): # or degree / grading 

""" 

EXAMPLES:: 

 

sage: C = WeightedIntegerVectors([2,1,3]) 

sage: C.grading((2,1,1)) 

8 

""" 

return sum(exp * deg for exp, deg in zip(x, self._weights)) 

 

 

def iterator_fast(n, l): 

""" 

Iterate over all ``l`` weighted integer vectors with total weight ``n``. 

 

INPUT: 

 

- ``n`` -- an integer 

- ``l`` -- the weights in weakly decreasing order 

 

EXAMPLES:: 

 

sage: from sage.combinat.integer_vector_weighted import iterator_fast 

sage: list(iterator_fast(3, [2,1,1])) 

[[1, 1, 0], [1, 0, 1], [0, 3, 0], [0, 2, 1], [0, 1, 2], [0, 0, 3]] 

sage: list(iterator_fast(2, [2])) 

[[1]] 

 

Test that :trac:`20491` is fixed:: 

 

sage: type(list(iterator_fast(2, [2]))[0][0]) 

<... 'sage.rings.integer.Integer'> 

""" 

if n < 0: 

return 

 

zero = ZZ.zero() 

one = ZZ.one() 

 

if not l: 

if n == 0: 

yield [] 

return 

if len(l) == 1: 

if n % l[0] == 0: 

yield [n // l[0]] 

return 

 

k = 0 

cur = [n // l[k] + one] 

rem = n - cur[-1] * l[k] # Amount remaining 

while cur: 

cur[-1] -= one 

rem += l[k] 

if rem == zero: 

yield cur + [zero] * (len(l) - len(cur)) 

elif cur[-1] < zero or rem < zero: 

rem += cur.pop() * l[k] 

k -= 1 

elif len(l) == len(cur) + 1: 

if rem % l[-1] == zero: 

yield cur + [rem // l[-1]] 

else: 

k += 1 

cur.append(rem // l[k] + one) 

rem -= cur[-1] * l[k] 

 

 

def WeightedIntegerVectors_nweight(n, weight): 

""" 

Deprecated in :trac:`12453`. Use :class:`WeightedIntegerVectors` instead. 

 

EXAMPLES:: 

 

sage: sage.combinat.integer_vector_weighted.WeightedIntegerVectors_nweight(7, [2,2]) 

doctest:...: DeprecationWarning: this class is deprecated. Use WeightedIntegerVectors instead 

See http://trac.sagemath.org/12453 for details. 

Integer vectors of 7 weighted by [2, 2] 

""" 

from sage.misc.superseded import deprecation 

deprecation(12453, 'this class is deprecated. Use WeightedIntegerVectors instead') 

return WeightedIntegerVectors(n, weight) 

 

from sage.structure.sage_object import register_unpickle_override 

register_unpickle_override('sage.combinat.integer_vector_weighted', 'WeightedIntegerVectors_nweight', WeightedIntegerVectors)