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

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

""" 

Linear Functions and Constraints 

  

This module implements linear functions (see :class:`LinearFunction`) 

in formal variables and chained (in)equalities between them (see 

:class:`LinearConstraint`). By convention, these are always written as 

either equalities or less-or-equal. For example:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: f = 1 + x[1] + 2*x[2]; f # a linear function 

1 + x_0 + 2*x_1 

sage: type(f) 

<type 'sage.numerical.linear_functions.LinearFunction'> 

  

sage: c = (0 <= f); c # a constraint 

0 <= 1 + x_0 + 2*x_1 

sage: type(c) 

<type 'sage.numerical.linear_functions.LinearConstraint'> 

  

Note that you can use this module without any reference to linear 

programming, it only implements linear functions over a base ring and 

constraints. However, for ease of demonstration we will always 

construct them out of linear programs (see 

:mod:`~sage.numerical.mip`). 

  

Constraints can be equations or (non-strict) inequalities. They can be 

chained:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: x[0] == x[1] == x[2] == x[3] 

x_0 == x_1 == x_2 == x_3 

  

sage: ieq_01234 = x[0] <= x[1] <= x[2] <= x[3] <= x[4] 

sage: ieq_01234 

x_0 <= x_1 <= x_2 <= x_3 <= x_4 

  

If necessary, the direction of inequality is flipped to always write 

inequalities as less or equal:: 

  

sage: x[5] >= ieq_01234 

x_0 <= x_1 <= x_2 <= x_3 <= x_4 <= x_5 

  

sage: (x[5] <= x[6]) >= ieq_01234 

x_0 <= x_1 <= x_2 <= x_3 <= x_4 <= x_5 <= x_6 

sage: (x[5] <= x[6]) <= ieq_01234 

x_5 <= x_6 <= x_0 <= x_1 <= x_2 <= x_3 <= x_4 

  

.. WARNING:: 

  

The implementation of chained inequalities uses a Python hack to 

make it work, so it is not completely robust. In particular, while 

constants are allowed, no two constants can appear next to 

eachother. The following does not work for example:: 

  

sage: x[0] <= 3 <= 4 

True 

  

If you really need this for some reason, you can explicitly convert 

the constants to a :class:`LinearFunction`:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LF = LinearFunctionsParent(QQ) 

sage: x[1] <= LF(3) <= LF(4) 

x_1 <= 3 <= 4 

  

TESTS: 

  

This was fixed in :trac:`24423`:: 

  

sage: p.<x> = MixedIntegerLinearProgram() 

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LF = LinearFunctionsParent(QQ) 

sage: 3 <= x[0] <= LF(4) 

3 <= x_0 <= 4 

  

See :trac:`12091`:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: b[0] <= b[1] <= 2 

x_0 <= x_1 <= 2 

sage: list(b[0] <= b[1] <= 2) 

[x_0, x_1, 2] 

sage: 1 >= b[1] >= 2*b[0] 

2*x_0 <= x_1 <= 1 

sage: b[2] >= b[1] >= 2*b[0] 

2*x_0 <= x_1 <= x_2 

""" 

  

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

# Copyright (C) 2012 Nathann Cohen <nathann.cohen@gmail.com> 

# Copyright (C) 2012 Volker Braun <vbraun.name@gmail.com> 

# Copyright (C) 2016 Jeroen Demeyer <jdemeyer@cage.ugent.be> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

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

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

from __future__ import print_function 

  

from cpython.object cimport Py_EQ, Py_GE, Py_LE, Py_GT, Py_LT 

  

from sage.misc.fast_methods cimport hash_by_id 

from sage.structure.parent cimport Parent 

from sage.structure.element cimport ModuleElement, Element 

from sage.misc.cachefunc import cached_function 

  

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

# 

# Utility functions to test that something is a linear function / constraint 

# 

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

  

cpdef is_LinearFunction(x): 

""" 

Test whether ``x`` is a linear function 

  

INPUT: 

  

- ``x`` -- anything. 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: from sage.numerical.linear_functions import is_LinearFunction 

sage: is_LinearFunction(x[0] - 2*x[2]) 

True 

sage: is_LinearFunction('a string') 

False 

""" 

return isinstance(x, LinearFunction) 

  

def is_LinearConstraint(x): 

""" 

Test whether ``x`` is a linear constraint 

  

INPUT: 

  

- ``x`` -- anything. 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: ieq = (x[0] <= x[1]) 

sage: from sage.numerical.linear_functions import is_LinearConstraint 

sage: is_LinearConstraint(ieq) 

True 

sage: is_LinearConstraint('a string') 

False 

""" 

return isinstance(x, LinearConstraint) 

  

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

# 

# Factory functions for the parents to ensure uniqueness 

# 

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

  

@cached_function 

def LinearFunctionsParent(base_ring): 

""" 

Return the parent for linear functions over ``base_ring``. 

  

The output is cached, so only a single parent is ever constructed 

for a given base ring. 

  

INPUT: 

  

- ``base_ring`` -- a ring. The coefficient ring for the linear 

functions. 

  

OUTPUT: 

  

The parent of the linear functions over ``base_ring``. 

  

EXAMPLES:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LinearFunctionsParent(QQ) 

Linear functions over Rational Field 

""" 

return LinearFunctionsParent_class(base_ring) 

  

@cached_function 

def LinearConstraintsParent(linear_functions_parent): 

""" 

Return the parent for linear functions over ``base_ring``. 

  

The output is cached, so only a single parent is ever constructed 

for a given base ring. 

  

INPUT: 

  

- ``linear_functions_parent`` -- a 

:class:`LinearFunctionsParent_class`. The type of linear 

functions that the constraints are made out of. 

  

OUTPUT: 

  

The parent of the linear constraints with the given linear functions. 

  

EXAMPLES:: 

  

sage: from sage.numerical.linear_functions import ( 

....: LinearFunctionsParent, LinearConstraintsParent) 

sage: LF = LinearFunctionsParent(QQ) 

sage: LinearConstraintsParent(LF) 

Linear constraints over Rational Field 

""" 

return LinearConstraintsParent_class(linear_functions_parent) 

  

  

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

# 

# Elements of linear functions or constraints 

# 

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

  

cdef chained_comparator_left = None 

cdef chained_comparator_right = None 

cdef LinearConstraint chained_comparator_replace = None 

  

cdef class LinearFunctionOrConstraint(ModuleElement): 

""" 

Base class for :class:`LinearFunction` and :class:`LinearConstraint`. 

  

This class exists solely to implement chaining of inequalities 

in constraints. 

""" 

def __richcmp__(self, other, int op): 

""" 

Create an inequality or equality object, possibly chaining 

several together. 

  

EXAMPLES:: 

  

sage: p.<x> = MixedIntegerLinearProgram() 

sage: x[0].__le__(x[1]) 

x_0 <= x_1 

  

:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: from sage.numerical.linear_functions import LinearFunction 

sage: LF({2 : 5, 3 : 2}) <= LF({2 : 3, 9 : 2}) 

5*x_2 + 2*x_3 <= 3*x_2 + 2*x_9 

  

sage: LF({2 : 5, 3 : 2}) >= LF({2 : 3, 9 : 2}) 

3*x_2 + 2*x_9 <= 5*x_2 + 2*x_3 

  

sage: LF({2 : 5, 3 : 2}) == LF({2 : 3, 9 : 2}) 

5*x_2 + 2*x_3 == 3*x_2 + 2*x_9 

  

We can chain multiple (in)equalities:: 

  

sage: p.<b> = MixedIntegerLinearProgram() 

sage: b[0] == 1 == b[1] == 2 == b[2] == 3 

x_0 == 1 == x_1 == 2 == x_2 == 3 

sage: b[0] <= 1 <= b[1] <= 2 <= b[2] <= 3 

x_0 <= 1 <= x_1 <= 2 <= x_2 <= 3 

sage: b[0] <= b[1] <= b[2] <= b[3] 

x_0 <= x_1 <= x_2 <= x_3 

  

Other comparison operators are not allowed:: 

  

sage: b[0] < b[1] 

Traceback (most recent call last): 

... 

ValueError: strict < is not allowed, use <= instead 

sage: b[0] > b[1] 

Traceback (most recent call last): 

... 

ValueError: strict > is not allowed, use >= instead 

sage: b[0] != b[1] 

Traceback (most recent call last): 

... 

ValueError: inequality != is not allowed, use one of <=, ==, >= 

  

Mixing operators is also not allowed:: 

  

sage: 1 <= b[1] >= 2 

Traceback (most recent call last): 

... 

ValueError: incorrectly chained inequality 

sage: 1 >= b[1] <= 2 

Traceback (most recent call last): 

... 

ValueError: incorrectly chained inequality 

sage: 1 == b[1] <= 2 

Traceback (most recent call last): 

... 

ValueError: cannot mix equations and inequalities 

sage: 1 >= b[1] == 2 

Traceback (most recent call last): 

... 

ValueError: cannot mix equations and inequalities 

  

TESTS:: 

  

sage: p.<x> = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: cm = sage.structure.element.get_coercion_model() 

sage: cm.explain(10, LF(1), operator.le) 

Coercion on left operand via 

Coercion map: 

From: Integer Ring 

To: Linear functions over Real Double Field 

Arithmetic performed after coercions. 

Result lives in Linear functions over Real Double Field 

Linear functions over Real Double Field 

  

sage: operator.le(10, x[0]) 

10 <= x_0 

sage: x[0] <= 1 

x_0 <= 1 

sage: x[0] >= 1 

1 <= x_0 

sage: 1 <= x[0] 

1 <= x_0 

sage: 1 >= x[0] 

x_0 <= 1 

  

This works with non-Sage types too, see :trac:`14540`:: 

  

sage: p.<b> = MixedIntegerLinearProgram() 

sage: int(1) <= b[0] <= int(2) 

1 <= x_0 <= 2 

sage: int(1) >= b[0] >= int(2) 

2 <= x_0 <= 1 

sage: int(1) == b[0] == int(2) 

1 == x_0 == 2 

sage: float(0) <= b[0] <= int(1) <= b[1] <= float(2) 

0 <= x_0 <= 1 <= x_1 <= 2 

""" 

# Store the chaining variables and set them to None for now in 

# order to have a sane state for any conversions below or when 

# an exception is raised. 

global chained_comparator_left 

global chained_comparator_right 

global chained_comparator_replace 

  

chain_left = chained_comparator_left 

chain_right = chained_comparator_right 

chain_replace = chained_comparator_replace 

  

chained_comparator_left = None 

chained_comparator_right = None 

chained_comparator_replace = None 

  

# Assign {self, other} to {py_left, py_right} such that 

# py_left <= py_right. 

cdef bint equality = False 

if op == Py_LE: 

py_left, py_right = self, other 

elif op == Py_GE: 

py_left, py_right = other, self 

elif op == Py_EQ: 

py_left, py_right = self, other 

equality = True 

elif op == Py_LT: 

raise ValueError("strict < is not allowed, use <= instead") 

elif op == Py_GT: 

raise ValueError("strict > is not allowed, use >= instead") 

else: 

raise ValueError("inequality != is not allowed, use one of <=, ==, >=") 

  

# Convert py_left and py_right to constraints left and right, 

# possibly replacing them to implement the hack below. 

cdef LinearConstraint left = None 

cdef LinearConstraint right = None 

  

# HACK to allow chained constraints: Python translates 

# x <= y <= z into: 

# 

# temp = x <= y # calls x.__richcmp__(y) 

# if temp: # calls temp.__nonzero__() 

# return y <= z # calls y.__richcmp__(z) 

# else: 

# return temp 

# 

# or, if x <= y is not implemented (for example, if x is a 

# non-Sage type): 

# 

# temp = y >= x # calls y.__richcmp__(x) 

# if temp: # calls temp.__nonzero__() 

# return y <= z # calls y.__richcmp__(z) 

# else: 

# return temp 

# 

# but we would like x <= y <= z as output. The trick to make it 

# work is to store x and y in the first call to __richcmp__ 

# and temp in the call to __nonzero__. Then we can replace x 

# or y by x <= y in the second call to __richcmp__. 

if chain_replace is not None: 

if chain_replace.equality != equality: 

raise ValueError("cannot mix equations and inequalities") 

  

# First, check for correctly-chained inequalities 

# x <= y <= z or z <= y <= x. 

if py_left is chain_right: 

left = chain_replace 

elif py_right is chain_left: 

right = chain_replace 

# Next, check for incorrectly chained inequalities like 

# x <= y >= z. If we are dealing with inequalities, this 

# is an error. For an equality, we fix the chaining by 

# reversing one of the sides. 

elif py_left is chain_left: 

if not equality: 

raise ValueError("incorrectly chained inequality") 

chain_replace.constraints.reverse() 

left = chain_replace 

elif py_right is chain_right: 

if not equality: 

raise ValueError("incorrectly chained inequality") 

left = chain_replace 

py_right = py_left 

  

# Figure out the correct parent to work with: if we did a 

# replacement, its parent takes priority. 

if left is not None: 

LC = left._parent 

elif right is not None: 

LC = right._parent 

else: 

LC = (<LinearFunctionOrConstraint>self)._parent 

  

# We want the parent to be a LinearConstraintsParent 

if not isinstance(LC, LinearConstraintsParent_class): 

LC = LinearConstraintsParent(LC) 

  

if left is None: 

try: 

left = <LinearConstraint?>py_left 

except TypeError: 

left = <LinearConstraint>LC(py_left, equality=equality) 

else: 

if left._parent is not LC: 

left = <LinearConstraint>LC(left.constraints, equality=left.equality) 

  

if right is None: 

try: 

right = <LinearConstraint?>py_right 

except TypeError: 

right = <LinearConstraint>LC(py_right, equality=equality) 

else: 

if right._parent is not LC: 

right = <LinearConstraint>LC(right.constraints, equality=right.equality) 

  

# Finally, chain the (in)equalities 

if left.equality != equality or right.equality != equality: 

raise ValueError("cannot mix equations and inequalities") 

ret = LC(left.constraints + right.constraints, equality=equality) 

  

# Everything done, so we set the chaining variables 

chained_comparator_left = py_left 

chained_comparator_right = py_right 

chained_comparator_replace = None 

  

return ret 

  

def __hash__(self): 

r""" 

Return a hash from the ``id()``. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: f = LF({2 : 5, 3 : 2}) 

sage: f.__hash__() # random output 

103987752 

sage: d = {} 

sage: d[f] = 3 

""" 

# see __cmp__() if you want to change the hash function 

return hash_by_id(<void*>self) 

  

def __cmp__(left, right): 

""" 

Implement comparison of two linear functions or constraints. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: f = LF({2 : 5, 3 : 2}) 

sage: cmp(f, f) 

0 

sage: abs(cmp(f, f+0)) # since we are comparing by id() 

1 

sage: abs(cmp(f, f+1)) 

1 

sage: len(set([f, f])) 

1 

sage: len(set([f, f+0])) 

2 

sage: len(set([f, f+1])) 

2 

sage: abs(cmp(f <= 0, f <= 0)) 

1 

""" 

# Note: if you want to implement smarter comparison, you also 

# need to change __hash__(). The comparison function must 

# satisfy cmp(x,y)==0 => hash(x)==hash(y) 

if left is right: 

return 0 

if <size_t><void*>left < <size_t><void*>right: 

return -1 

else: 

return 1 

  

  

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

# 

# Parent of linear functions 

# 

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

  

cdef class LinearFunctionsParent_class(Parent): 

r""" 

The parent for all linear functions over a fixed base ring. 

  

.. warning:: 

  

You should use :func:`LinearFunctionsParent` to construct 

instances of this class. 

  

INPUT/OUTPUT: 

  

See :func:`LinearFunctionsParent` 

  

EXAMPLES:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent_class 

sage: LinearFunctionsParent_class 

<type 'sage.numerical.linear_functions.LinearFunctionsParent_class'> 

""" 

def __cinit__(self): 

""" 

Cython initializer 

  

TESTS:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent_class 

sage: LF = LinearFunctionsParent_class.__new__(LinearFunctionsParent_class) 

sage: LF._multiplication_symbol 

'*' 

""" 

# Do not use coercion framework for __richcmp__ 

self.flags |= Parent_richcmp_element_without_coercion 

self._multiplication_symbol = '*' 

  

def __init__(self, base_ring): 

""" 

The Python constructor 

  

TESTS:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LinearFunctionsParent(RDF) 

Linear functions over Real Double Field 

""" 

from sage.categories.modules_with_basis import ModulesWithBasis 

Parent.__init__(self, base=base_ring, category=ModulesWithBasis(base_ring)) 

  

def set_multiplication_symbol(self, symbol='*'): 

""" 

Set the multiplication symbol when pretty-printing linear functions. 

  

INPUT: 

  

- ``symbol`` -- string, default: ``'*'``. The multiplication 

symbol to be used. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: f = -1-2*x[0]-3*x[1] 

sage: LF = f.parent() 

sage: LF._get_multiplication_symbol() 

'*' 

sage: f 

-1 - 2*x_0 - 3*x_1 

sage: LF.set_multiplication_symbol(' ') 

sage: f 

-1 - 2 x_0 - 3 x_1 

sage: LF.set_multiplication_symbol() 

sage: f 

-1 - 2*x_0 - 3*x_1 

""" 

self._multiplication_symbol = symbol 

  

def _get_multiplication_symbol(self): 

""" 

Return the multiplication symbol. 

  

OUTPUT: 

  

String. By default, this is ``'*'``. 

  

EXAMPLES:: 

  

sage: LF = MixedIntegerLinearProgram().linear_functions_parent() 

sage: LF._get_multiplication_symbol() 

'*' 

""" 

return self._multiplication_symbol 

  

def tensor(self, free_module): 

""" 

Return the tensor product with ``free_module``. 

  

INPUT: 

  

- ``free_module`` -- vector space or matrix space over the 

same base ring. 

  

OUTPUT: 

  

Instance of 

:class:`sage.numerical.linear_tensor.LinearTensorParent_class`. 

  

EXAMPLES:: 

  

sage: LF = MixedIntegerLinearProgram().linear_functions_parent() 

sage: LF.tensor(RDF^3) 

Tensor product of Vector space of dimension 3 over Real Double Field 

and Linear functions over Real Double Field 

sage: LF.tensor(QQ^2) 

Traceback (most recent call last): 

... 

ValueError: base rings must match 

""" 

from sage.numerical.linear_tensor import LinearTensorParent 

return LinearTensorParent(free_module, self) 

  

def gen(self, i): 

""" 

Return the linear variable `x_i`. 

  

INPUT: 

  

- ``i`` -- non-negative integer. 

  

OUTPUT: 

  

The linear function `x_i`. 

  

EXAMPLES:: 

  

sage: LF = MixedIntegerLinearProgram().linear_functions_parent() 

sage: LF.gen(23) 

x_23 

""" 

return LinearFunction(self, {i:1}) 

  

def _repr_(self): 

""" 

Return as string representation 

  

EXAMPLES:: 

  

sage: MixedIntegerLinearProgram().linear_functions_parent() 

Linear functions over Real Double Field 

""" 

return 'Linear functions over '+str(self.base_ring()) 

  

cpdef _element_constructor_(self, x): 

""" 

Construt a :class:`LinearFunction` from ``x``. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF._element_constructor_(123) 

123 

sage: p(123) # indirect doctest 

doctest:...: DeprecationWarning: ... 

123 

sage: type(_) 

<type 'sage.numerical.linear_functions.LinearFunction'> 

  

sage: p_QQ = MixedIntegerLinearProgram(solver='ppl') 

sage: LF_QQ = p_QQ.linear_functions_parent() 

sage: f = LF({-1:1/2, 2:3/4}); f 

0.5 + 0.75*x_2 

sage: LF(f) is f 

True 

sage: LF_QQ(f) 

1/2 + 3/4*x_2 

sage: LF_QQ(f) is f 

False 

""" 

if is_LinearFunction(x): 

if x.parent() is self: 

return x 

else: 

return LinearFunction(self, (<LinearFunction>x)._f) 

return LinearFunction(self, x) 

  

cpdef _coerce_map_from_(self, R): 

""" 

Allow coercion of scalars into linear functions. 

  

INPUT: 

  

- ``R`` -- a ring. 

  

OUTPUT: 

  

Boolean. Whether there is a coercion map. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: parent = p.linear_functions_parent() 

sage: parent.coerce(int(2)) 

2 

sage: parent._coerce_map_from_(int) 

True 

""" 

if R in [int, float, long, complex]: 

return True 

from sage.rings.real_mpfr import mpfr_prec_min 

from sage.rings.all import RealField 

if RealField(mpfr_prec_min()).has_coerce_map_from(R): 

return True 

return False 

  

def _an_element_(self): 

""" 

Returns an element 

  

OUTPUT: 

  

A linear function. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram().linear_functions_parent() 

sage: p._an_element_() 

5*x_2 + 7*x_5 

sage: p.an_element() # indirect doctest 

5*x_2 + 7*x_5 

""" 

return self._element_constructor_({2:5, 5:7}) 

  

  

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

# 

# Elements of linear functions 

# 

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

  

cdef class LinearFunction(LinearFunctionOrConstraint): 

r""" 

An elementary algebra to represent symbolic linear functions. 

  

.. warning:: 

  

You should never instantiate :class:`LinearFunction` 

manually. Use the element constructor in the parent 

instead. 

  

EXAMPLES: 

  

For example, do this:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: parent = p.linear_functions_parent() 

sage: parent({0 : 1, 3 : -8}) 

x_0 - 8*x_3 

  

instead of this:: 

  

sage: from sage.numerical.linear_functions import LinearFunction 

sage: LinearFunction(p.linear_functions_parent(), {0 : 1, 3 : -8}) 

x_0 - 8*x_3 

""" 

  

def __init__(self, parent, f): 

r""" 

Constructor taking a dictionary or a numerical value as its argument. 

  

A linear function is represented as a dictionary. The 

values are the coefficient of the variable represented 

by the keys ( which are integers ). The key ``-1`` 

corresponds to the constant term. 

  

EXAMPLES: 

  

With a dictionary:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF({0 : 1, 3 : -8}) 

x_0 - 8*x_3 

  

Using the constructor with a numerical value:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF(25) 

25 

""" 

ModuleElement.__init__(self, parent) 

R = self.base_ring() 

if isinstance(f, dict): 

self._f = dict( (int(key), R(value)) for key, value in f.iteritems() ) 

else: 

self._f = {-1: R(f)} 

  

cpdef iteritems(self): 

""" 

Iterate over the index, coefficient pairs 

  

OUTPUT: 

  

An iterator over the ``(key, coefficient)`` pairs. The keys 

are integers indexing the variables. The key ``-1`` 

corresponds to the constant term. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram(solver = 'ppl') 

sage: x = p.new_variable() 

sage: f = 0.5 + 3/2*x[1] + 0.6*x[3] 

sage: for id, coeff in f.iteritems(): 

....: print('id = {} coeff = {}'.format(id, coeff)) 

id = 0 coeff = 3/2 

id = 1 coeff = 3/5 

id = -1 coeff = 1/2 

""" 

return self._f.iteritems() 

  

def dict(self): 

r""" 

Return the dictionary corresponding to the Linear Function. 

  

OUTPUT: 

  

The linear function is represented as a dictionary. The value 

are the coefficient of the variable represented by the keys ( 

which are integers ). The key ``-1`` corresponds to the 

constant term. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: lf = LF({0 : 1, 3 : -8}) 

sage: lf.dict() 

{0: 1.0, 3: -8.0} 

""" 

return dict(self._f) 

  

def coefficient(self, x): 

r""" 

Return one of the coefficients. 

  

INPUT: 

  

- ``x`` -- a linear variable or an integer. If an integer `i` 

is passed, then `x_i` is used as linear variable. 

  

OUTPUT: 

  

A base ring element. The coefficient of ``x`` in the linear 

function. Pass ``-1`` for the constant term. 

  

EXAMPLES:: 

  

sage: mip.<b> = MixedIntegerLinearProgram() 

sage: lf = -8 * b[3] + b[0] - 5; lf 

-5 - 8*x_0 + x_1 

sage: lf.coefficient(b[3]) 

-8.0 

sage: lf.coefficient(0) # x_0 is b[3] 

-8.0 

sage: lf.coefficient(4) 

0.0 

sage: lf.coefficient(-1) 

-5.0 

  

TESTS:: 

  

sage: lf.coefficient(b[3] + b[4]) 

Traceback (most recent call last): 

... 

ValueError: x is a sum, must be a single variable 

sage: lf.coefficient(2*b[3]) 

Traceback (most recent call last): 

... 

ValueError: x must have a unit coefficient 

sage: mip.<q> = MixedIntegerLinearProgram(solver='ppl') 

sage: lf.coefficient(q[0]) 

Traceback (most recent call last): 

... 

ValueError: x is from a different linear functions module 

""" 

if is_LinearFunction(x): 

if self.parent() != x.parent(): 

raise ValueError('x is from a different linear functions module') 

if len((<LinearFunction>x)._f) != 1: 

raise ValueError('x is a sum, must be a single variable') 

i, = (<LinearFunction>x)._f.keys() 

if (<LinearFunction>x)._f[i] != 1: 

raise ValueError('x must have a unit coefficient') 

else: 

i = int(x) 

try: 

return self._f[i] 

except KeyError: 

return self.parent().base_ring().zero() 

  

cpdef _add_(self, b): 

r""" 

Defining the + operator 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF({0 : 1, 3 : -8}) + LF({2 : 5, 3 : 2}) - 16 

-16 + x_0 + 5*x_2 - 6*x_3 

""" 

e = dict(self._f) 

for (id,coeff) in b.dict().iteritems(): 

e[id] = self._f.get(id,0) + coeff 

P = self.parent() 

return P(e) 

  

cpdef _neg_(self): 

r""" 

Defining the - operator (opposite). 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: - LF({0 : 1, 3 : -8}) 

-1*x_0 + 8*x_3 

""" 

P = self.parent() 

return P(dict([(id,-coeff) for (id, coeff) in self._f.iteritems()])) 

  

cpdef _sub_(self, b): 

r""" 

Defining the - operator (substraction). 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF({2 : 5, 3 : 2}) - 3 

-3 + 5*x_2 + 2*x_3 

sage: LF({0 : 1, 3 : -8}) - LF({2 : 5, 3 : 2}) - 16 

-16 + x_0 - 5*x_2 - 10*x_3 

""" 

e = dict(self._f) 

for (id,coeff) in b.dict().iteritems(): 

e[id] = self._f.get(id,0) - coeff 

P = self.parent() 

return P(e) 

  

cpdef _lmul_(self, Element b): 

r""" 

Multiplication by scalars 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LF = p.linear_functions_parent() 

sage: LF({2 : 5, 3 : 2}) * 3 

15*x_2 + 6*x_3 

sage: 3 * LF({2 : 5, 3 : 2}) 

15*x_2 + 6*x_3 

""" 

P = self.parent() 

return P(dict([(id,b*coeff) for (id, coeff) in self._f.iteritems()])) 

  

cpdef _acted_upon_(self, x, bint self_on_left): 

""" 

Act with scalars that do not have a natural coercion into 

``self.base_ring()`` 

  

EXAMPLES: 

  

Note that there is no coercion from ``RR`` to ``QQ``, but you 

can explicitly convert them:: 

  

sage: 1/2 * 0.6 

0.300000000000000 

  

If there were a coercion, then 0.6 would have been coerced into 

6/10 and the result would have been rational. This is 

undesirable, which is why there cannot be a coercion on the 

level of the coefficient rings. 

  

By declaring an action of ``RR`` on the linear functions over 

``QQ`` we make the following possible:: 

  

sage: p = MixedIntegerLinearProgram(solver='ppl') 

sage: p.base_ring() 

Rational Field 

sage: x = p.new_variable() 

sage: x[0] * 0.6 

3/5*x_0 

  

sage: vf = (2 + x[0]) * vector(ZZ, [3,4]); vf 

(6, 8) + (3, 4)*x_0 

sage: vf.parent() 

Tensor product of Vector space of dimension 2 over Rational Field 

and Linear functions over Rational Field 

  

sage: tf = x[0] * identity_matrix(2); tf 

[x_0 0 ] 

[0 x_0] 

sage: tf.parent() 

Tensor product of Full MatrixSpace of 2 by 2 dense matrices over 

Rational Field and Linear functions over Rational Field 

""" 

R = self.base_ring() 

try: 

x_R = R(x) 

except TypeError: 

M = x.parent().base_extend(R) 

x_M = M(x) 

from sage.numerical.linear_tensor import LinearTensorParent 

P = LinearTensorParent(M, self.parent()) 

tensor = dict() 

for k, v in self._f.items(): 

tensor[k] = x_M * v 

return P(tensor) 

return self._rmul_(x_R) 

  

def _coeff_formatter(self, coeff, constant_term=False): 

""" 

Pretty-print multiplicative coefficient ``x`` 

  

OUTPUT: 

  

String, including a trailing space if the coefficient is not 

one. Empty string otherwise. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: f = p(1); type(f) 

<type 'sage.numerical.linear_functions.LinearFunction'> 

sage: f._coeff_formatter(1) 

'' 

sage: f._coeff_formatter(1, constant_term=True) 

'1' 

sage: f._coeff_formatter(RDF(12.0)) 

'12*' 

sage: f._coeff_formatter(RDF(12.3)) 

'12.3*' 

  

sage: p = MixedIntegerLinearProgram(solver='ppl') 

sage: f = p(1) 

sage: f._coeff_formatter(13/45) 

'13/45*' 

  

sage: from sage.rings.number_field.number_field import QuadraticField 

sage: K.<sqrt5> = QuadraticField(5, 'sqrt5') 

sage: p = MixedIntegerLinearProgram(solver='interactivelp', base_ring=K) 

sage: f = p(1) 

sage: f._coeff_formatter(sqrt5) 

'sqrt5*' 

  

sage: from sage.rings.all import AA 

sage: sqrt5 = AA(5).sqrt() 

sage: p = MixedIntegerLinearProgram(solver='interactivelp', base_ring=AA) 

sage: f = p(1) 

sage: f._coeff_formatter(sqrt5) 

'2.236067977499790?*' 

""" 

R = self.base_ring() 

if coeff == R.one() and not constant_term: 

return '' 

try: 

from sage.rings.all import ZZ 

coeff = ZZ(coeff) # print as integer if possible 

except (TypeError, ValueError): 

pass 

if constant_term: 

return str(coeff) 

else: 

return str(coeff) + self.parent()._multiplication_symbol 

  

def _repr_(self): 

r""" 

Returns a string version of the linear function. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram(solver='GLPK') 

sage: LF = p.linear_functions_parent() 

sage: LF({-1: -15, 2 : -5.1, 3 : 2/3}) 

-15 - 5.1*x_2 + 0.666666666667*x_3 

sage: p = MixedIntegerLinearProgram(solver='ppl') 

sage: LF = p.linear_functions_parent() 

sage: LF({-1: -15, 2 : -5.1, 3 : 2/3}) 

-15 - 51/10*x_2 + 2/3*x_3 

""" 

cdef dict d = dict(self._f) 

cdef bint first = True 

t = "" 

  

if -1 in d: 

coeff = d.pop(-1) 

if coeff: 

t = self._coeff_formatter(coeff, constant_term=True) 

first = False 

  

cdef list l = sorted(d.items()) 

for id, coeff in l: 

sign = coeff.sign() 

if sign == 0: 

continue 

if not first: 

if sign == -1: 

t += ' - ' 

if sign == +1: 

t += ' + ' 

t += self._coeff_formatter(abs(coeff)) + 'x_' + str(id) 

else: 

t += self._coeff_formatter(coeff) + 'x_' + str(id) 

first = False 

  

if first: 

return '0' 

else: 

return t 

  

cpdef is_zero(self): 

""" 

Test whether ``self`` is zero. 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: (x[1] - x[1] + 0*x[2]).is_zero() 

True 

""" 

for coeff in self._f.values(): 

if not coeff.is_zero(): 

return False 

return True 

  

cpdef equals(LinearFunction left, LinearFunction right): 

""" 

Logically compare ``left`` and ``right``. 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: (x[1] + 1).equals(3/3 + 1*x[1] + 0*x[2]) 

True 

""" 

return (left-right).is_zero() 

  

  

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

# 

# Parent of linear constraints 

# 

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

  

cdef class LinearConstraintsParent_class(Parent): 

""" 

Parent for :class:`LinearConstraint` 

  

.. warning:: 

  

This class has no reason to be instantiated by the user, and 

is meant to be used by instances of 

:class:`MixedIntegerLinearProgram`. Also, use the 

:func:`LinearConstraintsParent` factory function. 

  

INPUT/OUTPUT: 

  

See :func:`LinearFunctionsParent` 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LC = p.linear_constraints_parent(); LC 

Linear constraints over Real Double Field 

sage: from sage.numerical.linear_functions import LinearConstraintsParent 

sage: LinearConstraintsParent(p.linear_functions_parent()) is LC 

True 

""" 

def __cinit__(self, linear_functions_parent): 

""" 

Cython initializer 

  

TESTS:: 

  

sage: from sage.numerical.linear_functions import LinearConstraintsParent_class 

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LF = LinearFunctionsParent(RDF) 

sage: LinearConstraintsParent_class.__new__(LinearConstraintsParent_class, LF) 

Linear constraints over Real Double Field 

sage: LinearConstraintsParent_class.__new__(LinearConstraintsParent_class, None) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert NoneType to sage.numerical.linear_functions.LinearFunctionsParent_class 

""" 

self._LF = <LinearFunctionsParent_class?>linear_functions_parent 

# Do not use coercion framework for __richcmp__ 

self.flags |= Parent_richcmp_element_without_coercion 

  

def __init__(self, linear_functions_parent): 

""" 

The Python constructor 

  

INPUT/OUTPUT: 

  

See :func:`LinearFunctionsParent` 

  

TESTS:: 

  

sage: from sage.numerical.linear_functions import LinearFunctionsParent 

sage: LF = LinearFunctionsParent(RDF) 

sage: from sage.numerical.linear_functions import LinearConstraintsParent 

sage: LinearConstraintsParent(LF) 

Linear constraints over Real Double Field 

sage: LinearConstraintsParent(None) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert NoneType to sage.numerical.linear_functions.LinearFunctionsParent_class 

""" 

Parent.__init__(self) 

  

def linear_functions_parent(self): 

""" 

Return the parent for the linear functions 

  

EXAMPLES:: 

  

sage: LC = MixedIntegerLinearProgram().linear_constraints_parent() 

sage: LC.linear_functions_parent() 

Linear functions over Real Double Field 

""" 

return self._LF 

  

def _repr_(self): 

""" 

Return a string representation 

  

OUTPUT: 

  

String. 

  

EXAMPLES:: 

  

sage: MixedIntegerLinearProgram().linear_constraints_parent() 

Linear constraints over Real Double Field 

""" 

return 'Linear constraints over '+str(self.linear_functions_parent().base_ring()) 

  

cpdef _element_constructor_(self, left, right=None, equality=False): 

""" 

Construt a :class:`LinearConstraint`. 

  

INPUT: 

  

- ``left`` -- a :class:`LinearFunction`, or something that can 

be converted into one, a list/tuple of 

:class:`LinearFunction`, or an existing 

:class:`LinearConstraint`. 

  

- ``right`` -- a :class:`LinearFunction` or ``None`` 

(default). 

  

- ``equality`` -- boolean (default: ``True``). Whether to 

construct an equation or an inequality. 

  

OUTPUT: 

  

The :class:`LinearConstraint` constructed from the input data. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LC = p.linear_constraints_parent() 

sage: LC._element_constructor_(1, 2) 

1 <= 2 

  

sage: x = p.new_variable() 

sage: LC([x[0], x[1], x[2]]) 

x_0 <= x_1 <= x_2 

  

sage: LC([x[0], x[1], x[2]], equality=True) 

x_0 == x_1 == x_2 

  

sage: type(_) 

<type 'sage.numerical.linear_functions.LinearConstraint'> 

  

TESTS:: 

  

sage: inequality = LC([x[0], 1/2*x[1], 3/4*x[2]]); inequality 

x_0 <= 0.5*x_1 <= 0.75*x_2 

sage: LC(inequality) is inequality 

True 

sage: p_QQ = MixedIntegerLinearProgram(solver='ppl') 

sage: LC_QQ = p_QQ.linear_constraints_parent() 

sage: LC_QQ(inequality) 

x_0 <= 1/2*x_1 <= 3/4*x_2 

sage: LC_QQ(inequality) is inequality 

False 

""" 

if right is None and is_LinearConstraint(left): 

if (left.parent() is self) and (left.is_equation() == equality): 

return left 

else: 

return LinearConstraint(self, (<LinearConstraint>left).constraints, 

equality=equality) 

if right is None: 

if isinstance(left, (list,tuple)): 

return LinearConstraint(self, left, equality=equality) 

else: 

return LinearConstraint(self, [left], equality=equality) 

else: 

return LinearConstraint(self, [left, right], equality=equality) 

  

cpdef _coerce_map_from_(self, R): 

""" 

Allow coercion of scalars into linear functions. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: parent = p.linear_constraints_parent() 

sage: parent.coerce(int(2)) 

trivial constraint starting with 2 

sage: parent._coerce_map_from_(int) 

True 

""" 

return self.linear_functions_parent().has_coerce_map_from(R) 

  

def _an_element_(self): 

""" 

Returns an element 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram().linear_functions_parent() 

sage: p._an_element_() 

5*x_2 + 7*x_5 

sage: p.an_element() # indirect doctest 

5*x_2 + 7*x_5 

""" 

LF = self.linear_functions_parent() 

return self(0) <= LF.an_element() 

  

  

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

# 

# Elements of linear constraints 

# 

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

  

cdef class LinearConstraint(LinearFunctionOrConstraint): 

""" 

A class to represent formal Linear Constraints. 

  

A Linear Constraint being an inequality between 

two linear functions, this class lets the user 

write ``LinearFunction1 <= LinearFunction2`` 

to define the corresponding constraint, which 

can potentially involve several layers of such 

inequalities (``A <= B <= C``), or even equalities 

like ``A == B == C``. 

  

Trivial constraints (meaning that they have only one term and no 

relation) are also allowed. They are required for the coercion 

system to work. 

  

.. warning:: 

  

This class has no reason to be instantiated by the user, and 

is meant to be used by instances of 

:class:`MixedIntegerLinearProgram`. 

  

INPUT: 

  

- ``parent`` -- the parent, a :class:`LinearConstraintsParent_class` 

  

- ``terms`` -- a list/tuple/iterable of two or more linear 

functions (or things that can be converted into linear 

functions). 

  

- ``equality`` -- boolean (default: ``False``). Whether the terms 

are the entries of a chained less-or-equal (``<=``) inequality 

or a chained equality. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: b[2]+2*b[3] <= b[8]-5 

x_0 + 2*x_1 <= -5 + x_2 

""" 

  

def __init__(self, parent, terms, equality=False): 

r""" 

Constructor for ``LinearConstraint`` 

  

INPUT: 

  

See :class:`LinearConstraint`. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: b[2]+2*b[3] <= b[8]-5 

x_0 + 2*x_1 <= -5 + x_2 

""" 

assert len(terms) > 0 

super(LinearConstraint, self).__init__(parent) 

self.equality = equality 

LF = parent.linear_functions_parent() 

self.constraints = [ LF(term) for term in terms ] 

  

cpdef equals(LinearConstraint left, LinearConstraint right): 

""" 

Compare ``left`` and ``right``. 

  

OUTPUT: 

  

Boolean. Whether all terms of ``left`` and ``right`` are 

equal. Note that this is stronger than mathematical 

equivalence of the relations. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: x = p.new_variable() 

sage: (x[1] + 1 >= 2).equals(3/3 + 1*x[1] + 0*x[2] >= 8/4) 

True 

sage: (x[1] + 1 >= 2).equals(x[1] + 1-1 >= 1-1) 

False 

""" 

if len(left.constraints) != len(right.constraints): 

return False 

if left.equality != right.equality: 

return False 

cdef LinearFunction l, r 

for i in range(len(left.constraints)): 

l = <LinearFunction>(left.constraints[i]) 

r = <LinearFunction>(right.constraints[i]) 

if not l.equals(r): 

return False 

return True 

  

def is_equation(self): 

""" 

Whether the constraint is a chained equation 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: (b[0] == b[1]).is_equation() 

True 

sage: (b[0] <= b[1]).is_equation() 

False 

""" 

return self.equality 

  

def is_less_or_equal(self): 

""" 

Whether the constraint is a chained less-or_equal inequality 

  

OUTPUT: 

  

Boolean. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: (b[0] == b[1]).is_less_or_equal() 

False 

sage: (b[0] <= b[1]).is_less_or_equal() 

True 

""" 

return not self.equality 

  

def is_trivial(self): 

""" 

Test whether the constraint is trivial. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: LC = p.linear_constraints_parent() 

sage: ieq = LC(1,2); ieq 

1 <= 2 

sage: ieq.is_trivial() 

False 

  

sage: ieq = LC(1); ieq 

trivial constraint starting with 1 

sage: ieq.is_trivial() 

True 

""" 

return len(self.constraints) < 2 

  

def __iter__(self): 

""" 

Iterate over the terms of the chained (in)-equality 

  

OUTPUT: 

  

A generator yielding the individual terms of the constraint in 

left-to-right order. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: ieq = 1 <= b[0] <= b[2] <= 3 <= b[3]; ieq 

1 <= x_0 <= x_1 <= 3 <= x_2 

sage: list(ieq) 

[1, x_0, x_1, 3, x_2] 

sage: for term in ieq: 

....: print(term) 

1 

x_0 

x_1 

3 

x_2 

""" 

for term in self.constraints: 

yield term 

  

def equations(self): 

""" 

Iterate over the unchained(!) equations 

  

OUTPUT: 

  

An iterator over pairs ``(lhs, rhs)`` such that the individual 

equations are ``lhs == rhs``. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: eqns = 1 == b[0] == b[2] == 3 == b[3]; eqns 

1 == x_0 == x_1 == 3 == x_2 

sage: for lhs, rhs in eqns.equations(): 

....: print(str(lhs) + ' == ' + str(rhs)) 

1 == x_0 

x_0 == x_1 

x_1 == 3 

3 == x_2 

""" 

if not self.is_equation() or self.is_trivial(): 

return 

term_iter = iter(self) 

lhs = next(term_iter) 

rhs = next(term_iter) 

while True: 

yield (lhs, rhs) 

lhs = rhs 

rhs = next(term_iter) 

  

def inequalities(self): 

""" 

Iterate over the unchained(!) inequalities 

  

OUTPUT: 

  

An iterator over pairs ``(lhs, rhs)`` such that the individual 

equations are ``lhs <= rhs``. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: ieq = 1 <= b[0] <= b[2] <= 3 <= b[3]; ieq 

1 <= x_0 <= x_1 <= 3 <= x_2 

  

sage: for lhs, rhs in ieq.inequalities(): 

....: print(str(lhs) + ' <= ' + str(rhs)) 

1 <= x_0 

x_0 <= x_1 

x_1 <= 3 

3 <= x_2 

""" 

if not self.is_less_or_equal() or self.is_trivial(): 

return 

term_iter = iter(self) 

lhs = next(term_iter) 

rhs = next(term_iter) 

while True: 

yield (lhs, rhs) 

lhs = rhs 

rhs = next(term_iter) 

  

def _repr_(self): 

r""" 

Returns a string representation of the constraint. 

  

OUTPUT: 

  

String. 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: b[3] <= b[8] + 9 

x_0 <= 9 + x_1 

  

sage: LC = p.linear_constraints_parent() 

sage: LC(b[3], b[8] + 9) 

x_0 <= 9 + x_1 

sage: LC(b[3]) 

trivial constraint starting with x_0 

""" 

comparator = ( ' == ' if self.equality else ' <= ' ) 

result = comparator.join(map(str, self)) 

if self.is_trivial(): 

return 'trivial constraint starting with '+result 

return result 

  

def __nonzero__(self): 

""" 

Part of the hack to allow chained (in)equalities 

  

EXAMPLES:: 

  

sage: p = MixedIntegerLinearProgram() 

sage: b = p.new_variable() 

sage: ieq = (b[3] <= b[8] + 9) 

sage: ieq <= ieq <= ieq 

x_0 <= 9 + x_1 <= x_0 <= 9 + x_1 <= x_0 <= 9 + x_1 

""" 

global chained_comparator_replace 

chained_comparator_replace = self 

return True