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

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

# -*- coding: utf-8 -*- 

from __future__ import print_function, division 

 

from sympy.core.basic import Basic 

from sympy.core.compatibility import is_sequence, as_int, string_types 

from sympy.core.expr import Expr 

from sympy.core.symbol import Symbol, symbols as _symbols 

from sympy.core.sympify import CantSympify 

from mpmath import isint 

from sympy.core import S 

from sympy.printing.defaults import DefaultPrinting 

from sympy.utilities import public 

from sympy.utilities.iterables import flatten 

from sympy.utilities.magic import pollute 

from sympy import sign 

 

 

@public 

def free_group(symbols): 

"""Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1))``. 

 

Parameters 

---------- 

symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y, z = free_group("x, y, z") 

>>> F 

<free group on the generators (x, y, z)> 

>>> x**2*y**-1 

x**2*y**-1 

>>> type(_) 

<class 'sympy.combinatorics.free_group.FreeGroupElement'> 

 

""" 

_free_group = FreeGroup(symbols) 

return (_free_group,) + tuple(_free_group.generators) 

 

@public 

def xfree_group(symbols): 

"""Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1)))``. 

 

Parameters 

---------- 

symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import xfree_group 

>>> F, (x, y, z) = xfree_group("x, y, z") 

>>> F 

<free group on the generators (x, y, z)> 

>>> y**2*x**-2*z**-1 

y**2*x**-2*z**-1 

>>> type(_) 

<class 'sympy.combinatorics.free_group.FreeGroupElement'> 

 

""" 

_free_group = FreeGroup(symbols) 

return (_free_group, _free_group.generators) 

 

@public 

def vfree_group(symbols): 

"""Construct a free group and inject ``f_0, f_1, ..., f_(n-1)`` as symbols 

into the global namespace. 

 

Parameters 

---------- 

symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty) 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import vfree_group 

>>> vfree_group("x, y, z") 

<free group on the generators (x, y, z)> 

>>> x**2*y**-2*z 

x**2*y**-2*z 

>>> type(_) 

<class 'sympy.combinatorics.free_group.FreeGroupElement'> 

 

""" 

_free_group = FreeGroup(symbols) 

pollute([sym.name for sym in _free_group.symbols], _free_group.generators) 

return _free_group 

 

 

def _parse_symbols(symbols): 

if not symbols: 

return tuple() 

if isinstance(symbols, string_types): 

return _symbols(symbols, seq=True) 

elif isinstance(symbols, Expr): 

return (symbols,) 

elif is_sequence(symbols): 

if all(isinstance(s, string_types) for s in symbols): 

return _symbols(symbols) 

elif all(isinstance(s, Expr) for s in symbols): 

return symbols 

raise ValueError("") 

 

 

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

# FREE GROUP # 

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

 

_free_group_cache = {} 

 

class FreeGroup(DefaultPrinting): 

"""Free group with finite or infinite number of generators. Its input API 

is that of an str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty). 

 

References 

========== 

 

[1] http://www.gap-system.org/Manuals/doc/ref/chap37.html 

 

[2] https://en.wikipedia.org/wiki/Free_group 

 

See Also 

======== 

 

sympy.polys.rings.PolyRing 

 

""" 

is_associative = True 

is_group = True 

is_FreeGroup = True 

is_PermutationGroup = False 

 

def __new__(cls, symbols): 

symbols = tuple(_parse_symbols(symbols)) 

rank = len(symbols) 

_hash = hash((cls.__name__, symbols, rank)) 

obj = _free_group_cache.get(_hash) 

 

if obj is None: 

obj = object.__new__(cls) 

obj._hash = _hash 

obj._rank = rank 

# dtype method is used to create new instances of FreeGroupElement 

obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj}) 

obj.symbols = symbols 

obj.generators = obj._generators() 

obj._gens_set = set(obj.generators) 

for symbol, generator in zip(obj.symbols, obj.generators): 

if isinstance(symbol, Symbol): 

name = symbol.name 

if hasattr(obj, name): 

setattr(obj, name, generator) 

 

_free_group_cache[_hash] = obj 

 

return obj 

 

def _generators(group): 

"""Returns the generators of the FreeGroup 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y, z = free_group("x, y, z") 

>>> F.generators 

(x, y, z) 

 

""" 

gens = [] 

for sym in group.symbols: 

elm = ((sym, 1),) 

gens.append(group.dtype(elm)) 

return tuple(gens) 

 

def clone(self, symbols=None): 

return self.__class__(symbols or self.symbols) 

 

def __contains__(self, i): 

"""Return True if `i` is contained in FreeGroup. 

""" 

if not isinstance(i, FreeGroupElement): 

raise TypeError("FreeGroup contains only FreeGroupElement as elements " 

", not elements of type %s" % type(i)) 

group = i.group 

return self == group 

 

def __hash__(self): 

return self._hash 

 

def __len__(self): 

return self.rank 

 

def __str__(self): 

if self.rank > 30: 

str_form = "<free group with %s generators>" % self.rank 

else: 

str_form = "<free group on the generators " 

gens = self.generators 

str_form += str(gens) + ">" 

return str_form 

 

__repr__ = __str__ 

 

def __getitem__(self, index): 

symbols = self.symbols[index] 

return self.clone(symbols=symbols) 

 

def __eq__(self, other): 

"""No ``FreeGroup`` is equal to any "other" ``FreeGroup``. 

""" 

return self is other 

 

def index(self, gen): 

"""Returns the index of the generator `gen` from (f_0, ..., f_(n-1)) 

""" 

if isinstance(gen, self.dtype): 

try: 

return self.generators.index(gen) 

except: 

raise ValueError("invalid generator: %s" % gen) 

else: 

raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen)) 

 

def order(self): 

"""Returns the order of the free group. 

""" 

if self.rank == 0: 

return 1 

else: 

return S.Infinity 

 

@property 

def elements(self): 

if self.rank == 0: 

# A set containing Identity element of `FreeGroup` self is returned 

return set([self.identity]) 

else: 

raise ValueError("Group contains infinitely many elements" 

", hence can't be represented") 

 

@property 

def rank(self): 

r""" 

In group theory, the `rank` of a group `G`, denoted `G.rank`, 

can refer to the smallest cardinality of a generating set 

for G, that is 

 

\operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \langle X\rangle =G\}. 

 

""" 

return self._rank 

 

def _symbol_index(self, symbol): 

"""Returns the index of a generator for free group `self`, while 

returns the -ve index of the inverse generator. 

""" 

try: 

return self.symbols.index(symbol) 

except ValueError: 

return -self.symbols.index(-symbol) 

 

@property 

def is_abelian(self): 

"""Tests if the group is Abelian. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> f.is_abelian 

False 

 

""" 

if self.rank == 0 or self.rank == 1: 

return True 

else: 

return False 

 

@property 

def identity(self): 

"""Returns the identity element of free group. 

""" 

return self.dtype() 

 

def contains(self, g): 

"""Tests if Free Group element ``g`` belong to self, ``G``. 

 

In mathematical terms any linear combination of generators 

of a Free Group is contained in it. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> f.contains(x**3*y**2) 

True 

 

""" 

if not isinstance(g, FreeGroupElement): 

return False 

elif self != g.group: 

return False 

else: 

return True 

 

def is_subgroup(self, F): 

"""Return True if all elements of `self` belong to `F`. 

""" 

return F.is_group and all([self.contains(gen) for gen in F.generators]) 

 

def center(self): 

"""Returns the center of the free group `self`. 

""" 

return set([self.identity]) 

 

 

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

# FreeGroupElement # 

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

 

 

class FreeGroupElement(CantSympify, DefaultPrinting, tuple): 

"""Used to create elements of FreeGroup. It can not be used directly to 

create a free group element. It is called by the `dtype` method of the 

`FreeGroup` class. 

 

""" 

is_assoc_word = True 

 

def new(self, init): 

return self.__class__(init) 

 

_hash = None 

 

def __hash__(self): 

_hash = self._hash 

if _hash is None: 

self._hash = _hash = hash((self.group, frozenset(tuple(self)))) 

return _hash 

 

def copy(self): 

return self.new(self) 

 

@property 

def is_identity(self): 

if self.array_form == tuple(): 

return True 

else: 

return False 

 

@property 

def array_form(self): 

""" 

SymPy provides two different internal kinds of representation 

of associative words. The first one is called the `array_form` 

which is a tuple containing `tuples` as its elements, where the 

size of each tuple is two. At the first position the tuple 

contains the `symbol-generator`, while at the second position 

of tuple contains the exponent of that generator at the position. 

Since elements (i.e. words) don't commute, the indexing of tuple 

makes that property to stay. 

 

The structure in `array_form` of `FreeGroupElement` is shown below, 

 

( ( symbol_of_gen , exponent ), ( , ), ... ( , ) ) 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> (x*z).array_form 

((x, 1), (z, 1)) 

>>> (x**2*z*y*x**2).array_form 

((x, 2), (z, 1), (y, 1), (x, 2)) 

 

See Also 

======== 

 

letter_repr 

 

""" 

return tuple(self) 

 

@property 

def letter_form(self): 

""" 

The letter representation of an `FreeGroupElement` is as a 

tuple of generator symbols, each entry corresponding to a group 

generator. Inverses of the generators are represented by 

negative generator symbols. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b, c, d = free_group("a b c d") 

>>> (a**3).letter_form 

(a, a, a) 

>>> (a**2*d**-2*a*b**-4).letter_form 

(a, a, -d, -d, a, -b, -b, -b, -b) 

>>> (a**-2*b**3*d).letter_form 

(-a, -a, b, b, b, d) 

 

See Also 

======== 

 

array_form 

 

""" 

return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) 

for i, j in self.array_form])) 

 

def __getitem__(self, i): 

group = self.group 

r = self.letter_form[i] 

if r.is_Symbol: 

return group.dtype(((r, 1),)) 

else: 

return group.dtype(((-r, -1),)) 

 

def index(self, gen): 

if len(gen) != 1: 

raise ValueError() 

return (self.letter_form).index(gen.letter_form[0]) 

 

@property 

def letter_form_elm(self): 

""" 

""" 

group = self.group 

r = self.letter_form 

return [group.dtype(((elm,1),)) if elm.is_Symbol \ 

else group.dtype(((-elm,-1),)) for elm in r] 

 

@property 

def ext_rep(self): 

"""This is called the External Representation of `FreeGroupElement` 

""" 

return tuple(flatten(self.array_form)) 

 

def __contains__(self, gen): 

return gen.array_form[0][0] in tuple([r[0] for r in self.array_form]) 

 

def __str__(self): 

if self.is_identity: 

return "<identity>" 

 

symbols = self.group.symbols 

str_form = "" 

array_form = self.array_form 

for i in range(len(array_form)): 

if i == len(array_form) - 1: 

if array_form[i][1] == 1: 

str_form += str(array_form[i][0]) 

else: 

str_form += str(array_form[i][0]) + \ 

"**" + str(array_form[i][1]) 

else: 

if array_form[i][1] == 1: 

str_form += str(array_form[i][0]) + "*" 

else: 

str_form += str(array_form[i][0]) + \ 

"**" + str(array_form[i][1]) + "*" 

return str_form 

 

__repr__ = __str__ 

 

def __pow__(self, n): 

n = as_int(n) 

group = self.group 

if n == 0: 

return group.identity 

 

if n < 0: 

n = -n 

return (self.inverse())**n 

 

result = self 

for i in range(n - 1): 

result = result*self 

# this method can be improved instead of just returning the 

# multiplication of elements 

return result 

 

def __mul__(self, other): 

"""Returns the product of elements belonging to the same `FreeGroup`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> x*y**2*y**-4 

x*y**-2 

>>> z*y**-2 

z*y**-2 

>>> x**2*y*y**-1*x**-2 

<identity> 

 

""" 

group = self.group 

if not isinstance(other, group.dtype): 

raise TypeError("only FreeGroup elements of same FreeGroup can " 

"be multiplied") 

if self.is_identity: 

return other 

if other.is_identity: 

return self 

r = list(self.array_form + other.array_form) 

zero_mul_simp(r, len(self.array_form) - 1) 

return group.dtype(tuple(r)) 

 

def __div__(self, other): 

group = self.group 

if not isinstance(other, group.dtype): 

raise TypeError("only FreeGroup elements of same FreeGroup can " 

"be multiplied") 

return self*(other.inverse()) 

 

def __rdiv__(self, other): 

group = self.group 

if not isinstance(other, group.dtype): 

raise TypeError("only FreeGroup elements of same FreeGroup can " 

"be multiplied") 

return other*(self.inverse()) 

 

__truediv__ = __div__ 

 

__rtruediv__ = __rdiv__ 

 

def __add__(self, other): 

return NotImplemented 

 

def inverse(self): 

""" 

Returns the inverse of a `FreeGroupElement` element 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> x.inverse() 

x**-1 

>>> (x*y).inverse() 

y**-1*x**-1 

 

""" 

group = self.group 

r = tuple([(i, -j) for i, j in self.array_form[::-1]]) 

return group.dtype(r) 

 

def order(self): 

"""Find the order of a `FreeGroupElement`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y = free_group("x y") 

>>> (x**2*y*y**-1*x**-2).order() 

1 

 

""" 

if self.is_identity: 

return 1 

else: 

return S.Infinity 

 

def commutator(self, other): 

"""Returns the commutator of self and x: ``~x*~self*x*self`` 

""" 

group = self.group 

if not isinstance(other, group.dtype): 

raise ValueError("commutator of only `FreeGroupElement` of the same " 

"`FreeGroup` exists") 

else: 

return self.inverse()*other.inverse()*self*other 

 

def eliminate_word(self, gen, by): 

""" 

For an associative word `self`, a generator `gen`, and an associative 

word by, `eliminate_word` returns the associative word obtained by 

replacing each occurrence of `gen` in `self` by `by`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y = free_group("x y") 

>>> w = x**5*y*x**2*y**-4*x 

>>> w.eliminate_word( x, x**2 ) 

x**10*y*x**4*y**-4*x**2 

>>> w.eliminate_word( x, y**-1 ) 

y**-11 

 

See Also 

======== 

substituted_word 

 

""" 

group = self.group 

r = Symbol(str(gen)) 

arr = self.array_form 

array = [] 

by_arr = list(by.array_form) 

l_by = len(by_arr) 

for i in range(len(arr)): 

if arr[i][0] == r: 

# TODO: this shouldn't be checked again and again, since `by` 

# is fixed 

if by_arr == 1: 

array.append((by_arr[0][0], by_arr[0][1]*arr[i][1])) 

zero_mul_simp(array, len(array) - l_by - 1) 

else: 

k = arr[i][1] 

sig = sign(k) 

for j in range(sig*k): 

array.extend(list((by**sig).array_form)) 

zero_mul_simp(array, len(array) - l_by - 1) 

else: 

array.append(arr[i]) 

zero_mul_simp(array, len(array) - 2) 

return group.dtype(tuple(array)) 

 

def __len__(self): 

""" 

For an associative word `self`, this returns the number of letters in it. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a b") 

>>> w = a**5*b*a**2*b**-4*a 

>>> len(w) 

13 

>>> len(a**17) 

17 

>>> len(w**0) 

0 

 

""" 

return sum([abs(j) for (i, j) in self]) 

 

def __eq__(self, other): 

""" 

Two associative words are equal if they are words over the 

same alphabet and if they are sequences of the same letters. 

This is equivalent to saying that the external representations 

of the words are equal. 

There is no "universal" empty word, every alphabet has its own 

empty word. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") 

>>> f 

<free group on the generators (swapnil0, swapnil1)> 

>>> g, swap0, swap1 = free_group("swap0 swap1") 

>>> g 

<free group on the generators (swap0, swap1)> 

 

>>> swapnil0 == swapnil1 

False 

>>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1 

True 

>>> swapnil0*swapnil1 == swapnil1*swapnil0 

False 

>>> swapnil1**0 == swap0**0 

False 

 

""" 

group = self.group 

if not isinstance(other, group.dtype): 

return False 

return tuple.__eq__(self, other) 

 

def __lt__(self, other): 

""" 

The ordering of associative words is defined by length and 

lexicography (this ordering is called short-lex ordering), that 

is, shorter words are smaller than longer words, and words of the 

same length are compared w.r.t. the lexicographical ordering induced 

by the ordering of generators. Generators are sorted according 

to the order in which they were created. If the generators are 

invertible then each generator g is larger than its inverse g**-1, 

and g**-1 is larger than every generator that is smaller than g. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a b") 

>>> b < a 

False 

>>> a < a.inverse() 

False 

 

""" 

group = self.group 

if not isinstance(other, group.dtype): 

raise TypeError("only FreeGroup elements of same FreeGroup can " 

"be compared") 

l = len(self) 

m = len(other) 

# implement lenlex order 

if l < m: 

return True 

elif l > m: 

return False 

a = self.letter_form 

b = other.letter_form 

for i in range(l): 

p = group._symbol_index(a[i]) 

q = group._symbol_index(b[i]) 

if abs(p) < abs(q): 

return True 

elif abs(p) > abs(q): 

return False 

elif p < q: 

return True 

elif p > q: 

return False 

return False 

 

def __le__(self, other): 

return (self == other or self < other) 

 

def __gt__(self, other): 

""" 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, x, y, z = free_group("x y z") 

>>> y**2 > x**2 

True 

>>> y*z > z*y 

False 

>>> x > x.inverse() 

True 

 

""" 

group = self.group 

if not isinstance(other, group.dtype): 

raise TypeError("only FreeGroup elements of same FreeGroup can " 

"be compared") 

return not self <= other 

 

def __ge__(self, other): 

return not self < other 

 

def exponent_sum(self, gen): 

""" 

For an associative word `self` and a generator or inverse of generator 

`gen`, ``exponent_sum`` returns the number of times `gen` appears in 

`self` minus the number of times its inverse appears in `self`. If 

neither `gen` nor its inverse occur in `self` then 0 is returned. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> w = x**2*y**3 

>>> w.exponent_sum(x) 

2 

>>> w.exponent_sum(x**-1) 

-2 

>>> w = x**2*y**4*x**-3 

>>> w.exponent_sum(x) 

-1 

 

See Also 

======== 

generator_count 

 

""" 

if len(gen) != 1: 

raise ValueError("gen must be a generator or inverse of a generator") 

s = gen.array_form[0] 

return s[1]*sum([i[1] for i in self.array_form if i[0] == s[0]]) 

 

def generator_count(self, gen): 

""" 

For an associative word `self` and a generator `gen`, 

``generator_count`` returns the multiplicity of generator 

`gen` in `self`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> w = x**2*y**3 

>>> w.generator_count(x) 

2 

>>> w = x**2*y**4*x**-3 

>>> w.generator_count(x) 

5 

 

See Also 

======== 

exponent_sum 

 

""" 

if len(gen) != 1 or gen.array_form[0][1] < 0: 

raise ValueError("gen must be a generator") 

s = gen.array_form[0] 

return s[1]*sum([abs(i[1]) for i in self.array_form if i[0] == s[0]]) 

 

def subword(self, from_i, to_j): 

""" 

For an associative word `self` and two positive integers `from_i` and 

`to_j`, subword returns the subword of `self` that begins at position 

`from_to` and ends at `to_j`, indexing is done with origin 0. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a b") 

>>> w = a**5*b*a**2*b**-4*a 

>>> w.subword(2, 6) 

a**3*b 

 

""" 

group = self.group 

if from_i < 0 or to_j > len(self): 

raise ValueError("`from_i`, `to_j` must be positive and less than " 

"the length of associative word") 

if to_j <= from_i: 

return group.identity 

else: 

letter_form = self.letter_form[from_i: to_j] 

array_form = letter_form_to_array_form(letter_form, group) 

return group.dtype(array_form) 

 

def is_dependent(self, word): 

""" 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> (x**4*y**-3).is_dependent(x**4*y**-2) 

True 

>>> (x**2*y**-1).is_dependent(x*y) 

False 

>>> (x*y**2*x*y**2).is_dependent(x*y**2) 

True 

>>> (x**12).is_dependent(x**-4) 

True 

 

See Also 

======== 

is_independent 

 

""" 

self_st = str(self.letter_form)[1: -1] 

return str(word.letter_form)[1: -1] in self_st or \ 

str((word**-1).letter_form)[1: -1] in self_st 

 

def is_independent(self, word): 

""" 

 

See Also 

======== 

is_dependent 

 

""" 

return not self.is_dependent 

 

def contains_generators(self): 

""" 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y, z = free_group("x, y, z") 

>>> (x**2*y**-1).contains_generators() 

set([x, y]) 

>>> (x**3*z).contains_generators() 

set([x, z]) 

 

""" 

group = self.group 

gens = set() 

for syllable in self.array_form: 

gens.add(group.dtype(((syllable[0], 1),))) 

return set(gens) 

 

def cyclic_subword(self, from_i, to_j): 

group = self.group 

l = len(self) 

letter_form = self.letter_form 

period1 = int(from_i/l) 

if from_i >= l: 

from_i -= l*period1 

to_j -= l*period1 

diff = to_j - from_i 

word = letter_form[from_i: to_j] 

period2 = int(to_j/l) - 1 

word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2] 

word = letter_form_to_array_form(word, group) 

return group.dtype(word) 

 

def cyclic_conjugates(self): 

"""Returns a words which are cyclic to the word `self`. 

 

References 

========== 

 

http://planetmath.org/cyclicpermutation 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> w = x*y*x*y*x 

>>> w.cyclic_conjugates() 

set([x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x]) 

>>> s = x*y*x**2*y*x 

>>> s.cyclic_conjugates() 

set([x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x]) 

 

""" 

return set([self.cyclic_subword(i, i+len(self)) for i in range(len(self))]) 

 

def is_cyclic_conjugate(self, w): 

""" 

Checks whether words ``self``, ``w`` are cyclic conjugates. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> w1 = x**2*y**5 

>>> w2 = x*y**5*x 

>>> w1.is_cyclic_conjugate(w2) 

True 

>>> w3 = x**-1*y**5*x**-1 

>>> w3.is_cyclic_conjugate(w2) 

False 

 

""" 

l1 = len(self) 

l2 = len(w) 

if l1 != l2: 

return False 

w1 = self.identity_cyclic_reduction() 

w2 = w.identity_cyclic_reduction() 

letter1 = w1.letter_form 

letter2 = w2.letter_form 

str1 = ' '.join(map(str, letter1)) 

str2 = ' '.join(map(str, letter2)) 

if len(str1) != len(str2): 

return False 

 

return str1 in str2 + ' ' + str2 

 

def number_syllables(self): 

"""Returns the number of syllables of the associative word `self`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") 

>>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables() 

3 

 

""" 

return len(self.array_form) 

 

def exponent_syllable(self, i): 

""" 

Returns the exponent of the `i`-th syllable of the associative word 

`self`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a b") 

>>> w = a**5*b*a**2*b**-4*a 

>>> w.exponent_syllable( 2 ) 

2 

 

""" 

return self.array_form[i][1] 

 

def generator_syllable(self, i): 

""" 

Returns the number of the generator that is involved in the 

i-th syllable of the associative word `self`. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a b") 

>>> w = a**5*b*a**2*b**-4*a 

>>> w.generator_syllable( 3 ) 

b 

 

""" 

return self.array_form[i][0] 

 

def sub_syllables(self, from_i, to_j): 

""" 

`sub_syllables` returns the subword of the associative word `self` that 

consists of syllables from positions `from_to` to `to_j`, where 

`from_to` and `to_j` must be positive integers and indexing is done 

with origin 0. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> f, a, b = free_group("a, b") 

>>> w = a**5*b*a**2*b**-4*a 

>>> w.sub_syllables(1, 2) 

b 

>>> w.sub_syllables(3, 3) 

<identity> 

 

""" 

if not isinstance(from_i, int) or not isinstance(to_j, int): 

raise ValueError("both arguments should be integers") 

group = self.group 

if to_j <= from_i: 

return group.identity 

else: 

r = tuple(self.array_form[from_i: to_j]) 

return group.dtype(r) 

 

def substituted_word(self, from_i, to_j, by): 

""" 

Returns the associative word obtained by replacing the subword of 

`self` that begins at position `from_i` and ends at position `to_j` 

by the associative word `by`. `from_i` and `to_j` must be positive 

integers, indexing is done with origin 0. In other words, 

`w.substituted_word(w, from_i, to_j, by)` is the product of the three 

words: `w.subword(0, from_i - 1)`, `by`, and 

`w.subword(to_j + 1, len(w))`. 

 

See Also 

======== 

eliminate_word 

 

""" 

lw = len(self) 

if from_i > to_j or from_i > lw or to_j > lw: 

raise ValueError("values should be within bounds") 

 

# otherwise there are four possibilities 

 

# first if from=1 and to=lw then 

if from_i == 0 and to_j == lw - 1: 

return by 

elif from_i == 0: # second if from_i=1 (and to_j < lw) then 

return by*self.subword(to_j, lw - 1) 

elif to_j == lw: # third if to_j=1 (and fromi_i > 1) then 

return self.subword(0, from_i - 1)*by; 

else: # finally 

return self.subword(0, from_i - 1)*by*self.subword(to_j + 1, lw) 

 

def is_cyclically_reduced(self): 

"""Returns whether the word is cyclically reduced or not. 

A word is cyclically reduced if by forming the cycle of the 

word, the word is not reduced, i.e a word w = a_1 ... a_n 

is called cyclically reduced if a_1 != a_n**−1. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> (x**2*y**-1*x**-1).is_cyclically_reduced() 

False 

>>> (y*x**2*y**2).is_cyclically_reduced() 

True 

 

""" 

if not self: 

return True 

return self[0] != self[-1]**-1 

 

#TODO: may be it should moved to FpGroupElement 

def identity_cyclic_reduction(self): 

"""Return a unique cyclically reduced version of the word. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.free_group import free_group 

>>> F, x, y = free_group("x, y") 

>>> (x**2*y**2*x**-1).identity_cyclic_reduction() 

x*y**2 

>>> (x**-3*y**-1*x**5).identity_cyclic_reduction() 

x**2*y**-1 

 

References 

========== 

 

http://planetmath.org/cyclicallyreduced 

 

""" 

if self.is_cyclically_reduced(): 

return self.copy() 

group = self.group 

exp1 = self.exponent_syllable(0) 

exp2 = self.exponent_syllable(-1) 

r = exp1 + exp2 

if r == 0: 

rep = self.array_form[1: self.number_syllables() - 1] 

else: 

rep = ((self.generator_syllable(0), exp1 + exp2),) + \ 

self.array_form[1: self.number_syllables() - 1] 

return group.dtype(rep) 

 

 

def letter_form_to_array_form(array_form, group): 

""" 

This method converts a list given with possible repetitions of elements in 

it. It returns a new list such that repetitions of consecutive elements is 

removed and replace with a tuple element of size two such that the first 

index contains `value` and the second index contains the number of 

consecutive repetitions of `value`. 

 

""" 

a = list(array_form[:]) 

new_array = [] 

n = 1 

symbols = group.symbols 

for i in range(len(a)): 

if i == len(a) - 1: 

if a[i] == a[i - 1]: 

if (-a[i]) in symbols: 

new_array.append((-a[i], -n)) 

else: 

new_array.append((a[i], n)) 

else: 

if (-a[i]) in symbols: 

new_array.append((-a[i], -1)) 

else: 

new_array.append((a[i], 1)) 

return new_array 

elif a[i] == a[i + 1]: 

n += 1 

else: 

if (-a[i]) in symbols: 

new_array.append((-a[i], -n)) 

else: 

new_array.append((a[i], n)) 

n = 1 

 

 

def zero_mul_simp(l, index): 

"""Used to combine two reduced words.""" 

while index >=0 and index < len(l) - 1 and l[index][0] is l[index + 1][0]: 

exp = l[index][1] + l[index + 1][1] 

base = l[index][0] 

l[index] = (base, exp) 

del l[index + 1] 

if l[index][1] == 0: 

del l[index] 

index -= 1