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

r""" 

Common Interface Functionality 

 

See the examples in the other sections for how to use specific 

interfaces. The interface classes all derive from the generic 

interface that is described in this section. 

 

AUTHORS: 

 

- William Stein (2005): initial version 

 

- William Stein (2006-03-01): got rid of infinite loop on startup if 

client system missing 

 

- Felix Lawrence (2009-08-21): edited ._sage_() to support lists and float exponents in foreign notation. 

 

- Simon King (2010-09-25): Expect._local_tmpfile() depends on 

Expect.pid() and is cached; Expect.quit() clears that cache, 

which is important for forking. 

 

- Jean-Pierre Flori (2010,2011): Split non Pexpect stuff into a parent class. 

 

- Simon King (2015): Improve pickling for InterfaceElement 

""" 

 

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

# Copyright (C) 2005 William Stein <wstein@gmail.com> 

# 

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

# 

# This code is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 

# General Public License for more details. 

# 

# The full text of the GPL is available at: 

# 

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

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

from __future__ import print_function 

from six import iteritems, integer_types, string_types 

 

import operator 

 

from sage.structure.sage_object import SageObject 

from sage.structure.parent_base import ParentWithBase 

from sage.structure.element import Element, parent 

 

import sage.misc.sage_eval 

from sage.misc.fast_methods import WithEqualityById 

from sage.docs.instancedoc import instancedoc 

 

 

class AsciiArtString(str): 

def __repr__(self): 

return str(self) 

 

 

class Interface(WithEqualityById, ParentWithBase): 

""" 

Interface interface object. 

 

.. NOTE:: 

 

Two interfaces compare equal if and only if they are identical 

objects (this is a critical constraint so that caching of 

representations of objects in interfaces works 

correctly). Otherwise they are never equal. 

""" 

def __init__(self, name): 

""" 

Initialize ``self``. 

 

EXAMPLES:: 

 

sage: Maxima() == maxima 

False 

sage: maxima == maxima 

True 

 

sage: Maxima() != maxima 

True 

sage: maxima != maxima 

False 

""" 

self.__name = name 

self.__coerce_name = '_' + name.lower() + '_' 

self.__seq = -1 

self._available_vars = [] 

self._seed = None 

ParentWithBase.__init__(self, self) 

 

def _repr_(self): 

return self.__name.capitalize() 

 

def name(self, new_name=None): 

return self.__name 

 

def get_seed(self): 

""" 

Return the seed used to set the random number generator in 

this interface. 

 

The seed is initialized as ``None`` but should be set when the 

interface starts. 

 

EXAMPLES:: 

 

sage: s = Singular() 

sage: s.set_seed(107) 

107 

sage: s.get_seed() 

107 

""" 

return self._seed 

 

def rand_seed(self): 

""" 

Return a random seed that can be put into ``set_seed`` function 

for any interpreter. 

 

This should be overridden if the particular interface needs 

something other than a small positive integer. 

 

EXAMPLES:: 

 

sage: from sage.interfaces.interface import Interface 

sage: i = Interface("") 

sage: i.rand_seed() # random 

318491487L 

 

sage: s = Singular() 

sage: s.rand_seed() # random 

365260051L 

""" 

from sage.misc.randstate import randstate 

return randstate().seed()&0x1FFFFFFF 

 

def set_seed(self, seed=None): 

""" 

Set the random seed for the interpreter and return the new 

value of the seed. 

 

This is dependent on which interpreter so must be implemented 

in each separately. For examples see gap.py or singular.py. 

 

If seed is ``None`` then should generate a random seed. 

 

EXAMPLES:: 

 

sage: s = Singular() 

sage: s.set_seed(1) 

1 

sage: [s.random(1,10) for i in range(5)] 

[8, 10, 4, 9, 1] 

 

sage: from sage.interfaces.interface import Interface 

sage: i = Interface("") 

sage: i.set_seed() 

Traceback (most recent call last): 

... 

NotImplementedError: This interpreter did not implement a set_seed function 

""" 

raise NotImplementedError("This interpreter did not implement a set_seed function") 

 

def interact(self): 

r""" 

This allows you to interactively interact with the child 

interpreter. Press Ctrl-D or type 'quit' or 'exit' to exit and 

return to Sage. 

 

.. note:: 

 

This is completely different than the console() member 

function. The console function opens a new copy of the 

child interpreter, whereas the interact function gives you 

interactive access to the interpreter that is being used by 

Sage. Use sage(xxx) or interpretername(xxx) to pull objects 

in from sage to the interpreter. 

""" 

from sage.repl.interpreter import interface_shell_embed 

shell = interface_shell_embed(self) 

try: 

ipython = get_ipython() 

except NameError: 

shell() 

else: 

shell(local_ns=dict(ipython.user_ns)) 

 

def _pre_interact(self): 

pass 

 

def _post_interact(self): 

pass 

 

def cputime(self): 

""" 

CPU time since this process started running. 

""" 

raise NotImplementedError 

 

def read(self, filename): 

r""" 

EXAMPLES:: 

 

sage: filename = tmp_filename() 

sage: f = open(filename, 'w') 

sage: _ = f.write('x = 2\n') 

sage: f.close() 

sage: octave.read(filename) # optional - octave 

sage: octave.get('x') # optional - octave 

' 2' 

sage: import os 

sage: os.unlink(filename) 

""" 

self.eval(self._read_in_file_command(filename)) 

 

def _read_in_file_command(self, filename): 

raise NotImplementedError 

 

def eval(self, code, **kwds): 

""" 

Evaluate code in an interface. 

 

This method needs to be implemented in sub-classes. 

 

Note that it is not always to be expected that 

it returns a non-empty string. In contrast, 

:meth:`get` is supposed to return the result of applying 

a print command to the object so that the output is easier 

to parse. 

 

Likewise, the method :meth:`_eval_line` for evaluation of a single 

line, often makes sense to be overridden. 

""" 

raise NotImplementedError 

 

_eval_line = eval 

 

def execute(self, *args, **kwds): 

return self.eval(*args, **kwds) 

 

def __call__(self, x, name=None): 

 

r""" 

Create a new object in self from x. 

 

The object X returned can be used like any Sage object, and 

wraps an object in self. The standard arithmetic operators 

work. Moreover if foo is a function then 

X.foo(y,z,...) 

calls foo(X, y, z, ...) and returns the corresponding object. 

 

EXAMPLES:: 

 

sage: gp(2) 

2 

sage: gp('2') 

2 

sage: a = gp(2); gp(a) is a 

True 

 

""" 

cls = self._object_class() 

 

#Handle the case when x is an object 

#in some interface. 

if isinstance(x, InterfaceElement): 

if x.parent() is self: 

return x 

 

#We convert x into an object in this 

#interface by first going through Sage. 

try: 

return self(x._sage_()) 

except (NotImplementedError, TypeError): 

pass 

 

if isinstance(x, string_types): 

return cls(self, x, name=name) 

try: 

return self._coerce_from_special_method(x) 

except TypeError: 

raise 

except AttributeError: 

pass 

try: 

return self._coerce_impl(x, use_special=False) 

except TypeError as msg: 

try: 

return cls(self, str(x), name=name) 

except TypeError: 

raise TypeError(msg) 

 

def _coerce_from_special_method(self, x): 

""" 

Tries to coerce to self by calling a special underscore method. 

 

If no such method is defined, raises an AttributeError instead of a 

TypeError. 

""" 

s = '_%s_'%self.name() 

if s == '_maxima_lib_': 

s = '_maxima_' 

if s == '_pari_': 

s = '_gp_' 

try: 

return (x.__getattribute__(s))(self) 

except AttributeError: 

return self(x._interface_init_()) 

 

def _coerce_impl(self, x, use_special=True): 

if isinstance(x, integer_types): 

import sage.rings.all 

return self(sage.rings.all.Integer(x)) 

elif isinstance(x, float): 

import sage.rings.all 

return self(sage.rings.all.RDF(x)) 

if use_special: 

try: 

return self._coerce_from_special_method(x) 

except AttributeError: 

pass 

 

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

A = [] 

z = [] 

cls = self._object_class() 

for v in x: 

if isinstance(v, cls): 

A.append(v.name()) 

z.append(v) 

else: 

w = self(v) 

A.append(w.name()) 

z.append(w) 

X = ','.join(A) 

r = self.new('%s%s%s'%(self._left_list_delim(), X, self._right_list_delim())) 

r.__sage_list = z # do this to avoid having the entries of the list be garbage collected 

return r 

 

raise TypeError("unable to coerce element into %s"%self.name()) 

 

def new(self, code): 

return self(code) 

 

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

# these should all be appropriately overloaded by the derived class 

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

 

def _left_list_delim(self): 

return "[" 

 

def _right_list_delim(self): 

return "]" 

 

def _left_func_delim(self): 

return "(" 

 

def _right_func_delim(self): 

return ")" 

 

def _assign_symbol(self): 

return "=" 

 

def _equality_symbol(self): 

raise NotImplementedError 

 

# For efficiency purposes, you should definitely override these 

# in your derived class. 

def _true_symbol(self): 

try: 

return self.__true_symbol 

except AttributeError: 

self.__true_symbol = self.get('1 %s 1'%self._equality_symbol()) 

return self.__true_symbol 

 

def _false_symbol(self): 

try: 

return self.__false_symbol 

except AttributeError: 

self.__false_symbol = self.get('1 %s 2'%self._equality_symbol()) 

return self.__false_symbol 

 

def _lessthan_symbol(self): 

return '<' 

 

def _greaterthan_symbol(self): 

return '>' 

 

def _inequality_symbol(self): 

return '!=' 

 

def _relation_symbols(self): 

""" 

Returns a dictionary with operators as the keys and their 

string representation as the values. 

 

EXAMPLES:: 

 

sage: import operator 

sage: symbols = mathematica._relation_symbols() 

sage: symbols[operator.eq] 

'==' 

""" 

return dict([(operator.eq, self._equality_symbol()), (operator.ne, self._inequality_symbol()), 

(operator.lt, self._lessthan_symbol()), (operator.le, "<="), 

(operator.gt, self._greaterthan_symbol()), (operator.ge, ">=")]) 

 

def _exponent_symbol(self): 

""" 

Return the symbol used to denote *10^ in floats, e.g 'e' in 1.5e6 

 

EXAMPLES:: 

 

sage: from sage.interfaces.expect import Expect 

sage: Expect('nonexistent_interface', 'fake')._exponent_symbol() 

'e' 

""" 

return 'e' 

 

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

# Functions for working with variables. 

# The first three must be overloaded by derived classes, 

# and the definition depends a lot on the class. But 

# the functionality one gets from this is very nice. 

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

 

def set(self, var, value): 

""" 

Set the variable var to the given value. 

""" 

cmd = '%s%s%s;'%(var,self._assign_symbol(), value) 

self.eval(cmd) 

 

def get(self, var): 

""" 

Get the value of the variable var. 

 

Note that this needs to be overridden in some interfaces, 

namely when getting the string representation of an object 

requires an explicit print command. 

""" 

return self.eval(var) 

 

def get_using_file(self, var): 

r""" 

Return the string representation of the variable var in self, 

possibly using a file. Use this if var has a huge string 

representation, since it may be way faster. 

 

.. warning:: 

 

In fact unless a special derived class implements this, it 

will *not* be any faster. This is the case for this class 

if you're reading it through introspection and seeing this. 

""" 

return self.get(var) 

 

def clear(self, var): 

""" 

Clear the variable named var. 

""" 

self._available_vars.append(var) 

 

def _next_var_name(self): 

if len(self._available_vars) != 0: 

v = self._available_vars[0] 

del self._available_vars[0] 

return v 

self.__seq += 1 

return "sage%s"%self.__seq 

 

def _create(self, value, name=None): 

name = self._next_var_name() if name is None else name 

self.set(name, value) 

return name 

 

def _object_class(self): 

""" 

EXAMPLES:: 

 

sage: from sage.interfaces.expect import Expect 

sage: Expect._object_class(maxima) 

<class 'sage.interfaces.expect.ExpectElement'> 

""" 

return InterfaceElement 

 

def _function_class(self): 

""" 

EXAMPLES:: 

 

sage: from sage.interfaces.interface import Interface 

sage: Interface._function_class(maxima) 

<class 'sage.interfaces.interface.InterfaceFunction'> 

""" 

return InterfaceFunction 

 

def _function_element_class(self): 

""" 

EXAMPLES:: 

 

sage: from sage.interfaces.interface import Interface 

sage: Interface._function_element_class(maxima) 

<class 'sage.interfaces.interface.InterfaceFunctionElement'> 

""" 

return InterfaceFunctionElement 

 

def _convert_args_kwds(self, args=None, kwds=None): 

""" 

Converts all of the args and kwds to be elements of this 

interface. 

 

EXAMPLES:: 

 

sage: args = [5] 

sage: kwds = {'x': 6} 

sage: args, kwds = gap._convert_args_kwds(args, kwds) 

sage: args 

[5] 

sage: list(map(type, args)) 

[<class 'sage.interfaces.gap.GapElement'>] 

sage: type(kwds['x']) 

<class 'sage.interfaces.gap.GapElement'> 

""" 

args = [] if args is None else args 

kwds = {} if kwds is None else kwds 

if not isinstance(args, list): 

args = [args] 

for i, arg in enumerate(args): 

if not isinstance(arg, InterfaceElement) or arg.parent() is not self: 

args[i] = self(arg) 

for key, value in iteritems(kwds): 

if not isinstance(value, InterfaceElement) or value.parent() is not self: 

kwds[key] = self(value) 

 

return args, kwds 

 

def _check_valid_function_name(self, function): 

""" 

Checks to see if function is a valid function name in this 

interface. If it is not, an exception is raised. Otherwise, nothing 

is done. 

 

EXAMPLES:: 

 

sage: gap._check_valid_function_name('SymmetricGroup') 

sage: gap._check_valid_function_name('') 

Traceback (most recent call last): 

... 

ValueError: function name must be nonempty 

sage: gap._check_valid_function_name('__foo') 

Traceback (most recent call last): 

... 

AttributeError 

""" 

if function == '': 

raise ValueError("function name must be nonempty") 

if function[:2] == "__": 

raise AttributeError 

 

def function_call(self, function, args=None, kwds=None): 

""" 

EXAMPLES:: 

 

sage: maxima.quad_qags(x, x, 0, 1, epsrel=1e-4) 

[0.5,0.55511151231257...e-14,21,0] 

sage: maxima.function_call('quad_qags', [x, x, 0, 1], {'epsrel':'1e-4'}) 

[0.5,0.55511151231257...e-14,21,0] 

""" 

args, kwds = self._convert_args_kwds(args, kwds) 

self._check_valid_function_name(function) 

s = self._function_call_string(function, 

[s.name() for s in args], 

['%s=%s'%(key,value.name()) for key, value in kwds.items()]) 

return self.new(s) 

 

def _function_call_string(self, function, args, kwds): 

""" 

Returns the string used to make function calls. 

 

EXAMPLES:: 

 

sage: maxima._function_call_string('diff', ['f(x)', 'x'], []) 

'diff(f(x),x)' 

""" 

return "%s(%s)"%(function, ",".join(list(args) + list(kwds))) 

 

def call(self, function_name, *args, **kwds): 

return self.function_call(function_name, args, kwds) 

 

def _contains(self, v1, v2): 

raise NotImplementedError 

 

def __getattr__(self, attrname): 

""" 

TESTS:: 

 

sage: ParentWithBase.__getattribute__(singular, '_coerce_map_from_') 

<bound method Singular._coerce_map_from_ of Singular> 

""" 

try: 

return ParentWithBase.__getattribute__(self, attrname) 

except AttributeError: 

if attrname[:1] == "_": 

raise 

return self._function_class()(self, attrname) 

 

def console(self): 

raise NotImplementedError 

 

def help(self, s): 

return AsciiArtString('No help on %s available'%s) 

 

 

@instancedoc 

class InterfaceFunction(SageObject): 

""" 

Interface function. 

""" 

def __init__(self, parent, name): 

self._parent = parent 

self._name = name 

 

def _repr_(self): 

return "%s"%self._name 

 

def __call__(self, *args, **kwds): 

return self._parent.function_call(self._name, list(args), kwds) 

 

def _instancedoc_(self): 

""" 

EXAMPLES:: 

 

sage: gp.gcd.__doc__ 

'gcd(x,{y}): greatest common divisor of x and y.' 

""" 

M = self._parent 

return M.help(self._name) 

 

 

@instancedoc 

class InterfaceFunctionElement(SageObject): 

""" 

Interface function element. 

""" 

def __init__(self, obj, name): 

self._obj = obj 

self._name = name 

 

def _repr_(self): 

return "%s" % self._name 

 

def __call__(self, *args, **kwds): 

return self._obj.parent().function_call(self._name, [self._obj] + list(args), kwds) 

 

def help(self): 

print(self.__doc__) 

 

def _instancedoc_(self): 

""" 

EXAMPLES:: 

 

sage: gp(2).gcd.__doc__ 

'gcd(x,{y}): greatest common divisor of x and y.' 

""" 

M = self._obj.parent() 

return M.help(self._name) 

 

 

 

def is_InterfaceElement(x): 

return isinstance(x, InterfaceElement) 

 

 

@instancedoc 

class InterfaceElement(Element): 

""" 

Interface element. 

""" 

def __init__(self, parent, value, is_name=False, name=None): 

Element.__init__(self, parent) 

self._create = value 

if parent is None: return # means "invalid element" 

# idea: Joe Wetherell -- try to find out if the output 

# is too long and if so get it using file, otherwise 

# don't. 

 

if is_name: 

self._name = value 

else: 

try: 

self._name = parent._create(value, name=name) 

except (TypeError, RuntimeError, ValueError) as x: 

raise TypeError(x) 

 

def _latex_(self): 

# return "\\begin{verbatim}%s\\end{verbatim}"%self 

string = str(self) 

if not '|' in string: 

delim = '|' 

elif not '#' in string: 

delim = '#' 

elif not '@' in string: 

delim = '@' 

elif not '~' in string: 

delim = '~' 

return "\\verb%s%s%s"%(delim, string, delim) 

 

def __iter__(self): 

for i in range(1, len(self)+1): 

yield self[i] 

 

def __len__(self): 

""" 

Call self.sage() and return the length of that sage object. 

 

This approach is inefficient - each interface should override 

this method with one that calls the external program's length 

function. 

 

EXAMPLES:: 

 

sage: len(gp([1,2,3])) 

3 

 

AUTHORS: 

 

- Felix Lawrence (2009-08-21) 

""" 

return len(self.sage()) 

 

def __reduce__(self): 

""" 

The default linearisation is to return self's parent, 

which will then get the items returned by :meth:`_reduce` 

as arguments to reconstruct the element. 

 

EXAMPLES:: 

 

sage: G = gap.SymmetricGroup(6) 

sage: loads(dumps(G)) == G # indirect doctest 

True 

sage: y = gap(34) 

sage: loads(dumps(y)) 

34 

sage: type(_) 

<class 'sage.interfaces.gap.GapElement'> 

sage: y = singular(34) 

sage: loads(dumps(y)) 

34 

sage: type(_) 

<class 'sage.interfaces.singular.SingularElement'> 

sage: G = gap.PolynomialRing(QQ, ['x']) 

sage: loads(dumps(G)) 

PolynomialRing( Rationals, ["x"] ) 

sage: S = singular.ring(0, ('x')) 

sage: loads(dumps(S)) 

polynomial ring, over a field, global ordering 

// coefficients: QQ 

// number of vars : 1 

// block 1 : ordering lp 

// : names x 

// block 2 : ordering C 

 

Here are further examples of pickling of interface elements:: 

 

sage: loads(dumps(gp('"abc"'))) 

abc 

sage: loads(dumps(gp([1,2,3]))) 

[1, 2, 3] 

sage: loads(dumps(pari('"abc"'))) 

"abc" 

sage: loads(dumps(pari([1,2,3]))) 

[1, 2, 3] 

sage: loads(dumps(r('"abc"'))) 

[1] "abc" 

sage: loads(dumps(r([1,2,3]))) 

[1] 1 2 3 

sage: loads(dumps(maxima([1,2,3]))) 

[1,2,3] 

 

Unfortunately, strings in maxima can't be pickled yet:: 

 

sage: loads(dumps(maxima('"abc"'))) 

Traceback (most recent call last): 

... 

TypeError: unable to make sense of Maxima expression '"abc"' in Sage 

 

""" 

return self.parent(), (self._reduce(),) 

 

def _reduce(self): 

""" 

Helper for pickling. 

 

By default, if self is a string, then the representation of 

that string is returned (not the string itself). Otherwise, 

it is attempted to return the corresponding Sage object. 

If this fails with a NotImplementedError, the string 

representation of self is returned instead. 

 

EXAMPLES:: 

 

sage: S = singular.ring(0, ('x')) 

sage: S._reduce() 

Univariate Polynomial Ring in x over Rational Field 

sage: G = gap.PolynomialRing(QQ, ['x']) 

sage: G._reduce() 

'PolynomialRing( Rationals, ["x"] )' 

sage: G.sage() 

Traceback (most recent call last): 

... 

NotImplementedError: Unable to parse output: PolynomialRing( Rationals, ["x"] ) 

sage: singular('"abc"')._reduce() 

"'abc'" 

sage: singular('1')._reduce() 

1 

 

""" 

if self.is_string(): 

return repr(self.sage()) 

try: 

return self.sage() 

except NotImplementedError: 

return repr(self) 

 

def __call__(self, *args): 

self._check_valid() 

P = self.parent() 

return getattr(P, self.name())(*args) 

 

def __contains__(self, x): 

P = self._check_valid() 

if not isinstance(x, InterfaceElement) or x.parent() is not self.parent(): 

x = P.new(x) 

return P._contains(x.name(), self.name()) 

 

def _instancedoc_(self): 

""" 

EXAMPLES:: 

 

sage: gp(2).__doc__ 

'2' 

""" 

return str(self) 

 

def __hash__(self): 

""" 

Returns the hash of self. This is a default implementation of hash 

which just takes the hash of the string of self. 

""" 

return hash('%s'%(self)) 

 

def __cmp__(self, other): 

""" 

Comparison of interface elements. 

 

NOTE: 

 

GAP has a special role here. It may in some cases raise an error 

when comparing objects, which is unwanted in Python. We catch 

these errors. Moreover, GAP does not recognise certain objects as 

equal even if there definitions are identical. 

 

NOTE: 

 

This methods need to be overridden if the subprocess would 

not return a string representation of a boolean value unless 

an explicit print command is used. 

 

TESTS: 

 

Here are examples in which GAP succeeds with a comparison:: 

 

sage: gap('SymmetricGroup(8)')==gap('SymmetricGroup(8)') 

True 

sage: gap('SymmetricGroup(8)')>gap('AlternatingGroup(8)') 

False 

sage: gap('SymmetricGroup(8)')<gap('AlternatingGroup(8)') 

True 

 

Here, GAP fails to compare, and so ``False`` is returned. 

In previous Sage versions, this example actually resulted 

in an error; compare :trac:`5962`. 

:: 

 

sage: gap('DihedralGroup(8)')==gap('DihedralGroup(8)') 

False 

 

""" 

P = self._check_valid() 

try: 

if P.eval("%s %s %s"%(self.name(), P._equality_symbol(), 

other.name())) == P._true_symbol(): 

return 0 

except RuntimeError: 

pass 

try: 

if P.eval("%s %s %s"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): 

return -1 

except RuntimeError: 

pass 

try: 

if P.eval("%s %s %s"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): 

return 1 

except Exception: 

pass 

 

# everything is supposed to be comparable in Python, so we define 

# the comparison thus when no comparison is available in interfaced system. 

if (hash(self) < hash(other)): 

return -1 

else: 

return 1 

 

def is_string(self): 

""" 

Tell whether this element is a string. 

 

By default, the answer is negative. 

""" 

return False 

 

def _matrix_(self, R): 

raise NotImplementedError 

 

def _vector_(self, R): 

raise NotImplementedError 

 

def _check_valid(self): 

""" 

Check that this object is valid, i.e., the session in which this 

object is defined is still running. This is relevant for 

interpreters that can't be interrupted via ctrl-C, hence get 

restarted. 

""" 

try: 

P = self.parent() 

if P is None: 

raise ValueError("The %s session in which this object was defined is no longer running."%P.name()) 

except AttributeError: 

raise ValueError("The session in which this object was defined is no longer running.") 

return P 

 

def __del__(self): 

try: 

self._check_valid() 

except ValueError: 

return 

if hasattr(self,'_name'): 

P = self.parent() 

if not (P is None): 

P.clear(self._name) 

 

def _sage_repr(self): 

""" 

Return a sage-friendly string representation of the object. 

 

Some programs use different notation to Sage, e.g. Mathematica 

writes lists with {} instead of []. This method calls repr(self) 

then converts the foreign notation into Sage's notation. 

 

OUTPUT: 

 

A string representation of the object that is ready for 

sage_eval(). 

 

EXAMPLES:: 

 

sage: repr(mathematica([1,2,3])) # optional - mathematica 

'{1, 2, 3}' 

sage: mathematica([1,2,3])._sage_repr() # optional - mathematica 

'[1, 2, 3]' 

 

:: 

 

sage: gp(10.^80)._sage_repr() 

'1.0000000000000000000000000000000000000e80' # 64-bit 

'1.000000000000000000000000000e80' # 32-bit 

sage: mathematica('10.^80')._sage_repr() # optional - mathematica 

'1.e80' 

 

AUTHORS: 

 

- Felix Lawrence (2009-08-21) 

""" 

#TO DO: this could use file transfers when self.is_remote() 

 

string = repr(self).replace('\n',' ').replace('\r', '') 

# Translate the external program's function notation to Sage's 

lfd = self.parent()._left_func_delim() 

if '(' != lfd: string = string.replace(lfd, '(') 

rfd = self.parent()._right_func_delim() 

if ')' != rfd: string = string.replace(rfd, ')') 

# Translate the external program's list formatting to Sage's 

lld = self.parent()._left_list_delim() 

if '[' != lld: string = string.replace(lld, '[') 

rld = self.parent()._right_list_delim() 

if ']' != rld: string = string.replace(rld, ']') 

# Translate the external program's exponent formatting 

expl = self.parent()._exponent_symbol() 

if 'e' != expl: string = string.replace(expl, 'e') 

return string 

 

def _sage_(self): 

""" 

Attempt to return a Sage version of this object. 

This is a generic routine that just tries to evaluate 

the repr(self). 

 

EXAMPLES:: 

 

sage: gp(1/2)._sage_() 

1/2 

sage: _.parent() 

Rational Field 

 

AUTHORS: 

 

- William Stein 

 

- Felix Lawrence (2009-08-21) 

""" 

string = self._sage_repr() 

try: 

return sage.misc.sage_eval.sage_eval(string) 

except Exception: 

raise NotImplementedError("Unable to parse output: %s" % string) 

 

 

def sage(self, *args, **kwds): 

""" 

Attempt to return a Sage version of this object. 

 

This method does nothing more than calling :meth:`_sage_`, 

simply forwarding any additional arguments. 

 

EXAMPLES:: 

 

sage: gp(1/2).sage() 

1/2 

sage: _.parent() 

Rational Field 

sage: singular.lib("matrix") 

sage: R = singular.ring(0, '(x,y,z)', 'dp') 

sage: singular.matrix(2,2).sage() 

[0 0] 

[0 0] 

""" 

return self._sage_(*args, **kwds) 

 

def __repr__(self): 

""" 

To obtain the string representation, it is first checked whether 

the element is still valid. Then, if ``self._cached_repr`` is 

a string then it is returned. Otherwise, ``self._repr_()`` 

is called (and the result is cached, if ``self._cached_repr`` 

evaluates to ``True``). 

 

If the string obtained so far contains ``self._name``, then it 

is replaced by ``self``'s custom name, if available. 

 

To implement a custom string representation, override the method 

``_repr_``, but do not override this double underscore method. 

 

EXAMPLE: 

 

Here is one example showing that the string representation will 

be cached when requested:: 

 

sage: from sage.interfaces.maxima_lib import maxima_lib 

sage: M = maxima_lib('sqrt(2) + 1/3') 

sage: M._cached_repr 

True 

sage: repr(M) is repr(M) # indirect doctest 

True 

sage: M._cached_repr 

'sqrt(2)+1/3' 

sage: M 

sqrt(2)+1/3 

 

If the interface breaks then it is reflected in the string representation:: 

 

sage: s = singular('2') 

sage: s 

2 

sage: singular.quit() 

sage: s 

(invalid Singular object -- The singular session in which this object was defined is no longer running.) 

 

""" 

try: 

P = self._check_valid() 

except ValueError as msg: 

return '(invalid {} object -- {})'.format(self.parent() or type(self), msg) 

cr = getattr(self, '_cached_repr', None) 

if isinstance(cr, string_types): 

s = cr 

else: 

s = self._repr_() 

if self._name in s: 

try: 

s = s.replace(self._name, getattr(self, '__custom_name')) 

except AttributeError: 

pass 

if cr: 

self._cached_repr = s 

return s 

 

def _repr_(self): 

""" 

Default implementation of a helper method for string representation. 

 

It is supposed that immediately before calling this method, 

the validity of ``self``'s parent was confirmed. So, when you 

override this method, you can assume that the parent is valid. 

 

TESTS: 

 

In :trac:`22501`, several string representation methods have been 

removed in favour of using the default implementation. The corresponding 

tests have been moved here:: 

 

sage: gap(SymmetricGroup(8)) # indirect doctest 

SymmetricGroup( [ 1 .. 8 ] ) 

sage: gap(2) 

2 

sage: x = var('x') 

sage: giac(x) 

x 

sage: giac(5) 

5 

sage: M = matrix(QQ,2,range(4)) 

sage: giac(M) 

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

sage: x = var('x') # optional - maple 

sage: maple(x) # optional - maple 

x 

sage: maple(5) # optional - maple 

5 

sage: M = matrix(QQ,2,range(4)) # optional - maple 

sage: maple(M) # optional - maple 

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

sage: maxima('sqrt(2) + 1/3') 

sqrt(2)+1/3 

sage: mupad.package('"MuPAD-Combinat"') # optional - mupad-Combinat 

sage: S = mupad.examples.SymmetricFunctions(); S # optional - mupad-Combinat 

examples::SymmetricFunctions(Dom::ExpressionField()) 

 

""" 

P = self.parent() 

try: 

if self._get_using_file: 

return P.get_using_file(self._name).rstrip() 

except AttributeError: 

return self.parent().get(self._name).rstrip() 

 

def __getattr__(self, attrname): 

P = self._check_valid() 

if attrname[:1] == "_": 

raise AttributeError 

return P._function_element_class()(self, attrname) 

 

def get_using_file(self): 

""" 

Return this element's string representation using a file. Use this 

if self has a huge string representation. It'll be way faster. 

 

EXAMPLES:: 

 

sage: a = maxima(str(2^1000)) 

sage: a.get_using_file() 

'10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376' 

""" 

try: 

self._check_valid() 

except ValueError as msg: 

return '(invalid {} object -- {})'.format(self.parent() or type(self), msg) 

return self.parent().get_using_file(self._name) 

 

def hasattr(self, attrname): 

""" 

Returns whether the given attribute is already defined by this 

object, and in particular is not dynamically generated. 

 

EXAMPLES:: 

 

sage: m = maxima('2') 

sage: m.hasattr('integral') 

True 

sage: m.hasattr('gcd') 

False 

""" 

return not isinstance(getattr(self, attrname), (InterfaceFunctionElement, InterfaceElement)) 

 

def attribute(self, attrname): 

""" 

If this wraps the object x in the system, this returns the object 

x.attrname. This is useful for some systems that have object 

oriented attribute access notation. 

 

EXAMPLES:: 

 

sage: g = gap('SO(1,4,7)') 

sage: k = g.InvariantQuadraticForm() 

sage: k.attribute('matrix') 

[ [ 0*Z(7), Z(7)^0, 0*Z(7), 0*Z(7) ], [ 0*Z(7), 0*Z(7), 0*Z(7), 0*Z(7) ], 

[ 0*Z(7), 0*Z(7), Z(7), 0*Z(7) ], [ 0*Z(7), 0*Z(7), 0*Z(7), Z(7)^0 ] ] 

 

:: 

 

sage: e = gp('ellinit([0,-1,1,-10,-20])') 

sage: e.attribute('j') 

-122023936/161051 

""" 

P = self._check_valid() 

return P('%s.%s'%(self.name(), attrname)) 

 

def __getitem__(self, n): 

P = self._check_valid() 

if not isinstance(n, tuple): 

return P.new('%s[%s]'%(self._name, n)) 

else: 

return P.new('%s[%s]'%(self._name, str(n)[1:-1])) 

 

def __int__(self): 

""" 

EXAMPLES:: 

 

sage: int(maxima('1')) 

1 

sage: type(_) 

<... 'int'> 

""" 

return int(repr(self)) 

 

def bool(self): 

""" 

Return whether this element is equal to ``True``. 

 

NOTE: 

 

This method needs to be overridden if the subprocess would 

not return a string representation of a boolean value unless 

an explicit print command is used. 

 

EXAMPLES:: 

 

sage: singular(0).bool() 

False 

sage: singular(1).bool() 

True 

 

""" 

P = self._check_valid() 

t = P._true_symbol() 

cmd = '%s %s %s'%(self._name, P._equality_symbol(), t) 

return P.eval(cmd) == t 

 

def __bool__(self): 

""" 

EXAMPLES:: 

 

sage: bool(maxima(0)) 

False 

sage: bool(maxima(1)) 

True 

""" 

return self.bool() 

 

__nonzero__ = __bool__ 

 

def __long__(self): 

""" 

EXAMPLES:: 

 

sage: m = maxima('1') 

sage: long(m) 

1L 

""" 

return long(repr(self)) 

 

def __float__(self): 

""" 

EXAMPLES:: 

 

sage: m = maxima('1/2') 

sage: m.__float__() 

0.5 

sage: float(m) 

0.5 

""" 

return float(repr(self)) 

 

def _integer_(self, ZZ=None): 

""" 

EXAMPLES:: 

 

sage: m = maxima('1') 

sage: m._integer_() 

1 

sage: _.parent() 

Integer Ring 

sage: QQ(m) 

1 

""" 

import sage.rings.all 

return sage.rings.all.Integer(repr(self)) 

 

def _rational_(self): 

""" 

EXAMPLES:: 

 

sage: m = maxima('1/2') 

sage: m._rational_() 

1/2 

sage: _.parent() 

Rational Field 

sage: QQ(m) 

1/2 

""" 

import sage.rings.all 

return sage.rings.all.Rational(repr(self)) 

 

def name(self, new_name=None): 

""" 

Returns the name of self. If new_name is passed in, then this 

function returns a new object identical to self whose name is 

new_name. 

 

Note that this can overwrite existing variables in the system. 

 

EXAMPLES:: 

 

sage: x = r([1,2,3]); x 

[1] 1 2 3 

sage: x.name() 

'sage3' 

sage: x = r([1,2,3]).name('x'); x 

[1] 1 2 3 

sage: x.name() 

'x' 

 

:: 

 

sage: s5 = gap.SymmetricGroup(5).name('s5') 

sage: s5 

SymmetricGroup( [ 1 .. 5 ] ) 

sage: s5.name() 

's5' 

""" 

if new_name is not None: 

if not isinstance(new_name, string_types): 

raise TypeError("new_name must be a string") 

p = self.parent() 

p.set(new_name, self._name) 

return p._object_class()(p, new_name, is_name=True) 

 

return self._name 

 

def gen(self, n): 

P = self._check_valid() 

return P.new('%s.%s'%(self._name, int(n))) 

 

def _operation(self, operation, other=None): 

r""" 

Return the result of applying the binary operation 

``operation`` on the arguments ``self`` and ``other``, or the 

unary operation on ``self`` if ``other`` is not given. 

 

This is a utility function which factors out much of the 

commonality used in the arithmetic operations for interface 

elements. 

 

INPUT: 

 

- ``operation`` -- a string representing the operation 

being performed. For example, '*', or '1/'. 

 

- ``other`` -- the other operand. If ``other`` is ``None``, 

then the operation is assumed to be unary rather than binary. 

 

OUTPUT: an interface element 

 

EXAMPLES:: 

 

sage: a = gp('23') 

sage: b = gp('5') 

sage: a._operation('%', b) 

3 

sage: a._operation('19+') 

42 

sage: a._operation('!@#$%') 

Traceback (most recent call last): 

... 

TypeError: Error executing code in GP:... 

""" 

P = self._check_valid() 

if other is None: 

cmd = '%s %s'%(operation, self._name) 

else: 

cmd = '%s %s %s'%(self._name, operation, other._name) 

try: 

return P.new(cmd) 

except Exception as msg: 

raise TypeError(msg) 

 

def _add_(self, right): 

""" 

EXAMPLES:: 

 

sage: f = maxima.cos(x) 

sage: g = maxima.sin(x) 

sage: f + g 

sin(_SAGE_VAR_x)+cos(_SAGE_VAR_x) 

sage: f + 2 

cos(_SAGE_VAR_x)+2 

sage: 2 + f 

cos(_SAGE_VAR_x)+2 

 

:: 

 

sage: x,y = var('x,y') 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima.function('x','-cos(x)') 

sage: f+g 

sin(x)-cos(x) 

sage: f+3 

sin(x)+3 

 

The Maxima variable ``x`` is different from the Sage symbolic variable:: 

 

sage: (f+maxima.cos(x)) 

sin(x)+cos(_SAGE_VAR_x) 

sage: (f+maxima.cos(y)) 

sin(x)+cos(_SAGE_VAR_y) 

 

Note that you may get unexpected results when calling symbolic expressions 

and not explicitly giving the variables:: 

 

sage: (f+maxima.cos(x))(2) 

cos(_SAGE_VAR_x)+sin(2) 

sage: (f+maxima.cos(y))(2) 

cos(_SAGE_VAR_y)+sin(2) 

""" 

return self._operation("+", right) 

 

def _sub_(self, right): 

""" 

EXAMPLES:: 

 

sage: f = maxima.cos(x) 

sage: g = maxima.sin(x) 

sage: f - g 

cos(_SAGE_VAR_x)-sin(_SAGE_VAR_x) 

sage: f - 2 

cos(_SAGE_VAR_x)-2 

sage: 2 - f 

2-cos(_SAGE_VAR_x) 

 

:: 

 

sage: x,y = var('x,y') 

sage: f = maxima.function('x','sin(x)') 

 

The Maxima variable ``x`` is different from the Sage symbolic variable:: 

 

sage: (f-maxima.cos(x)) 

sin(x)-cos(_SAGE_VAR_x) 

sage: (f-maxima.cos(y)) 

sin(x)-cos(_SAGE_VAR_y) 

 

Note that you may get unexpected results when calling symbolic expressions 

and not explicitly giving the variables:: 

 

sage: (f-maxima.cos(x))(2) 

sin(2)-cos(_SAGE_VAR_x) 

sage: (f-maxima.cos(y))(2) 

sin(2)-cos(_SAGE_VAR_y) 

""" 

return self._operation('-', right) 

 

def _neg_(self): 

""" 

EXAMPLES:: 

 

sage: f = maxima('sin(x)') 

sage: -f 

-sin(x) 

sage: f = maxima.function('x','sin(x)') 

sage: -f 

-sin(x) 

""" 

return self._operation('-') 

 

def _mul_(self, right): 

""" 

EXAMPLES:: 

 

sage: f = maxima.cos(x) 

sage: g = maxima.sin(x) 

sage: f*g 

cos(_SAGE_VAR_x)*sin(_SAGE_VAR_x) 

sage: 2*f 

2*cos(_SAGE_VAR_x) 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') # not a function! 

sage: f*g 

-cos(x)*sin(x) 

sage: _(2) 

-cos(2)*sin(2) 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') 

sage: g*f 

-cos(x)*sin(x) 

sage: _(2) 

-cos(2)*sin(2) 

sage: 2*f 

2*sin(x) 

""" 

return self._operation('*', right) 

 

def _div_(self, right): 

""" 

EXAMPLES:: 

 

sage: f = maxima.cos(x) 

sage: g = maxima.sin(x) 

sage: f/g 

cos(_SAGE_VAR_x)/sin(_SAGE_VAR_x) 

sage: f/2 

cos(_SAGE_VAR_x)/2 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') 

sage: f/g 

-sin(x)/cos(x) 

sage: _(2) 

-sin(2)/cos(2) 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') 

sage: g/f 

-cos(x)/sin(x) 

sage: _(2) 

-cos(2)/sin(2) 

sage: 2/f 

2/sin(x) 

""" 

return self._operation("/", right) 

 

def __invert__(self): 

""" 

EXAMPLES:: 

 

sage: f = maxima('sin(x)') 

sage: ~f 

1/sin(x) 

sage: f = maxima.function('x','sin(x)') 

sage: ~f 

1/sin(x) 

""" 

return self._operation('1/') 

 

def _mod_(self, right): 

""" 

EXAMPLES:: 

 

sage: f = gp("x^3 + x") 

sage: g = gp("2*x + 1") 

sage: f % g 

-5/8 

""" 

return self._operation("%", right) 

 

def __pow__(self, n): 

""" 

EXAMPLES:: 

 

sage: a = maxima('2') 

sage: a^(3/4) 

2^(3/4) 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') 

sage: f^g 

1/sin(x)^cos(x) 

 

:: 

 

sage: f = maxima.function('x','sin(x)') 

sage: g = maxima('-cos(x)') # not a function 

sage: g^f 

(-cos(x))^sin(x) 

""" 

P = self._check_valid() 

if parent(n) is not P: 

n = P(n) 

return self._operation("^", n)