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

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

# http://pyrocko.org - GPLv3 

# 

# The Pyrocko Developers, 21st Century 

# ---|P------/S----------~Lg---------- 

''' 

Snuffling infrastructure 

 

This module provides the base class :py:class:`Snuffling` for user-defined 

snufflings and some utilities for their handling. 

''' 

from __future__ import absolute_import 

 

import os 

import sys 

import logging 

import traceback 

import tempfile 

 

from .qt_compat import qc, qw, getSaveFileName, use_pyqt5 

 

from pyrocko import pile, config 

from pyrocko.util import quote 

 

from .util import (ValControl, LinValControl, FigureFrame, WebKitFrame, 

VTKFrame, PixmapFrame, Marker, EventMarker, PhaseMarker, 

load_markers, save_markers) 

 

 

if sys.version_info >= (3, 0): 

from importlib import reload 

 

 

Marker, load_markers, save_markers # noqa 

 

logger = logging.getLogger('pyrocko.gui.snuffling') 

 

 

def fnpatch(x): 

if use_pyqt5: 

return x 

else: 

return x, None 

 

 

class MyFrame(qw.QFrame): 

widgetVisibilityChanged = qc.pyqtSignal(bool) 

 

def showEvent(self, ev): 

self.widgetVisibilityChanged.emit(True) 

 

def hideEvent(self, ev): 

self.widgetVisibilityChanged.emit(False) 

 

 

class Param(object): 

''' 

Definition of an adjustable floating point parameter for the 

snuffling. The snuffling may display controls for user input for 

such parameters. 

 

:param name: labels the parameter on the snuffling's control panel 

:param ident: identifier of the parameter 

:param default: default value 

:param minimum: minimum value for the parameter 

:param maximum: maximum value for the parameter 

:param low_is_none: if ``True``: parameter is set to None at lowest value 

of parameter range (optional) 

:param high_is_none: if ``True``: parameter is set to None at highest value 

of parameter range (optional) 

:param low_is_zero: if ``True``: parameter is set to value 0 at lowest 

value of parameter range (optional) 

''' 

 

def __init__( 

self, name, ident, default, minimum, maximum, 

low_is_none=None, 

high_is_none=None, 

low_is_zero=False): 

 

if low_is_none and default == minimum: 

default = None 

if high_is_none and default == maximum: 

default = None 

 

self.name = name 

self.ident = ident 

self.default = default 

self.minimum = minimum 

self.maximum = maximum 

self.low_is_none = low_is_none 

self.high_is_none = high_is_none 

self.low_is_zero = low_is_zero 

self._control = None 

 

 

class Switch(object): 

''' 

Definition of a boolean switch for the snuffling. The snuffling 

may display a checkbox for such a switch. 

 

:param name: labels the switch on the snuffling's control panel 

:param ident: identifier of the parameter 

:param default: default value 

''' 

 

def __init__(self, name, ident, default): 

self.name = name 

self.ident = ident 

self.default = default 

 

 

class Choice(object): 

''' 

Definition of a string choice for the snuffling. The snuffling 

may display a menu for such a choice. 

 

:param name: labels the menu on the snuffling's control panel 

:param ident: identifier of the parameter 

:param default: default value 

:param choices: tuple of other options 

''' 

 

def __init__(self, name, ident, default, choices): 

self.name = name 

self.ident = ident 

self.default = default 

self.choices = choices 

 

 

class Snuffling(object): 

'''Base class for user snufflings. 

 

Snufflings are plugins for snuffler (and other applications using the 

:py:class:`pyrocko.pile_viewer.PileOverview` class defined in 

``pile_viewer.py``). They can be added, removed and reloaded at runtime and 

should provide a simple way of extending the functionality of snuffler. 

 

A snuffling has access to all data available in a pile viewer, can process 

this data and can create and add new traces and markers to the viewer. 

''' 

 

def __init__(self): 

self._path = None 

 

self._name = 'Untitled Snuffling' 

self._viewer = None 

self._tickets = [] 

self._markers = [] 

 

self._delete_panel = None 

self._delete_menuitem = None 

 

self._panel_parent = None 

self._menu_parent = None 

 

self._panel = None 

self._menuitem = None 

self._helpmenuitem = None 

self._parameters = [] 

self._param_controls = {} 

 

self._triggers = [] 

 

self._live_update = True 

self._previous_output_filename = None 

self._previous_input_filename = None 

self._previous_input_directory = None 

 

self._tempdir = None 

self._iplot = 0 

 

self._have_pre_process_hook = False 

self._have_post_process_hook = False 

self._pre_process_hook_enabled = False 

self._post_process_hook_enabled = False 

 

self._no_viewer_pile = None 

self._cli_params = {} 

self._filename = None 

self._force_panel = False 

 

def setup(self): 

''' 

Setup the snuffling. 

 

This method should be implemented in subclass and contain e.g. calls to 

:py:meth:`set_name` and :py:meth:`add_parameter`. 

''' 

 

pass 

 

def module_dir(self): 

''' 

Returns the path of the directory where snufflings are stored. 

 

The default path is ``$HOME/.snufflings``. 

''' 

 

return self._path 

 

def init_gui(self, viewer, panel_parent, menu_parent, reloaded=False): 

''' 

Set parent viewer and hooks to add panel and menu entry. 

 

This method is called from the 

:py:class:`pyrocko.pile_viewer.PileOverview` object. Calls 

:py:meth:`setup_gui`. 

''' 

 

self._viewer = viewer 

self._panel_parent = panel_parent 

self._menu_parent = menu_parent 

 

self.setup_gui(reloaded=reloaded) 

 

def setup_gui(self, reloaded=False): 

''' 

Create and add gui elements to the viewer. 

 

This method is initially called from :py:meth:`init_gui`. It is also 

called, e.g. when new parameters have been added or if the name of the 

snuffling has been changed. 

''' 

 

if self._panel_parent is not None: 

self._panel = self.make_panel(self._panel_parent) 

if self._panel: 

self._panel_parent.add_panel( 

self.get_name(), self._panel, reloaded) 

 

if self._menu_parent is not None: 

self._menuitem = self.make_menuitem(self._menu_parent) 

self._helpmenuitem = self.make_helpmenuitem(self._menu_parent) 

if self._menuitem: 

self._menu_parent.add_snuffling_menuitem(self._menuitem) 

 

if self._helpmenuitem: 

self._menu_parent.add_snuffling_help_menuitem( 

self._helpmenuitem) 

 

def set_force_panel(self, bool=True): 

''' 

Force to create a panel. 

 

:param bool: if ``True`` will create a panel with Help, Clear and Run 

button. 

''' 

 

self._force_panel = bool 

 

def make_cli_parser1(self): 

import optparse 

 

class MyOptionParser(optparse.OptionParser): 

def error(self, msg): 

logger.error(msg) 

self.exit(1) 

 

parser = MyOptionParser() 

 

parser.add_option( 

'--format', 

dest='format', 

default='from_extension', 

choices=( 

'mseed', 'sac', 'kan', 'segy', 'seisan', 'seisan.l', 

'seisan.b', 'gse1', 'gcf', 'yaff', 'datacube', 

'from_extension', 'detect'), 

help='assume files are of given FORMAT [default: \'%default\']') 

 

parser.add_option( 

'--pattern', 

dest='regex', 

metavar='REGEX', 

help='only include files whose paths match REGEX') 

 

self.add_params_to_cli_parser(parser) 

self.configure_cli_parser(parser) 

return parser 

 

def configure_cli_parser(self, parser): 

pass 

 

def cli_usage(self): 

return None 

 

def add_params_to_cli_parser(self, parser): 

 

for param in self._parameters: 

if isinstance(param, Param): 

parser.add_option( 

'--' + param.ident, 

dest=param.ident, 

default=param.default, 

type='float', 

help=param.name) 

 

def setup_cli(self): 

self.setup() 

parser = self.make_cli_parser1() 

(options, args) = parser.parse_args() 

 

for param in self._parameters: 

if isinstance(param, Param): 

setattr(self, param.ident, getattr(options, param.ident)) 

 

self._cli_params['regex'] = options.regex 

self._cli_params['format'] = options.format 

self._cli_params['sources'] = args 

 

return options, args, parser 

 

def delete_gui(self): 

''' 

Remove the gui elements of the snuffling. 

 

This removes the panel and menu entry of the widget from the viewer and 

also removes all traces and markers added with the 

:py:meth:`add_traces` and :py:meth:`add_markers` methods. 

''' 

 

self.cleanup() 

 

if self._panel is not None: 

self._panel_parent.remove_panel(self._panel) 

self._panel = None 

 

if self._menuitem is not None: 

self._menu_parent.remove_snuffling_menuitem(self._menuitem) 

self._menuitem = None 

 

if self._helpmenuitem is not None: 

self._menu_parent.remove_snuffling_help_menuitem( 

self._helpmenuitem) 

 

def set_name(self, name): 

''' 

Set the snuffling's name. 

 

The snuffling's name is shown as a menu entry and in the panel header. 

''' 

 

self._name = name 

self.reset_gui() 

 

def get_name(self): 

''' 

Get the snuffling's name. 

''' 

 

return self._name 

 

def set_have_pre_process_hook(self, bool): 

self._have_pre_process_hook = bool 

self._live_update = False 

self._pre_process_hook_enabled = False 

self.reset_gui() 

 

def set_have_post_process_hook(self, bool): 

self._have_post_process_hook = bool 

self._live_update = False 

self._post_process_hook_enabled = False 

self.reset_gui() 

 

def set_have_pile_changed_hook(self, bool): 

self._pile_ = False 

 

def enable_pile_changed_notifications(self): 

''' 

Get informed when pile changed. 

 

When activated, the :py:meth:`pile_changed` method is called on every 

update in the viewer's pile. 

''' 

 

viewer = self.get_viewer() 

viewer.pile_has_changed_signal.connect( 

self.pile_changed) 

 

def disable_pile_changed_notifications(self): 

''' 

Stop getting informed about changes in viewer's pile. 

''' 

 

viewer = self.get_viewer() 

viewer.pile_has_changed_signal.disconnect( 

self.pile_changed) 

 

def pile_changed(self): 

''' 

Called when the connected viewer's pile has changed. 

 

Must be activated with a call to 

:py:meth:`enable_pile_changed_notifications`. 

''' 

 

pass 

 

def reset_gui(self, reloaded=False): 

''' 

Delete and recreate the snuffling's panel. 

''' 

 

if self._panel or self._menuitem: 

sett = self.get_settings() 

self.delete_gui() 

self.setup_gui(reloaded=reloaded) 

self.set_settings(sett) 

 

def show_message(self, kind, message): 

''' 

Display a message box. 

 

:param kind: string defining kind of message 

:param message: the message to be displayed 

''' 

 

try: 

box = qw.QMessageBox(self.get_viewer()) 

box.setText('%s: %s' % (kind.capitalize(), message)) 

box.exec_() 

except NoViewerSet: 

pass 

 

def error(self, message): 

''' 

Show an error message box. 

 

:param message: specifying the error 

''' 

 

logger.error('%s: %s' % (self._name, message)) 

self.show_message('error', message) 

 

def warn(self, message): 

''' 

Display a warning message. 

 

:param message: specifying the warning 

''' 

 

logger.warning('%s: %s' % (self._name, message)) 

self.show_message('warning', message) 

 

def fail(self, message): 

''' 

Show an error message box and raise :py:exc:`SnufflingCallFailed` 

exception. 

 

:param message: specifying the error 

''' 

 

self.error(message) 

raise SnufflingCallFailed(message) 

 

def pylab(self, name=None, get='axes'): 

''' 

Create a :py:class:`FigureFrame` and return either the frame, 

a :py:class:`matplotlib.figure.Figure` instance or a 

:py:class:`matplotlib.axes.Axes` instance. 

 

:param name: labels the figure frame's tab 

:param get: 'axes'|'figure'|'frame' (optional) 

''' 

 

if name is None: 

self._iplot += 1 

name = 'Plot %i (%s)' % (self._iplot, self.get_name()) 

 

fframe = FigureFrame() 

self._panel_parent.add_tab(name, fframe) 

if get == 'axes': 

return fframe.gca() 

elif get == 'figure': 

return fframe.gcf() 

elif get == 'figure_frame': 

return fframe 

 

def figure(self, name=None): 

''' 

Returns a :py:class:`matplotlib.figure.Figure` instance 

which can be displayed within snuffler by calling 

:py:meth:`canvas.draw`. 

 

:param name: labels the tab of the figure 

''' 

 

return self.pylab(name=name, get='figure') 

 

def axes(self, name=None): 

''' 

Returns a :py:class:`matplotlib.axes.Axes` instance. 

 

:param name: labels the tab of axes 

''' 

 

return self.pylab(name=name, get='axes') 

 

def figure_frame(self, name=None): 

''' 

Create a :py:class:`pyrocko.gui.util.FigureFrame`. 

 

:param name: labels the tab figure frame 

''' 

 

return self.pylab(name=name, get='figure_frame') 

 

def pixmap_frame(self, filename=None, name=None): 

''' 

Create a :py:class:`pyrocko.gui.util.PixmapFrame`. 

 

:param name: labels the tab 

:param filename: name of file to be displayed 

''' 

 

f = PixmapFrame(filename) 

 

scroll_area = qw.QScrollArea() 

scroll_area.setWidget(f) 

scroll_area.setWidgetResizable(True) 

 

self._panel_parent.add_tab(name or "Pixmap", scroll_area) 

return f 

 

def web_frame(self, url=None, name=None): 

''' 

Creates a :py:class:`WebKitFrame` which can be used as a browser 

within snuffler. 

 

:param url: url to open 

:param name: labels the tab 

''' 

 

if name is None: 

self._iplot += 1 

name = 'Web browser %i (%s)' % (self._iplot, self.get_name()) 

 

f = WebKitFrame(url) 

self._panel_parent.add_tab(name, f) 

return f 

 

def vtk_frame(self, name=None, actors=None): 

''' 

Create a :py:class:`pyrocko.gui.util.VTKFrame` to render interactive 3D 

graphics. 

 

:param actors: list of VTKActors 

:param name: labels the tab 

 

Initialize the interactive rendering by calling the frames' 

:py:meth`initialize` method after having added all actors to the frames 

renderer. 

 

Requires installation of vtk including python wrapper. 

''' 

if name is None: 

self._iplot += 1 

name = 'VTK %i (%s)' % (self._iplot, self.get_name()) 

 

try: 

f = VTKFrame(actors=actors) 

except ImportError as e: 

self.fail(e) 

 

self._panel_parent.add_tab(name, f) 

return f 

 

def tempdir(self): 

''' 

Create a temporary directory and return its absolute path. 

 

The directory and all its contents are removed when the Snuffling 

instance is deleted. 

''' 

 

if self._tempdir is None: 

self._tempdir = tempfile.mkdtemp('', 'snuffling-tmp-') 

 

return self._tempdir 

 

def set_live_update(self, live_update): 

''' 

Enable/disable live updating. 

 

When live updates are enabled, the :py:meth:`call` method is called 

whenever the user changes a parameter. If it is disabled, the user has 

to initiate such a call manually by triggering the snuffling's menu 

item or pressing the call button. 

''' 

 

self._live_update = live_update 

if self._have_pre_process_hook: 

self._pre_process_hook_enabled = live_update 

if self._have_post_process_hook: 

self._post_process_hook_enabled = live_update 

 

try: 

self.get_viewer().clean_update() 

except NoViewerSet: 

pass 

 

def add_parameter(self, param): 

''' 

Add an adjustable parameter to the snuffling. 

 

:param param: object of type :py:class:`Param`, :py:class:`Switch`, or 

:py:class:`Choice`. 

 

For each parameter added, controls are added to the snuffling's panel, 

so that the parameter can be adjusted from the gui. 

''' 

 

self._parameters.append(param) 

self._set_parameter_value(param.ident, param.default) 

 

if self._panel is not None: 

self.delete_gui() 

self.setup_gui() 

 

def add_trigger(self, name, method): 

''' 

Add a button to the snuffling's panel. 

 

:param name: string that labels the button 

:param method: method associated with the button 

''' 

 

self._triggers.append((name, method)) 

 

if self._panel is not None: 

self.delete_gui() 

self.setup_gui() 

 

def get_parameters(self): 

''' 

Get the snuffling's adjustable parameter definitions. 

 

Returns a list of objects of type :py:class:`Param`. 

''' 

 

return self._parameters 

 

def get_parameter(self, ident): 

''' 

Get one of the snuffling's adjustable parameter definitions. 

 

:param ident: identifier of the parameter 

 

Returns an object of type :py:class:`Param` or ``None``. 

''' 

 

for param in self._parameters: 

if param.ident == ident: 

return param 

return None 

 

def set_parameter(self, ident, value): 

''' 

Set one of the snuffling's adjustable parameters. 

 

:param ident: identifier of the parameter 

:param value: new value of the parameter 

 

Adjusts the control of a parameter without calling :py:meth:`call`. 

''' 

 

self._set_parameter_value(ident, value) 

 

control = self._param_controls.get(ident, None) 

if control: 

control.set_value(value) 

 

def set_parameter_range(self, ident, vmin, vmax): 

''' 

Set the range of one of the snuffling's adjustable parameters. 

 

:param ident: identifier of the parameter 

:param vmin,vmax: new minimum and maximum value for the parameter 

 

Adjusts the control of a parameter without calling :py:meth:`call`. 

''' 

 

control = self._param_controls.get(ident, None) 

if control: 

control.set_range(vmin, vmax) 

 

def set_parameter_choices(self, ident, choices): 

''' 

Update the choices of a Choice parameter. 

 

:param ident: identifier of the parameter 

:param choices: list of strings 

''' 

 

control = self._param_controls.get(ident, None) 

if control: 

selected_choice = control.set_choices(choices) 

self._set_parameter_value(ident, selected_choice) 

 

def _set_parameter_value(self, ident, value): 

setattr(self, ident, value) 

 

def get_parameter_value(self, ident): 

''' 

Get the current value of a parameter. 

 

:param ident: identifier of the parameter 

''' 

return getattr(self, ident) 

 

def get_settings(self): 

''' 

Returns a dictionary with identifiers of all parameters as keys and 

their values as the dictionaries values. 

''' 

 

params = self.get_parameters() 

settings = {} 

for param in params: 

settings[param.ident] = self.get_parameter_value(param.ident) 

 

return settings 

 

def set_settings(self, settings): 

params = self.get_parameters() 

dparams = dict([(param.ident, param) for param in params]) 

for k, v in settings.items(): 

if k in dparams: 

self._set_parameter_value(k, v) 

if k in self._param_controls: 

control = self._param_controls[k] 

control.set_value(v) 

 

def get_viewer(self): 

''' 

Get the parent viewer. 

 

Returns a reference to an object of type :py:class:`PileOverview`, 

which is the main viewer widget. 

 

If no gui has been initialized for the snuffling, a 

:py:exc:`NoViewerSet` exception is raised. 

''' 

 

if self._viewer is None: 

raise NoViewerSet() 

return self._viewer 

 

def get_pile(self): 

''' 

Get the pile. 

 

If a gui has been initialized, a reference to the viewer's internal 

pile is returned. If not, the :py:meth:`make_pile` method (which may be 

overloaded in subclass) is called to create a pile. This can be 

utilized to make hybrid snufflings, which may work also in a standalone 

mode. 

''' 

 

try: 

p = self.get_viewer().get_pile() 

except NoViewerSet: 

if self._no_viewer_pile is None: 

self._no_viewer_pile = self.make_pile() 

 

p = self._no_viewer_pile 

 

return p 

 

def get_active_event_and_stations( 

self, trange=(-3600., 3600.), missing='warn'): 

 

''' 

Get event and stations with available data for active event. 

 

:param trange: (begin, end), time range around event origin time to 

query for available data 

:param missing: string, what to do in case of missing station 

information: ``'warn'``, ``'raise'`` or ``'ignore'``. 

 

:returns: ``(event, stations)`` 

''' 

 

p = self.get_pile() 

v = self.get_viewer() 

 

event = v.get_active_event() 

if event is None: 

self.fail( 

'No active event set. Select an event and press "e" to make ' 

'it the "active event"') 

 

stations = {} 

for traces in p.chopper( 

event.time+trange[0], 

event.time+trange[1], 

load_data=False, 

degap=False): 

 

for tr in traces: 

try: 

for skey in v.station_keys(tr): 

if skey in stations: 

continue 

 

station = v.get_station(skey) 

stations[skey] = station 

 

except KeyError: 

s = 'No station information for station key "%s".' \ 

% '.'.join(skey) 

 

if missing == 'warn': 

logger.warning(s) 

elif missing == 'raise': 

raise MissingStationInformation(s) 

elif missing == 'ignore': 

pass 

else: 

assert False, 'invalid argument to "missing"' 

 

stations[skey] = None 

 

return event, [st for st in stations.values() if st is not None] 

 

def get_stations(self): 

''' 

Get all stations known to the viewer. 

''' 

 

v = self.get_viewer() 

stations = list(v.stations.values()) 

return stations 

 

def get_markers(self): 

''' 

Get all markers from the viewer. 

''' 

 

return self.get_viewer().get_markers() 

 

def get_event_markers(self): 

''' 

Get all event markers from the viewer. 

''' 

 

return [m for m in self.get_viewer().get_markers() 

if isinstance(m, EventMarker)] 

 

def get_selected_markers(self): 

''' 

Get all selected markers from the viewer. 

''' 

 

return self.get_viewer().selected_markers() 

 

def get_selected_event_markers(self): 

''' 

Get all selected event markers from the viewer. 

''' 

 

return [m for m in self.get_viewer().selected_markers() 

if isinstance(m, EventMarker)] 

 

def get_active_event_and_phase_markers(self): 

''' 

Get the marker of the active event and any associated phase markers 

''' 

 

viewer = self.get_viewer() 

markers = viewer.get_markers() 

event_marker = viewer.get_active_event_marker() 

if event_marker is None: 

self.fail( 

'No active event set. ' 

'Select an event and press "e" to make it the "active event"') 

 

event = event_marker.get_event() 

 

selection = [] 

for m in markers: 

if isinstance(m, PhaseMarker): 

if m.get_event() is event: 

selection.append(m) 

 

return ( 

event_marker, 

[m for m in markers if isinstance(m, PhaseMarker) and 

m.get_event() == event]) 

 

def get_viewer_trace_selector(self, mode='inview'): 

''' 

Get currently active trace selector from viewer. 

 

:param mode: set to ``'inview'`` (default) to only include selections 

currently shown in the viewer, ``'visible' to include all traces 

not currenly hidden by hide or quick-select commands, or ``'all'`` 

to disable any restrictions. 

''' 

 

viewer = self.get_viewer() 

 

def rtrue(tr): 

return True 

 

if mode == 'inview': 

return viewer.trace_selector or rtrue 

elif mode == 'visible': 

return viewer.trace_filter or rtrue 

elif mode == 'all': 

return rtrue 

else: 

raise Exception('invalid mode argument') 

 

def chopper_selected_traces(self, fallback=False, marker_selector=None, 

mode='inview', main_bandpass='False', 

*args, **kwargs): 

''' 

Iterate over selected traces. 

 

Shortcut to get all trace data contained in the selected markers in the 

running snuffler. For each selected marker, 

:py:meth:`pyrocko.pile.Pile.chopper` is called with the arguments 

*tmin*, *tmax*, and *trace_selector* set to values according to the 

marker. Additional arguments to the chopper are handed over from 

*\\*args* and *\\*\\*kwargs*. 

 

:param fallback: if ``True``, if no selection has been marked, use the 

content currently visible in the viewer. 

:param marker_selector: if not ``None`` a callback to filter markers. 

:param mode: set to ``'inview'`` (default) to only include selections 

currently shown in the viewer (excluding traces accessible 

through vertical scrolling), ``'visible'`` to include all 

traces not currenly hidden by hide or quick-select commands 

(including traces accessible through vertical scrolling), or 

``'all'`` to disable any restrictions. 

:param main_bandpass: if ``True``, apply main control high- and lowpass 

filters to traces. 

''' 

 

try: 

viewer = self.get_viewer() 

markers = [ 

m for m in viewer.selected_markers() 

if not isinstance(m, EventMarker)] 

 

if marker_selector is not None: 

markers = [ 

marker for marker in markers if marker_selector(marker)] 

 

pile = self.get_pile() 

 

def rtrue(tr): 

return True 

 

trace_selector_arg = kwargs.pop('trace_selector', rtrue) 

trace_selector_viewer = self.get_viewer_trace_selector(mode) 

 

if main_bandpass: 

def apply_filters(traces): 

for tr in traces: 

if viewer.highpass is not None: 

tr.highpass(4, viewer.highpass) 

if viewer.lowpass is not None: 

tr.lowpass(4, viewer.lowpass) 

return traces 

else: 

def apply_filters(traces): 

return traces 

 

if markers: 

for marker in markers: 

if not marker.nslc_ids: 

trace_selector_marker = rtrue 

else: 

def trace_selector_marker(tr): 

return marker.match_nslc(tr.nslc_id) 

 

def trace_selector(tr): 

return trace_selector_arg(tr) \ 

and trace_selector_viewer(tr) \ 

and trace_selector_marker(tr) 

 

for traces in pile.chopper( 

tmin=marker.tmin, 

tmax=marker.tmax, 

trace_selector=trace_selector, 

*args, 

**kwargs): 

 

yield apply_filters(traces) 

 

elif fallback: 

def trace_selector(tr): 

return trace_selector_arg(tr) \ 

and trace_selector_viewer(tr) 

 

tmin, tmax = viewer.get_time_range() 

for traces in pile.chopper( 

tmin=tmin, 

tmax=tmax, 

trace_selector=trace_selector, 

*args, 

**kwargs): 

 

yield apply_filters(traces) 

else: 

raise NoTracesSelected() 

 

except NoViewerSet: 

pile = self.get_pile() 

for traces in pile.chopper(*args, **kwargs): 

yield traces 

 

def get_selected_time_range(self, fallback=False): 

''' 

Get the time range spanning all selected markers. 

 

:param fallback: if ``True`` and no marker is selected return begin and 

end of visible time range 

''' 

 

viewer = self.get_viewer() 

markers = viewer.selected_markers() 

mins = [marker.tmin for marker in markers] 

maxs = [marker.tmax for marker in markers] 

 

if mins and maxs: 

tmin = min(mins) 

tmax = max(maxs) 

 

elif fallback: 

tmin, tmax = viewer.get_time_range() 

 

else: 

raise NoTracesSelected() 

 

return tmin, tmax 

 

def panel_visibility_changed(self, bool): 

''' 

Called when the snuffling's panel becomes visible or is hidden. 

 

Can be overloaded in subclass, e.g. to perform additional setup actions 

when the panel is activated the first time. 

''' 

 

pass 

 

def make_pile(self): 

''' 

Create a pile. 

 

To be overloaded in subclass. The default implementation just calls 

:py:func:`pyrocko.pile.make_pile` to create a pile from command line 

arguments. 

''' 

 

cachedirname = config.config().cache_dir 

sources = self._cli_params.get('sources', sys.argv[1:]) 

return pile.make_pile( 

sources, 

cachedirname=cachedirname, 

regex=self._cli_params['regex'], 

fileformat=self._cli_params['format']) 

 

def make_panel(self, parent): 

''' 

Create a widget for the snuffling's control panel. 

 

Normally called from the :py:meth:`setup_gui` method. Returns ``None`` 

if no panel is needed (e.g. if the snuffling has no adjustable 

parameters). 

''' 

 

params = self.get_parameters() 

self._param_controls = {} 

if params or self._force_panel: 

sarea = MyScrollArea(parent.get_panel_parent_widget()) 

sarea.setFrameStyle(qw.QFrame.NoFrame) 

sarea.setSizePolicy(qw.QSizePolicy( 

qw.QSizePolicy.Expanding, qw.QSizePolicy.Expanding)) 

frame = MyFrame(sarea) 

frame.widgetVisibilityChanged.connect( 

self.panel_visibility_changed) 

 

frame.setSizePolicy(qw.QSizePolicy( 

qw.QSizePolicy.Expanding, qw.QSizePolicy.Minimum)) 

frame.setFrameStyle(qw.QFrame.NoFrame) 

sarea.setWidget(frame) 

sarea.setWidgetResizable(True) 

layout = qw.QGridLayout() 

layout.setContentsMargins(0, 0, 0, 0) 

layout.setSpacing(0) 

frame.setLayout(layout) 

 

parlayout = qw.QGridLayout() 

 

irow = 0 

ipar = 0 

have_switches = False 

have_params = False 

for iparam, param in enumerate(params): 

if isinstance(param, Param): 

if param.minimum <= 0.0: 

param_control = LinValControl( 

high_is_none=param.high_is_none, 

low_is_none=param.low_is_none) 

else: 

param_control = ValControl( 

high_is_none=param.high_is_none, 

low_is_none=param.low_is_none, 

low_is_zero=param.low_is_zero) 

 

param_control.setup( 

param.name, 

param.minimum, 

param.maximum, 

param.default, 

iparam) 

 

param_control.valchange.connect( 

self.modified_snuffling_panel) 

 

self._param_controls[param.ident] = param_control 

for iw, w in enumerate(param_control.widgets()): 

parlayout.addWidget(w, ipar, iw) 

 

ipar += 1 

have_params = True 

 

elif isinstance(param, Choice): 

param_widget = ChoiceControl( 

param.ident, param.default, param.choices, param.name) 

param_widget.choosen.connect( 

self.choose_on_snuffling_panel) 

 

self._param_controls[param.ident] = param_widget 

parlayout.addWidget(param_widget, ipar, 0, 1, 3) 

ipar += 1 

have_params = True 

 

elif isinstance(param, Switch): 

have_switches = True 

 

if have_params: 

parframe = qw.QFrame(sarea) 

parframe.setSizePolicy(qw.QSizePolicy( 

qw.QSizePolicy.Expanding, qw.QSizePolicy.Minimum)) 

parframe.setLayout(parlayout) 

layout.addWidget(parframe, irow, 0) 

irow += 1 

 

if have_switches: 

swlayout = qw.QGridLayout() 

isw = 0 

for iparam, param in enumerate(params): 

if isinstance(param, Switch): 

param_widget = SwitchControl( 

param.ident, param.default, param.name) 

param_widget.sw_toggled.connect( 

self.switch_on_snuffling_panel) 

 

self._param_controls[param.ident] = param_widget 

swlayout.addWidget(param_widget, isw/10, isw % 10) 

isw += 1 

 

swframe = qw.QFrame(sarea) 

swframe.setSizePolicy(qw.QSizePolicy( 

qw.QSizePolicy.Expanding, qw.QSizePolicy.Minimum)) 

swframe.setLayout(swlayout) 

layout.addWidget(swframe, irow, 0) 

irow += 1 

 

butframe = qw.QFrame(sarea) 

butframe.setSizePolicy(qw.QSizePolicy( 

qw.QSizePolicy.Expanding, qw.QSizePolicy.Minimum)) 

butlayout = qw.QHBoxLayout() 

butframe.setLayout(butlayout) 

 

live_update_checkbox = qw.QCheckBox('Auto-Run') 

if self._live_update: 

live_update_checkbox.setCheckState(qc.Qt.Checked) 

 

butlayout.addWidget(live_update_checkbox) 

live_update_checkbox.toggled.connect( 

self.live_update_toggled) 

 

help_button = qw.QPushButton('Help') 

butlayout.addWidget(help_button) 

help_button.clicked.connect( 

self.help_button_triggered) 

 

clear_button = qw.QPushButton('Clear') 

butlayout.addWidget(clear_button) 

clear_button.clicked.connect( 

self.clear_button_triggered) 

 

call_button = qw.QPushButton('Run') 

butlayout.addWidget(call_button) 

call_button.clicked.connect( 

self.call_button_triggered) 

 

for name, method in self._triggers: 

but = qw.QPushButton(name) 

 

def call_and_update(method): 

def f(): 

try: 

method() 

except SnufflingError as e: 

if not isinstance(e, SnufflingCallFailed): 

# those have logged within error() 

logger.error('%s: %s' % (self._name, e)) 

logger.error( 

'%s: Snuffling action failed' % self._name) 

 

self.get_viewer().update() 

return f 

 

but.clicked.connect( 

call_and_update(method)) 

 

butlayout.addWidget(but) 

 

layout.addWidget(butframe, irow, 0) 

 

irow += 1 

spacer = qw.QSpacerItem( 

0, 0, qw.QSizePolicy.Expanding, qw.QSizePolicy.Expanding) 

 

layout.addItem(spacer, irow, 0) 

 

return sarea 

 

else: 

return None 

 

def make_helpmenuitem(self, parent): 

''' 

Create the help menu item for the snuffling. 

''' 

 

item = qw.QAction(self.get_name(), None) 

 

item.triggered.connect( 

self.help_button_triggered) 

 

return item 

 

def make_menuitem(self, parent): 

''' 

Create the menu item for the snuffling. 

 

This method may be overloaded in subclass and return ``None``, if no 

menu entry is wanted. 

''' 

 

item = qw.QAction(self.get_name(), None) 

item.setCheckable( 

self._have_pre_process_hook or self._have_post_process_hook) 

 

item.triggered.connect( 

self.menuitem_triggered) 

 

return item 

 

def output_filename( 

self, 

caption='Save File', 

dir='', 

filter='', 

selected_filter=None): 

 

''' 

Query user for an output filename. 

 

This is currently a wrapper to :py:func:`QFileDialog.getSaveFileName`. 

A :py:exc:`UserCancelled` exception is raised if the user cancels the 

dialog. 

''' 

 

if not dir and self._previous_output_filename: 

dir = self._previous_output_filename 

 

fn = getSaveFileName( 

self.get_viewer(), caption, dir, filter, selected_filter) 

if not fn: 

raise UserCancelled() 

 

self._previous_output_filename = fn 

return str(fn) 

 

def input_directory(self, caption='Open Directory', dir=''): 

''' 

Query user for an input directory. 

 

This is a wrapper to :py:func:`QFileDialog.getExistingDirectory`. 

A :py:exc:`UserCancelled` exception is raised if the user cancels the 

dialog. 

''' 

 

if not dir and self._previous_input_directory: 

dir = self._previous_input_directory 

 

dn = qw.QFileDialog.getExistingDirectory( 

None, caption, dir, qw.QFileDialog.ShowDirsOnly) 

 

if not dn: 

raise UserCancelled() 

 

self._previous_input_directory = dn 

return str(dn) 

 

def input_filename(self, caption='Open File', dir='', filter='', 

selected_filter=None): 

''' 

Query user for an input filename. 

 

This is currently a wrapper to :py:func:`QFileDialog.getOpenFileName`. 

A :py:exc:`UserCancelled` exception is raised if the user cancels the 

dialog. 

''' 

 

if not dir and self._previous_input_filename: 

dir = self._previous_input_filename 

 

fn, _ = fnpatch(qw.QFileDialog.getOpenFileName( 

self.get_viewer(), 

caption, 

dir, 

filter)) # selected_filter) 

 

if not fn: 

raise UserCancelled() 

 

self._previous_input_filename = fn 

return str(fn) 

 

def input_dialog(self, caption='', request='', directory=False): 

''' 

Query user for a text input. 

 

This is currently a wrapper to :py:func:`QInputDialog.getText`. 

A :py:exc:`UserCancelled` exception is raised if the user cancels the 

dialog. 

''' 

 

inp, ok = qw.QInputDialog.getText(self.get_viewer(), 'Input', caption) 

 

if not ok: 

raise UserCancelled() 

 

return inp 

 

def modified_snuffling_panel(self, value, iparam): 

''' 

Called when the user has played with an adjustable parameter. 

 

The default implementation sets the parameter, calls the snuffling's 

:py:meth:`call` method and finally triggers an update on the viewer 

widget. 

''' 

 

param = self.get_parameters()[iparam] 

self._set_parameter_value(param.ident, value) 

if self._live_update: 

self.check_call() 

self.get_viewer().update() 

 

def switch_on_snuffling_panel(self, ident, state): 

''' 

Called when the user has toggled a switchable parameter. 

''' 

 

self._set_parameter_value(ident, state) 

if self._live_update: 

self.check_call() 

self.get_viewer().update() 

 

def choose_on_snuffling_panel(self, ident, state): 

''' 

Called when the user has made a choice about a choosable parameter. 

''' 

 

self._set_parameter_value(ident, state) 

if self._live_update: 

self.check_call() 

self.get_viewer().update() 

 

def menuitem_triggered(self, arg): 

''' 

Called when the user has triggered the snuffling's menu. 

 

The default implementation calls the snuffling's :py:meth:`call` method 

and triggers an update on the viewer widget. 

''' 

 

self.check_call() 

 

if self._have_pre_process_hook: 

self._pre_process_hook_enabled = arg 

 

if self._have_post_process_hook: 

self._post_process_hook_enabled = arg 

 

if self._have_pre_process_hook or self._have_post_process_hook: 

self.get_viewer().clean_update() 

else: 

self.get_viewer().update() 

 

def call_button_triggered(self): 

''' 

Called when the user has clicked the snuffling's call button. 

 

The default implementation calls the snuffling's :py:meth:`call` method 

and triggers an update on the viewer widget. 

''' 

 

self.check_call() 

self.get_viewer().update() 

 

def clear_button_triggered(self): 

''' 

Called when the user has clicked the snuffling's clear button. 

 

This calls the :py:meth:`cleanup` method and triggers an update on the 

viewer widget. 

''' 

 

self.cleanup() 

self.get_viewer().update() 

 

def help_button_triggered(self): 

''' 

Creates a :py:class:`QLabel` which contains the documentation as 

given in the snufflings' __doc__ string. 

''' 

 

if self.__doc__: 

if self.__doc__.strip().startswith('<html>'): 

doc = qw.QLabel(self.__doc__) 

else: 

try: 

import markdown 

doc = qw.QLabel(markdown.markdown(self.__doc__)) 

 

except ImportError: 

logger.error( 

'Install Python module "markdown" for pretty help ' 

'formatting.') 

 

doc = qw.QLabel(self.__doc__) 

else: 

doc = qw.QLabel('This snuffling does not provide any online help.') 

 

labels = [doc] 

 

if self._filename: 

from html import escape 

 

code = open(self._filename, 'r').read() 

 

doc_src = qw.QLabel( 

'''<html><body> 

<hr /> 

<center><em>May the source be with you, young Skywalker!</em><br /><br /> 

<a href="file://%s"><code>%s</code></a></center> 

<br /> 

<p style="margin-left: 2em; margin-right: 2em; background-color:#eed;"> 

<pre style="white-space: pre-wrap"><code>%s 

</code></pre></p></body></html>''' 

% ( 

quote(self._filename), 

escape(self._filename), 

escape(code))) 

 

labels.append(doc_src) 

 

for h in labels: 

h.setAlignment(qc.Qt.AlignTop | qc.Qt.AlignLeft) 

h.setWordWrap(True) 

 

self._viewer.show_doc('Help: %s' % self._name, labels, target='panel') 

 

def live_update_toggled(self, on): 

''' 

Called when the checkbox for live-updates has been toggled. 

''' 

 

self.set_live_update(on) 

 

def add_traces(self, traces): 

''' 

Add traces to the viewer. 

 

:param traces: list of objects of type :py:class:`pyrocko.trace.Trace` 

 

The traces are put into a :py:class:`pyrocko.pile.MemTracesFile` and 

added to the viewer's internal pile for display. Note, that unlike with 

the traces from the files given on the command line, these traces are 

kept in memory and so may quickly occupy a lot of ram if a lot of 

traces are added. 

 

This method should be preferred over modifying the viewer's internal 

pile directly, because this way, the snuffling has a chance to 

automatically remove its private traces again (see :py:meth:`cleanup` 

method). 

''' 

 

ticket = self.get_viewer().add_traces(traces) 

self._tickets.append(ticket) 

return ticket 

 

def add_trace(self, tr): 

''' 

Add a trace to the viewer. 

 

See :py:meth:`add_traces`. 

''' 

 

self.add_traces([tr]) 

 

def add_markers(self, markers): 

''' 

Add some markers to the display. 

 

Takes a list of objects of type :py:class:`pyrocko.gui.util.Marker` and 

adds these to the viewer. 

''' 

 

self.get_viewer().add_markers(markers) 

self._markers.extend(markers) 

 

def add_marker(self, marker): 

''' 

Add a marker to the display. 

 

See :py:meth:`add_markers`. 

''' 

 

self.add_markers([marker]) 

 

def cleanup(self): 

''' 

Remove all traces and markers which have been added so far by the 

snuffling. 

''' 

 

try: 

viewer = self.get_viewer() 

viewer.release_data(self._tickets) 

viewer.remove_markers(self._markers) 

 

except NoViewerSet: 

pass 

 

self._tickets = [] 

self._markers = [] 

 

def check_call(self): 

try: 

self.call() 

return 0 

 

except SnufflingError as e: 

if not isinstance(e, SnufflingCallFailed): 

# those have logged within error() 

logger.error('%s: %s' % (self._name, e)) 

logger.error('%s: Snuffling action failed' % self._name) 

return 1 

 

except Exception: 

logger.exception( 

'%s: Snuffling action raised an exception' % self._name) 

 

def call(self): 

''' 

Main work routine of the snuffling. 

 

This method is called when the snuffling's menu item has been triggered 

or when the user has played with the panel controls. To be overloaded 

in subclass. The default implementation does nothing useful. 

''' 

 

pass 

 

def pre_process_hook(self, traces): 

return traces 

 

def post_process_hook(self, traces): 

return traces 

 

def get_tpad(self): 

''' 

Return current amount of extra padding needed by live processing hooks. 

''' 

 

return 0.0 

 

def pre_destroy(self): 

''' 

Called when the snuffling instance is about to be deleted. 

 

Can be overloaded to do user-defined cleanup actions. The 

default implementation calls :py:meth:`cleanup` and deletes 

the snuffling`s tempory directory, if needed. 

''' 

 

self.cleanup() 

if self._tempdir is not None: 

import shutil 

shutil.rmtree(self._tempdir) 

 

 

class SnufflingError(Exception): 

pass 

 

 

class NoViewerSet(SnufflingError): 

''' 

This exception is raised, when no viewer has been set on a Snuffling. 

''' 

 

def __str__(self): 

return 'No GUI available. ' \ 

'Maybe this Snuffling cannot be run in command line mode?' 

 

 

class MissingStationInformation(SnufflingError): 

''' 

Raised when station information is missing. 

''' 

 

 

class NoTracesSelected(SnufflingError): 

''' 

This exception is raised, when no traces have been selected in the viewer 

and we cannot fallback to using the current view. 

''' 

 

def __str__(self): 

return 'No traces have been selected / are available.' 

 

 

class UserCancelled(SnufflingError): 

''' 

This exception is raised, when the user has cancelled a snuffling dialog. 

''' 

 

def __str__(self): 

return 'The user has cancelled a dialog.' 

 

 

class SnufflingCallFailed(SnufflingError): 

''' 

This exception is raised, when :py:meth:`Snuffling.fail` is called from 

:py:meth:`Snuffling.call`. 

''' 

 

 

class InvalidSnufflingFilename(Exception): 

pass 

 

 

class SnufflingModule(object): 

''' 

Utility class to load/reload snufflings from a file. 

 

The snufflings are created by user modules which have the special function 

:py:func:`__snufflings__` which return the snuffling instances to be 

exported. The snuffling module is attached to a handler class, which makes 

use of the snufflings (e.g. :py:class:`pyrocko.pile_viewer.PileOverwiew` 

from ``pile_viewer.py``). The handler class must implement the methods 

``add_snuffling()`` and ``remove_snuffling()`` which are used as callbacks. 

The callbacks are utilized from the methods :py:meth:`load_if_needed` and 

:py:meth:`remove_snufflings` which may be called from the handler class, 

when needed. 

''' 

 

mtimes = {} 

 

def __init__(self, path, name, handler): 

self._path = path 

self._name = name 

self._mtime = None 

self._module = None 

self._snufflings = [] 

self._handler = handler 

 

def load_if_needed(self): 

filename = os.path.join(self._path, self._name+'.py') 

 

try: 

mtime = os.stat(filename)[8] 

except OSError as e: 

if e.errno == 2: 

logger.error(e) 

raise BrokenSnufflingModule(filename) 

 

if self._module is None: 

sys.path[0:0] = [self._path] 

try: 

logger.debug('Loading snuffling module %s' % filename) 

if self._name in sys.modules: 

raise InvalidSnufflingFilename(self._name) 

 

self._module = __import__(self._name) 

del sys.modules[self._name] 

 

for snuffling in self._module.__snufflings__(): 

snuffling._filename = filename 

self.add_snuffling(snuffling) 

 

except Exception: 

logger.error(traceback.format_exc()) 

raise BrokenSnufflingModule(filename) 

 

finally: 

sys.path[0:1] = [] 

 

elif self._mtime != mtime: 

logger.warning('Reloading snuffling module %s' % filename) 

settings = self.remove_snufflings() 

sys.path[0:0] = [self._path] 

try: 

 

sys.modules[self._name] = self._module 

 

reload(self._module) 

del sys.modules[self._name] 

 

for snuffling in self._module.__snufflings__(): 

snuffling._filename = filename 

self.add_snuffling(snuffling, reloaded=True) 

 

if len(self._snufflings) == len(settings): 

for sett, snuf in zip(settings, self._snufflings): 

snuf.set_settings(sett) 

 

except Exception: 

logger.error(traceback.format_exc()) 

raise BrokenSnufflingModule(filename) 

 

finally: 

sys.path[0:1] = [] 

 

self._mtime = mtime 

 

def add_snuffling(self, snuffling, reloaded=False): 

snuffling._path = self._path 

snuffling.setup() 

self._snufflings.append(snuffling) 

self._handler.add_snuffling(snuffling, reloaded=reloaded) 

 

def remove_snufflings(self): 

settings = [] 

for snuffling in self._snufflings: 

settings.append(snuffling.get_settings()) 

self._handler.remove_snuffling(snuffling) 

 

self._snufflings = [] 

return settings 

 

 

class BrokenSnufflingModule(Exception): 

pass 

 

 

class MyScrollArea(qw.QScrollArea): 

 

def sizeHint(self): 

s = qc.QSize() 

s.setWidth(self.widget().sizeHint().width()) 

s.setHeight(self.widget().sizeHint().height()) 

return s 

 

 

class SwitchControl(qw.QCheckBox): 

sw_toggled = qc.pyqtSignal(object, bool) 

 

def __init__(self, ident, default, *args): 

qw.QCheckBox.__init__(self, *args) 

self.ident = ident 

self.setChecked(default) 

self.toggled.connect(self._sw_toggled) 

 

def _sw_toggled(self, state): 

self.sw_toggled.emit(self.ident, state) 

 

def set_value(self, state): 

self.blockSignals(True) 

self.setChecked(state) 

self.blockSignals(False) 

 

 

class ChoiceControl(qw.QFrame): 

choosen = qc.pyqtSignal(object, object) 

 

def __init__(self, ident, default, choices, name, *args): 

qw.QFrame.__init__(self, *args) 

self.label = qw.QLabel(name, self) 

self.label.setMinimumWidth(120) 

self.cbox = qw.QComboBox(self) 

self.layout = qw.QHBoxLayout(self) 

self.layout.addWidget(self.label) 

self.layout.addWidget(self.cbox) 

self.layout.setContentsMargins(0, 0, 0, 0) 

self.layout.setSpacing(0) 

self.ident = ident 

self.choices = choices 

for ichoice, choice in enumerate(choices): 

self.cbox.addItem(choice) 

 

self.set_value(default) 

self.cbox.activated.connect(self.emit_choosen) 

 

def set_choices(self, choices): 

icur = self.cbox.currentIndex() 

if icur != -1: 

selected_choice = choices[icur] 

else: 

selected_choice = None 

 

self.choices = choices 

self.cbox.clear() 

for ichoice, choice in enumerate(choices): 

self.cbox.addItem(qc.QString(choice)) 

 

if selected_choice is not None and selected_choice in choices: 

self.set_value(selected_choice) 

return selected_choice 

else: 

self.set_value(choices[0]) 

return choices[0] 

 

def emit_choosen(self, i): 

self.choosen.emit( 

self.ident, 

self.choices[i]) 

 

def set_value(self, v): 

self.cbox.blockSignals(True) 

for i, choice in enumerate(self.choices): 

if choice == v: 

self.cbox.setCurrentIndex(i) 

self.cbox.blockSignals(False)