Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

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

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

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

""" 

Phylogeny-based detection of borrowings in lexicostatistical wordlists. 

""" 

from __future__ import print_function, division, unicode_literals 

import os 

import itertools 

from collections import defaultdict 

 

from six import text_type 

import numpy as np 

from clldutils import jsonlib 

 

from lingpy.compare._phylogeny.utils import get_acs 

from lingpy.compare._phylogeny._settings import rcParams 

from lingpy.align.multiple import Multiple 

from lingpy.convert.plot import plot_tree 

from lingpy import compat 

from lingpy import util 

from lingpy import log 

 

import networkx as nx 

 

# mpl is only used for specific plots, we can therefor make a safe import 

try: # pragma: no cover 

import matplotlib as mpl 

import matplotlib.pyplot as plt 

except: 

mpl, plt = None, None 

log.missing_module('matplotlib') 

 

# import the geoplot module 

try: # pragma: no cover 

import mpl_toolkits.basemap as bmp 

except ImportError: 

bmp = None 

log.missing_module('basemap') 

 

try: 

import scipy as sp 

except ImportError: 

sp = None 

log.missing_module('scipy') 

 

from lingpy.compare._phylogeny.polygon import getConvexHull 

from lingpy.thirdparty import cogent as cg 

from lingpy.convert.graph import gls2gml, radial_layout 

from lingpy.basic import Wordlist 

from lingpy.read.csv import csv2dict, csv2list 

 

 

def get_gls( 

paps, 

taxa, 

tree, 

gpl=1, 

weights=(1, 1), 

push_gains=True, 

missing_data=0): 

""" 

Calculate a gain-loss scenario. 

 

Parameters 

---------- 

paps : list 

A list containing the presence-absence patterns for all leaves of the 

reference tree. Presence is indicated by 1, and absence by 0. Missing 

characters are indicated by -1. 

taxa : list 

The list of taxa (leaves of the tree). 

tree : str 

A tree in Newick-format. Taxon names should (of course) be identical 

with the names in the list of taxa. 

gpl : int 

Gains per lineage. Specify the maximal amount of gains per lineage. One 

lineage is hereby defined as one path in the tree. If set to 0, only 

one gain per lineage is allowed, if set to 1, one additional gain is 

allowed, and so on. Use with care, since this will lead to larger 

computation costs (more possibilities have to be taken care of) and can 

also be quite unrealistic. 

weights : tuple (default=(1,1)) 

Specify the weights for gains and losses. Setting this parameter to 

(2,1) will penalize gain events with 2 and loss events with 1. 

push_gains : bool (default=True) 

Determine whether of a set of equally parsimonious patterns those 

should be retained that show gains closer to the leaves of the tree or 

not. 

missing_data : int (default=0) 

Determine how missing data should be represented. If set to 0 

(default), missing data will be treated in the same way as absence 

character states. If you want missing data to be accounted for in the 

algorithm, set this parameter to -1. 

 

Notes 

----- 

This is an enhanced version of the older approach to parsimony-based 

gain-loss mapping. The algorithm is much faster than the previous one and 

also written much clearer as to the code. In most tests I ran so far, it 

also outperformed other approaches by finding more parsimonious solutions. 

 

""" 

# this line is just to make sure we actually copy the paps and don't change 

# them unwillingly 

pap = [p for p in paps] 

 

for i, taxon in enumerate(taxa): 

if pap[i] == -1: 

pap[i] = missing_data 

 

# get dictionary for taxa with their states 

statesD = dict(zip(taxa, pap)) 

 

states1 = [s for s in statesD if statesD[s] == 1] 

 

# get subtree for taxa with positive paps 

tree = tree.lowestCommonAncestor([t for t in taxa if statesD[t] == 1]) 

 

tips = tree.getTipNames() 

root = tree.Name 

nodes = tree.getNodeNames() 

distances = defaultdict(list) 

for node in [n for n in nodes if n != root]: 

distances[len(tree.getConnectingEdges(root, node))].append(node) 

distances[0] = [root] 

 

# assign the scenarios, each scenario consists of the state of the node in 

# the tree and a dictionary with the previous events, where the node-name 

# is the key and the event (1,0,-1) is the value 

scenarios = {taxon: [(statesD[taxon], {})] for taxon in tips} 

 

# return simple scenario if the group is single origin 

if [statesD[tip] for tip in tips].count(1) == len(tips): 

return [(root, 1)] 

 

# start iteration over outmost layer 

for i in sorted(distances, reverse=True): 

log.debug("Calculating Layer {0}...".format(i)) 

 

for node in distances[i]: 

tree_node = tree.getNodeMatchingName(node) 

 

if not tree_node.isTip(): 

names = [n.Name for n in tree_node.Children] 

log.debug("... current node {0} ({1})".format(node, names)) 

 

# define new nodes list (to be appended to new node 

new_nodes = [] 

for combination in itertools.product( 

*[scenarios[n.Name] for n in tree_node.Children]): 

# get stories 

states = [node[0] for node in combination] 

stories = [node[1] for node in combination] 

 

# evaluate the states 

s1 = states.count(1) 

s0 = states.count(0) 

sM = states.count(-1) 

 

sL = len(states) 

 

new_stories = {} 

for story in stories: 

new_stories.update(story) 

 

if s1 + sM == sL: 

# combine states if they evaluate to 1 

new_nodes.append((1, new_stories)) 

log.debug("...... 1 nodes: %s" % (new_nodes[-1],)) 

elif s0 + sM == sL: 

# combine states if they evaluate to 0 

# append the new combined stuff to the dictionary 

new_nodes.append((0, new_stories)) 

log.debug("...... 0 nodes: %s" % (new_nodes[-1],)) 

elif sM == sL: 

# if the both evaluate to -1, also combine them 

new_nodes.append((-1, new_stories)) 

else: 

# append both scenarios if there's both 1 and 0 

# assuming origin, each node that has a 0, needs an extra origin 

new_storiesA = new_stories.copy() 

new_storiesB = new_stories.copy() 

 

for j, state in enumerate(states): 

if state == 1: 

new_storiesA[names[j]] = 1 

if state == 0: 

new_storiesB[names[j]] = 0 

 

new_nodes += [(1, new_storiesB)] 

new_nodes += [(0, new_storiesA)] 

 

log.debug("...... 01 nodes: %s" % (new_nodes[-2],)) 

log.debug("...... 01 nodes: %s" % (new_nodes[-1],)) 

 

# evaluate the scenarios for consistency reasons, 

good_nodes = [] 

minGains, minLoss = defaultdict(list), defaultdict(list) 

for j, (state, scenario) in enumerate(new_nodes): 

# avoid to append scenarios with more than allowed gains per lineage 

if not (state == 1 and list(scenario.values()).count(1) > gpl): 

# check scenarios having a loss in order to retrieve 

# the scenario with the minimal weight, since once a 

# loss is determined, the gains can be freely chosen 

gains = list(scenario.values()).count(1) 

losses = list(scenario.values()).count(0) 

w = gains * weights[0] + losses * weights[1] 

if state == 0: 

minGains[w].append(j) 

# do the same for scenarios having a gain, if multiple 

# loss-models are encountered 

elif state == 1: 

minLoss[w].append(j) 

 

# append lowest weights in gains to the list 

if minGains: 

good_nodes.extend([new_nodes[idx] for idx in minGains[min(minGains)]]) 

if minLoss: 

good_nodes.extend([new_nodes[idx] for idx in minLoss[min(minLoss)]]) 

 

scenarios[tree_node.Name] = good_nodes 

 

# select the best of all scenarios by comparing all weights 

winners = defaultdict(list) 

for s in scenarios[root]: 

if s[0] == 1: 

s[1][root] = s[0] 

 

# count the weights 

events = list(s[1].values()) 

winners[events.count(1) * weights[0] + events.count(0) * weights[1]].append( 

list(s[1].items())) 

 

# select the scenario with the hightest number of gains, if push-gains 

# option is set to true 

log.debug('%s' % ( 

[x for x in tree.getNodeMatchingName(root).getTipNames() if x not in states1],)) 

 

return sorted( 

winners[min(winners)], 

key=lambda x: [y[1] for y in x].count(1 if push_gains else 0))[0] 

 

 

class PhyBo(Wordlist): 

""" 

Basic class for calculations using the TreBor method. 

 

 

Parameters 

---------- 

dataset : string 

Name of the dataset that shall be analyzed. 

tree : {None, string} 

Name of the tree file. 

paps : string (default="pap") 

Name of the column that stores the specific cognate IDs consisting 

of an arbitrary integer key and a key for the concept. 

ref : string (default="cogid") 

Name of the column that stores the general cognate ids (the 

"reference" of the analysis). 

tree_calc : {'neighbor','upgma'} (default='neighbor') 

Select the algorithm to be used for the tree calculation if no tree is 

passed with the file. 

missing : int (default=-1) 

Specify how missing data should be handled. If set to -1, missing data 

can account for both presence or absence of a cognate set in the given 

language. If set to 0, missing data is treated as absence. 

degree : int (default=100) 

The degree which is chosen for the projection of the tree layout. 

""" 

 

# XXX generally: find a way to check whether a dataset was already loaded, 

# XXX otherwise it takes too long a time to recalculate everything 

 

def __init__( 

self, 

dataset, 

tree=None, 

paps='pap', 

ref='cogid', 

tree_calc='neighbor', 

output_dir=None, 

**keywords 

): 

# TODO check for keywords, allow to load trees, etc. 

util.setdefaults( 

keywords, 

degree=100, 

singletons=True, 

missing=-1, 

change=lambda x: x ** 1.5, 

start=0 

) 

 

# check for cognates 

if 'cognates' in keywords: 

log.deprecated('cognates', 'ref') 

ref = keywords['cognates'] 

 

# store the basename of the dataset without suffix and the identifier for paps 

self._dataset_dir = os.path.dirname(os.path.abspath(dataset)) 

self._output_dir = output_dir or self._dataset_dir 

dataset_name = os.path.basename(dataset) 

self.dataset = dataset_name[:-4] \ 

if dataset_name[-4:] in ['.qlc', '.csv'] else dataset_name 

self._pap_string = paps 

 

# open csv-file of the data and store it as a word list attribute 

if os.path.isfile(dataset): 

if dataset.endswith('.csv'): 

log.deprecated('csv', 'qlc') 

else: 

raise compat.FileNotFoundError("The input file could not be found.") 

Wordlist.__init__(self, dataset, row='concept', col='doculect') 

 

log.info("Loaded the wordlist file.") 

 

# check for glossid 

if 'glid' not in self.entries: 

self._gl2id = dict(zip(self.rows, [i + 1 for i in range(len(self.rows))])) 

self._id2gl = {b: a for a, b in self._gl2id.items()} 

self.add_entries('glid', 'concept', lambda x: self._gl2id[x]) 

else: 

self._id2gl = {int(self[k, 'glid']): self[k, 'concept'] for k in self} 

self._gl2id = {self[k, 'concept']: int(self[k, 'glid']) for k in self} 

 

# check for paps as attribute in the wordlist 

if paps not in self.entries: 

self.add_entries( 

paps, ref + ',glid', lambda x, y: "{0}:{1}".format(x[y[0]], x[y[1]])) 

log.info("Created entry PAP.") 

 

# get the paps and the etymological dictionary 

if not hasattr(self, 'paps'): 

self.paps = self.get_paps(ref=paps, missing=keywords['missing']) 

self.etd = self.get_etymdict(ref=paps) 

 

log.info("Created the PAP matrix.") 

 

# get a list of concepts corresponding to the cogs and get the 

# singletons to be excluded from the calculation 

if not hasattr(self, 'singletons'): 

tmp = self.get_etymdict(ref=paps, entry='concept') 

 

# a dictionary with pap-key as key and concept as value 

self.pap2con = {} 

 

# list stores the singletons 

self.singletons = [] 

 

# only calculate singletons if the option is chosen 

for key in self.paps: 

# get the names of the concepts 

concept_list = [k for k in tmp[key] if k != 0] 

concept = concept_list[0][0] 

self.pap2con[key] = concept 

 

# check for singletons 

if keywords['singletons']: 

if sum([1 for p in self.paps[key] if p >= 1]) == 1: 

self.singletons.append(key) 

 

# create a list of keys for faster access when iterating 

self.cogs = [k for k in self.pap2con if k not in self.singletons] 

log.info("Excluded singletons.") 

 

# summarize the cognate sets under their common concept 

 

# Load the tree, if it is not defined, assume that the treefile has the 

# same name as the dataset 

if not tree: 

if not hasattr(self, 'tree'): 

# try to load the tree first 

try: 

self.tree = cg.LoadTree(dataset + '.tre') 

except: 

# create it otherwise 

self.calculate('tree', ref=ref, tree_calc=tree_calc) 

log.info("Tree-file was not found, creating it now...") 

# XXX TODO 

# if it is explicitly defined, try to load that file 

else: # not hasattr(self,'tree'): 

self._meta['tree'] = cg.LoadTree(tree) 

log.info("Loaded the tree.") 

 

if isinstance(self.tree, text_type): 

self.tree = cg.LoadTree(treestring=self.tree) 

 

# if no good topology is given, create it automatically, using 

# the radial layout function 

gTpl = radial_layout( 

self.tree, 

filename='', 

degree=keywords['degree'], 

change=keywords['change'], 

start=keywords['start'] 

) 

log.info("Calculated radial layout for the tree. ") 

 

self.tgraph = gTpl 

 

# create a couple of further attributes 

for a in ['stats', 'gls', 'dists', 'graph', 'acs']: 

if not hasattr(self, a): 

setattr(self, a, {}) 

 

def _output_path(self, *comps, **kw): 

"""A path within the output directory for the dataset. 

 

Note: All intermediate directories will be created unless a keyword argument 

mkdir=False is passed. 

 

:param comps: path components relative to the output directory. 

:return: the path. 

""" 

return util._str_path( 

os.path.join( 

self._output_dir, os.path.basename(self.dataset) + '_phybo', *comps), 

mkdir=kw.get('mkdir', True)) 

 

def _write_file(self, name, content, log=True): 

"""Write a file to the dataset-specific output directory. 

 

:param name: Name of the file to be written relative to the output directory. 

:param content: Content to be written. 

:param log: Flag signalling whether there should be log output or not. 

""" 

util.write_text_file(self._output_path(name), content, log=log) 

 

def _config(self): 

if 'conf' in self._meta: 

return self._meta['conf'] 

try: 

return jsonlib.load(self.dataset + '.json') 

except: 

return {} 

 

def _existing_taxa_and_paps(self, pap, missing_data): 

# get the list of nodes that are not missing 

taxa, paps = [], [] 

for i, taxon in enumerate(self.taxa): 

if pap[i] == -1: 

pap[i] = missing_data 

taxa += [taxon] 

paps += [pap[i]] 

return taxa, paps 

 

def _get_GLS_top_down(self, pap, mode=1, missing_data=0): 

""" 

Infer gain-loss scenario using the method by Dagan & Martin (2007). 

 

""" 

# check for mode 

try: 

mode = int(mode) 

except (ValueError, TypeError): 

raise ValueError("[i] Mode should be an integer.") 

 

taxa, paps = self._existing_taxa_and_paps(pap, missing_data) 

 

# get list of taxa where pap is 1 

presents = [self.taxa[i] for i in range(len(self.taxa)) if pap[i] in (1, -1)] 

 

# get the subtree containing all taxa that have positive paps 

tree = self.tree.lowestCommonAncestor( 

[self.taxa[i] for i in range(len(self.taxa)) if pap[i] >= 1]) 

log.debug("Subtree is {0}.".format(text_type(tree))) 

 

# assign the basic (starting) values to the dictionary 

nodes = [t.Name for t in tree.tips()] 

log.debug("Nodes are {0}.".format(','.join(nodes))) 

 

if mode == 1: 

return [(tree.Name, 1)] 

 

# store the scenario 

scenario = [] 

 

# make the queue 

queue = [[tree, 1]] 

while queue: 

# get tree and counter from queue 

tmp_tree, counter = queue.pop(0) 

 

# break if counter exceeds the mode 

if counter >= mode: 

t = tmp_tree.lowestCommonAncestor( 

[p for p in presents if p in tmp_tree.getTipNames()]) 

scenario.append((t.Name, 1) if hasattr(t, 'Name') else (tmp_tree.Name, 0)) 

else: 

# store common names and children nodes 

commons = [] 

tmp_names = tmp_tree.getTipNames() 

 

# store results for separate children 

tmp_results = [] 

 

for child in tmp_tree.Children: 

subtree = child.lowestCommonAncestor( 

[p for p in presents if p in child.getTipNames()]) 

 

# check for tip names in subtrees 

if hasattr(subtree, "Children"): 

subnames = subtree.getTipNames() 

else: 

if child.Name in presents: 

subnames = [child.Name] 

else: 

subnames = [] 

 

commons.extend(subnames) 

tmp_results += [child] 

 

# evaluate the results 

cSet = set(commons) 

tSet = set(tmp_names) 

# check for identity and stop iteration if tips are identical 

if cSet == tSet: 

scenario += [(tmp_tree.lowestCommonAncestor(presents).Name, 1)] 

# otherwise check for intersection and small amount of 

# differences 

# elif tmp_tree == tree.lowestCommonAncestor(commons): 

# elif cSet.issubset(tSet) and len(tSet) - len(cSet) < len(tSet) / 2: 

# scenario += [(tmp_tree.lowestCommonAncestor(presents).Name,1)] 

# otherwise append the other results to the queue 

else: 

add2scenario = [] 

for child in tmp_results: 

if child.Children: 

queue += [(child, counter + 1)] 

else: 

if child.Name in presents: 

add2scenario += [child] 

 

if len(add2scenario) == 2: 

if add2scenario[0].Parent == add2scenario[1].Parent: 

scenario += [(add2scenario[0].Parent.Name, 1)] 

else: 

for c in add2scenario: 

scenario += [(c.Name, 1)] 

else: 

for c in add2scenario: 

scenario += [(c.Name, 1)] 

 

# TODO fill the scenario with gaps 

output = [] 

d = {taxon: 1 if paps[i] >= 1 else 0 for i, taxon in enumerate(taxa)} 

 

for s in scenario: 

output += [s] 

subtree = tree.getNodeMatchingName(s[0]) 

 

if subtree.Children: 

# order the internal nodes according to the number of their leaves 

ordered_nodes = sorted( 

subtree.nontips() + [subtree], key=lambda x: len(x.tips())) 

 

# start bottom-up 

for node in ordered_nodes: 

children = node.Children 

states = [] 

 

for child in children: 

state = d[child.Name] 

states += [state] 

 

# check for identity of states 

if sum(states) == len(states): 

d[node.Name] = 1 

elif sum(states) == 0: 

d[node.Name] = 0 

else: 

d[node.Name] = 1 

for i, state in enumerate(states): 

if state == 0: 

output += [(children[i].Name, 0)] 

 

return output 

 

def _get_GLS( 

self, 

pap, 

mode='w', 

r=(1, 1), 

gpl=1, 

push_gains=True, 

missing_data=0 

): 

""" 

Calculate a gain-loss scenario (GLS) for a given PAP. 

 

Parameters 

---------- 

pap : list 

The presence/absence pattern of a given cognate-set. 

mode : str (default='w') 

The mode of the analysis, select between "w" (weights) and "r" 

(restrictio). 

r : { tuple, int } (default=(1,1)) 

The weights (as binary tuple) or the restriction (an integer), 

negative restrictions mark the maximal amount of losses. 

gpl : int (default=1) 

The maximal number of gains per lineage. 

push_gains : bool (default=True) 

Indicate whether gains should be pushed to the leaves or not. 

missing_data : int (default=0) 

Indicate, how missing values should be represented in the paps. If 

set to 0, missing values will be treated as non-cognate words. If 

set to 1, missing values will be treated as potential cognates. 

 

""" 

# make a dictionary that stores the scenario 

d = {} 

taxa, paps = self._existing_taxa_and_paps(pap, missing_data) 

 

# get the subtree containing all taxa that have positive paps 

tree = self.tree.lowestCommonAncestor( 

[self.taxa[i] for i in range(len(self.taxa)) if pap[i] >= 1]) 

 

log.debug("Subtree is {0}.".format(text_type(tree))) 

 

# assign the basic (starting) values to the dictionary 

nodes = [t.Name for t in tree.tips()] 

log.debug("Nodes are {0}.".format(','.join(nodes))) 

 

# calculate the initial restriction value (maximal weight). This is roughly 

# spoken simply the minimal value of either all events being counted as 

# origins (case 1) or assuming origin of the character at the root and 

# counting all leaves that lost the character as single loss events (case 

# 2). In case two, the first gain of the character has to be added 

# additionally 

if mode == 'w': 

RST = min(paps.count(1) * r[0], paps.count(0) * r[1] + r[0]) 

elif mode == 'r': 

RST = r 

 

# get maximal number of gains and losses, note that we have to include 

# missing data in a two-fold fashion here. this is probably 

# computationally not the most feasible solution. however, it is the 

# only way I can think of at the moment 

maxG = sum([1 for x in nodes if paps[taxa.index(x)] in (1, -1)]) 

maxL = sum([1 for x in nodes if paps[taxa.index(x)] in (0, -1)]) 

 

log.debug("Initial restriction threshold is {0}.".format(RST)) 

 

# get the first state of all nodes and store the state in the 

# dictionary. note that we start from two distinct scenarios: one 

# assuming single origin at the root where all present states in the 

# leave are treated as retentions, and one assuming multiple origins, 

# where all present states in the leaves are treated as origins 

dbpaps = [] 

for node in nodes: 

idx = taxa.index(node) 

if paps[idx] >= 1: 

state = 1 

else: 

state = paps[idx] 

dbpaps += [node + '/' + str(state)] 

 

# we append the maximally remaining possible number of gains and 

# losses to the queue dictionary and decrease it steadily once two 

# branches are merged as either loss or gain 

d[node] = [(state, [], maxG, maxL)] 

 

# return simple scenario, if the group is single-origin 

if sum([d[node][0][0] for node in nodes]) == len(nodes): 

return [(tree.Name, 1)] 

 

# order the internal nodes according to the number of their leaves 

ordered_nodes = sorted(tree.nontips() + [tree], key=lambda x: len(x.tips())) 

 

search_space = 0 

log.debug('The Pap to be analysed: %s' % ', '.join(dbpaps)) 

 

# join the nodes successively 

for i, node in enumerate(ordered_nodes): 

log.debug('Node to be joined in this run: %s' % node) 

 

# when dealing with multifurcating trees, we have to store all 

# possible scenarios, i.e. we need to store the crossproduct of all 

# scenarios 

 

names = [x.Name for x in node.Children] 

 

# get the nodes with their states from the dictionary 

tmp_nodes = [d[x.Name] for x in node.Children] 

 

# get the cross-product of the stuff 

crossp = itertools.product(*tmp_nodes) 

 

newNodes = [] 

 

# combine the histories of the items if all have the same value, 

# therefore, we first get the states in a simple list 

for cross in crossp: 

search_space += 1 

 

states = [x[0] for x in cross] 

stories = [x[1] for x in cross] 

 

# get the restriction values 

maxGains = [x[2] for x in cross] 

maxLosses = [x[3] for x in cross] 

 

states_1 = states.count(1) 

states_0 = states.count(0) 

states_m = states.count(-1) # missing states 

 

states_len = len(states) 

 

# get the minimal gain and loss values 

maxGain = max(maxGains) 

maxLoss = max(maxLosses) 

 

# calculate the restriction value 

if mode == 'w': 

# the following line contains some serious bug 

# (DENKFEHLER), it works at the moment, but we should be 

# very DAMN careful with this! 

rst = min(maxGain * r[0] + r[1], maxLoss * r[1] + r[0]) 

else: 

rst = abs(RST) 

 

log.debug( 

"... MaxG / MaxL / rst: {0} / {1} / {2}.".format(maxGain, maxLoss, 

rst)) 

# log.debug("... Stories: %s" % stories) 

 

# combine the histories 

new_stories = [] 

for x in stories: 

new_stories += x 

 

# if states are identical and point to gain / presence of 

# chars, we add them directly. here we also include the number 

# of missing states: if missing states turn up, we simply treat 

# them as presence values 

if states_1 + states_m == states_len: 

 

# add the histories to the queue only if their weight is 

# less or equal to the maxWeight 

gl = [k[1] for k in new_stories] + [1] 

 

if mode == 'w': 

weight = gl.count(1) * r[0] + gl.count(0) * r[1] 

else: 

if RST < 0: 

weight = gl.count(0) 

else: 

weight = gl.count(1) + 1 # we need to add 1 here 

 

log.debug("... state,weight: %s %s" % (gl, weight)) 

# when combining two gains, make sure that the allowed 

# amount of gains per lineage will not be overwritten by 

# the combination of new gains 

gains_per_lineage = sum([1 for k in new_stories if k[1] == 1]) 

 

if weight <= rst and gains_per_lineage < gpl: 

 

# make sure to append a smaller restriction value, 

# since we could spare one event due to regular 

# calculation 

if mode == 'w': 

newNodes.append((1, new_stories, maxGain - 1, maxLoss)) 

else: 

# if gl.count(0) <= maxLoss: 

newNodes.append((1, new_stories, maxGain, maxLoss)) 

 

# if states are identical and point to absence of chars, we 

# assign them directly to the higher node. here, missing chars 

# are also included 

elif states_0 + states_m == states_len: 

gl = [k[1] for k in new_stories] 

log.debug("... state is 1 %s" % gl) 

 

if mode == 'w': 

weight = gl.count(1) * r[0] + gl.count(0) * r[1] 

else: 

weight = gl.count(0 if RST < 0 else 1) 

 

log.debug("... state,weight: %s %s" % (gl, weight)) 

 

if weight <= rst: 

newNodes.append((0, new_stories, maxGain, maxLoss - 1)) 

 

# if states are both missing 

elif states_m == states_len: 

log.debug("... all states are missing") 

newNodes.append((-1, new_stories, maxGain, maxLoss - 1)) 

 

# if the states are not identical, we check for both scenarios 

else: 

log.debug("... states are different.") 

 

# first scenario (tmpA) assumes origin, that is, for each node 

# that has a 1, we add an origin to new_stories, same is 

# for loss scenario (tmpB) 

tmpA = [x for x in new_stories] 

tmpB = [x for x in new_stories] 

for c, state in enumerate(states): 

if state == 1 or state == -1: 

tmpA += [(names[c], 1)] 

if state == 0 or state == -1: 

tmpB += [(names[c], 0)] 

 

# get the vectors to make it easier to retrieve the number 

# of losses and gains 

glA = [k[1] for k in tmpA] 

glB = [k[1] for k in tmpB] + [1] # don't forget adding 1 origin 

 

# check the gain-loss scores 

if mode == 'w': 

weightA = glA.count(1) * r[0] + glA.count(0) * r[1] 

weightB = glB.count(1) * r[0] + glB.count(0) * r[1] 

else: 

if RST < 0: 

weightA = glA.count(0) 

weightB = glB.count(0) 

else: 

weightA = glA.count(1) 

weightB = glB.count(1) 

 

# create the new nodes. Note that we can only reduce the 

# number of losses here by one, but not the possible number 

# of gains, since the last gain will also score in our 

# calculation, but we cannot predict, whether a given gain 

# is indeed the last one (or can we?) 

newNodeA = (0, tmpA, maxGain, maxLoss) 

newNodeB = (1, tmpB, maxGain, maxLoss) 

 

# check for additional gains in the gain-scenario, 

# according to the current model, we don't allow for one 

# character to be gained twice along a branch, i.e. by an 

# ancestor, then get lost, and than be gained anew 

gains_per_lineage = sum([1 for k in tmpB if k[1] == 1]) 

noB = gains_per_lineage >= gpl 

 

if weightA <= rst: 

newNodes += [newNodeA] 

 

if weightB <= rst and not noB: 

newNodes += [newNodeB] 

 

d[node.Name] = newNodes 

log.debug("... Possible scenarios for '{0}': {1}".format(node.Name, len( 

d[node.Name]))) 

 

# try to find the best scenario by counting the ratio of gains and losses. 

# the key idea here is to reduce the number of possible scenarios according 

# to a given criterion. We choose the criterion of minimal changes as a 

# first criterion to reduce the possibilities, i.e. we weight both gains 

# and losses by 1 and select only those scenarios where gains and losses 

# sum up to a minimal number of gains and losses. This pre-selection of 

# scenarios can be further reduced by weighting gains and losses 

# differently. So in a second stage we choose only those scenarios where 

# there is a minimal amount of gains. 

 

# convert the specific format of the d[tree.Name] to simple format 

gls_list = [] 

for first, last, mg, ml in d[tree.Name]: 

log.debug('%s %s' % (first, last)) 

if first == 1: 

gls_list.append([(tree.Name, first)] + last) 

else: 

gls_list.append(last) 

 

log.debug("Number of inferred scenarios: %s" % len(d[tree.Name])) 

log.debug("Number of decisions: %s" % search_space) 

 

# the tracer stores all scores 

tracer = [] 

 

for i, line in enumerate(gls_list): 

# calculate gains and losses 

gains = sum([1 for x in line if x[1] == 1]) 

losses = sum([1 for x in line if x[1] == 0]) 

 

# calculate the score 

if mode == 'w': 

score = r[0] * gains + r[1] * losses 

else: 

score = gains + losses 

 

tracer.append(score) 

 

minScore = min(tracer) 

 

if mode == 'w': 

# return the minimal indices, sort them according to the number of 

# gains inferred, thereby pushing gains to the root, similar to 

# Mirkin's (2003) suggestion 

best_gls = [gls_list[i] for i in range(len(tracer)) if tracer[i] == minScore] 

return sorted( 

best_gls, key=lambda x: sum([i[1] for i in x]), reverse=push_gains)[0] 

 

# push gains down to the root as suggested by Mirkin 2003 

minimal_gains = [gls_list[i] for i in range(len(tracer)) if tracer[i] == minScore] 

 

# make sure to check the model with minimal amount of gains 

minGains = len(self.taxa) 

for i, line in enumerate(minimal_gains): 

gains = sum([1 for x in line if x[1] == 1]) 

if gains <= minGains: 

minGains = gains 

minimal_gains = [line for line in minimal_gains 

if sum([1 for x in line if x[1] == 1]) == minGains] 

 

best_scenario = 0 

old_length_of_tips = len(self.taxa) + 1 

 

for i, line in enumerate(minimal_gains): 

# calculate number of tips for the gains of a given scenario 

new_length_of_tips = 0 

for taxon, state in line: 

if state == 1: 

new_length_of_tips += len( 

self.tree.getNodeMatchingName(taxon).getTipNames()) 

if new_length_of_tips < old_length_of_tips: 

old_length_of_tips = new_length_of_tips 

best_scenario = i 

 

return minimal_gains[best_scenario] 

 

def _plot(self, glm, output_plot, tar, fileformat='png'): 

# store the graph 

for cog in self.cogs: 

gls = self.gls[glm][cog][0] 

g = gls2gml( 

gls, 

self.tgraph, 

self.tree, 

filename=self._output_path( 

'gml', '{0}-{1}'.format(self.dataset, glm), cog)) 

 

if output_plot: 

nodes = [] 

for n, d in g.nodes(data=True): 

nodes.append(( 

d['graphics']['x'], 

d['graphics']['y'], 

d['graphics']['fill'], 

d['origin'], 

d['label'])) 

 

edges = [] 

for a, b, d in g.edges(data=True): 

edges.append(( 

g.node[a]['graphics']['x'], 

g.node[b]['graphics']['x'], 

g.node[a]['graphics']['y'], 

g.node[b]['graphics']['y'])) 

 

# mpl.rc('text',usetex=keywords['usetex']) 

fig = plt.figure() 

fig.add_subplot(111) 

plt.axes(frameon=False) 

plt.xticks([]) 

plt.yticks([]) 

plt.axis('equal') 

 

for xA, xB, yA, yB in edges: 

plt.plot([xA, xB], [yA, yB], '-', color='black', linewidth=5) 

plt.plot([xA, xB], [yA, yB], '-', color='0.2', linewidth=4) 

for x, y, f, o, l in nodes: 

if l.startswith('edge') or l.startswith('root'): 

plt.plot(x, y, 'o', markersize=20 if o == 1 else 10, color=f) 

else: 

plt.text( 

x, 

y, 

l, 

horizontalalignment='center', 

verticalalignment='center', 

size=8, 

fontweight='bold', 

color='#ffffff' if f == '#000000' else '#000000', 

backgroundcolor=f) 

 

# plt.subplots_adjust(left=0.02,right=0.98,top=0.98,bottom=0.02) 

plt.savefig(self._output_path( 

'gml', 

'{0}-{1}-figures'.format(self.dataset, glm), 

cog + '.' + fileformat)) 

plt.clf() 

 

# if tar is chosen, put it into a tarfile 

if tar: 

os.system( 

'cd {0}_phybo/gml/ ; tar -pczf {0}-{1}.tar.gz {0}-{1}; cd ..; cd ..'.format( 

self.dataset, glm)) 

os.system('rm {0}_phybo/gml/{0}-{1}/*.gml'.format(self.dataset, glm)) 

os.system('rmdir {0}_phybo/gml/{0}-{1}'.format(self.dataset, glm)) 

 

def get_GLS( 

self, 

mode='weighted', 

ratio=(1, 1), 

restriction=3, 

output_gml=False, 

output_plot=False, 

tar=False, 

**keywords 

): 

""" 

Create gain-loss-scenarios for all non-singleton paps in the data. 

 

Parameters 

---------- 

mode : string (default="weighted") 

Select between "weighted", "restriction" and "topdown". The three 

modes refer to the following frameworks: 

 

* "weighted" refers to the weighted parsimony framework described in 

:evobib:`List2014b` and :evobib:`List2014a`. 

Weights are 

specified with help of a ratio for the scoring of gain and loss 

events. The ratio can be defined with help of the *ratio* 

keyword. 

* "restrictino" refers to a simple method in which only a 

specific amount of gain events 

is allowed. The maximally allowed number of gain events can be 

defined with help of the *restriction* keyword. 

* "topdown" refers to the top-down method outlined in 

:evobib:`Dagan2007` and first applied to linguistic data in 

:evobib:`Nelson-Sathi2011`. This method also defines a maximal 

number of gain events, but in contrast to the "restriction" 

approach, it starts from the top of the tree and stops if the 

maximal number of restrictions has been reached. The maximally 

allowed number of gain events can, again, be specified with help 

of the *restriction* keyword. 

ratio : tuple (default=(1,1)) 

If "weighted" mode is selected, define the ratio between the 

weights for gains and losses. 

restriction : int (default=3) 

If "restriction" is selected as mode, define the maximal number of 

gains. 

output_gml : bool (default=False) 

If set to c{True}, the decisions for each GLS are stored in a 

separate file in GML-format. 

tar : bool (default=False) 

If set to c{True}, the GML-files will be added to a compressed tar-file. 

gpl : int (default=1) 

Specifies the maximal number of gains per lineage. This parameter 

specifies how cases should be handled in which a character is first 

gained, then lost, and then gained again. By setting this parameter 

to 1 (the default setting), such cases are prohibited, since only 

one gain per lineage is allowed. 

missing_data : int (default=0) 

Currently, we offer two ways to handle missing data. The first case 

just treats missing data in the same way in which the absence of a 

character is handled and can be evoked by setting this parameter to 

0. The second case will treat missing data as either absent or 

present characters, based on how well each option coincides with 

the overall evolutionary scenario. This behaviour can be evoked by 

setting this parameter to -1. 

push_gains: bool (default=True) 

In bottom-up calculations, there will often be multiple scenarios 

upon which only one is selected by the method. In order to define 

consistent criteria for scenario selection, we follow 

:evobib:`Mirkin2003` in allowing to force the algorithm to prefer 

those scenarios in which gains are pushed to the leaves. This 

behaviour is handle by this parameter. Setting it to *True* will 

force the algorithm to push gain events to the leaves of the tree. 

Setting it to *False* will force it to prefer those scenarios where 

the gains are closer to the root. 

 

 

""" 

if mode not in ['weighted', 'w', 'r', 'restriction', 't', 'topdown']: 

raise ValueError("[!] The mode {0} is not available".format(mode)) 

 

# define alias for mode 

if mode in ['w', 'weighted']: 

mode = 'weighted' 

elif mode in ['r', 'restriction']: 

mode = 'restriction' 

else: 

mode = 'topdown' 

 

# create a named string for the mode 

if mode == 'weighted': 

glm = 'w-{0[0]}-{0[1]}'.format(ratio) 

elif mode == 'restriction': 

glm = 'r-{0}'.format(restriction) 

elif mode == 'topdown': 

glm = 't-{0}'.format(restriction) 

 

util.setdefaults( 

keywords, 

force=False, 

gpl=1, 

push_gains=True, 

missing_data=0) 

 

# check for previous analyses 

if glm in self.gls and not keywords['force']: 

log.info( 

"Gain-loss scenario {0} has already been calculated. For recalculation, " 

"set 'force' to 'True'.".format(glm)) 

return 

 

# create statistics for this run 

self.stats[glm] = {} 

 

# store the statistics 

self.stats[glm]['mode'] = mode 

self.stats[glm]['dataset'] = self.dataset 

 

# attribute stores all gls for each cog 

self.gls[glm] = {} 

 

# make a temporary hash in order to decrease the number of calls to the algorithm 

cogDict = {} 

 

skip, nonskip = 0, 0 

for cog in util.pb(self.cogs, desc='GAIN-LOSS-MAPPING ({0})'.format(glm)): 

# check whether cog has already been calculated 

cogTuple = tuple(self.paps[cog]) 

if cogTuple in cogDict: 

skip += 1 

log.debug( 

"Skipping already calculated pattern for COG {0}...".format(cog)) 

self.gls[glm][cog] = cogDict[cogTuple] 

else: 

nonskip += 1 

log.debug("Calculating GLS for COG {0}...".format(cog)) 

 

# check for singletons 

if sum([x for x in self.paps[cog] if x == 1]) == 1: 

gls = [(self.taxa[self.paps[cog].index(1)], 1)] 

else: 

if mode == 'weighted': 

gls = get_gls( 

self.paps[cog], 

self.taxa, 

self.tree, 

gpl=keywords['gpl'], 

weights=ratio, 

push_gains=keywords['push_gains'], 

missing_data=keywords['missing_data'] 

) 

 

if mode == 'restriction': 

gls = self._get_GLS( 

self.paps[cog], 

r=restriction, 

mode='r', 

gpl=keywords['gpl'], 

push_gains=keywords['push_gains'], 

missing_data=keywords['missing_data'] 

) 

 

if mode == 'topdown': 

gls = self._get_GLS_top_down( 

self.paps[cog], 

mode=restriction, 

missing_data=keywords['missing_data'] 

) 

noo = sum([t[1] for t in gls]) 

 

self.gls[glm][cog] = (gls, noo) 

 

# append new results to cogDict 

cogDict[cogTuple] = (gls, noo) 

 

# append scenario to gls 

log.info("Successfully calculated Gain-Loss-Scenarios.") 

 

# write the results to file 

# if output of gls is chosen, load the gml-graph 

if output_gml: 

self._plot(glm, output_plot, tar) 

 

# store some statistics as attributes 

self.stats[glm]['ano'] = sum( 

[v[1] for v in self.gls[glm].values()] 

) / len(self.gls[glm]) 

self.stats[glm]['mno'] = max([v[1] for v in self.gls[glm].values()]) 

self.stats[glm]['ratio'] = ratio 

self.stats[glm]['restriction'] = restriction 

 

# store statistics and gain-loss-scenarios in textfiles 

log.info("Writing GLS data to file... ") 

 

lines = [['PAP', 'GainLossScenario', 'NumberOfOrigins']] 

for cog in sorted(self.gls[glm]): 

gls, noo = self.gls[glm][cog] 

lines.append([ 

"{0}".format(cog), 

','.join(["{0}:{1}".format(a, b) for a, b in gls]), 

text_type(noo)]) 

self._write_file( 

os.path.join('gls', '{0}-{1}.gls'.format(self.dataset, glm)), 

[util.tabjoin(line) for line in lines]) 

 

log.info("Average Number of Origins: {0:.2f}".format(self.stats[glm]['ano'])) 

 

lines = [ 

'Number of PAPs (total): {0}'.format(len(self.paps)), 

'Number of PAPs (non-singletons): {0}'.format(len(self.gls[glm])), 

'Number of Singletons: {0}'.format(len(self.singletons)), 

'Average Number of Origins: {0:.2f}'.format(self.stats[glm]['ano']), 

'Maximum Number of Origins: {0}'.format(self.stats[glm]['mno']), 

'Mode: {0}'.format(mode), 

] 

if mode == 'weighted': 

lines.append('Ratio: {0[0]} / {0[1]}'.format(ratio)) 

elif mode == 'restriction': 

lines.append('Restriction: {0}'.format(restriction)) 

self._write_file( 

os.path.join('stats', '{0}-{1}'.format(self.dataset, glm)), lines) 

return 

 

def get_CVSD(self): 

""" 

Calculate the Contemporary Vocabulary Size Distribution (CVSD). 

 

""" 

# -># define taxa and concept as attribute for convenience 

# ->taxa = self.taxa 

# ->concepts = self.concept #XXX do we need this? XXX 

 

# -># calculate vocabulary size 

# ->forms = [] 

# ->meanings = [] 

# ->for taxon in taxa: 

# -> f = [x for x in set( 

# -> self.get_list(col=taxon,entry=self._pap_string,flat=True) 

# -> ) if x in self.cogs 

# -> ] 

# -> m = set([x.split(':')[1] for x in f]) 

# -> forms += [len(f)] 

# -> meanings += [len(m)] 

# -> 

# -># store the stuff as an attribute 

# ->self.dists['contemporary'] = [x for x,y in zip(forms,meanings)] # XXX 

dists = [] 

for t in self.taxa: 

paps = sorted(set(p for p in self.get_list( 

taxa=t, entry=self._pap_string, flat=True) if p not in self.singletons)) 

forms = len(paps) 

dists += [forms] # / concepts] 

self.dists['contemporary'] = dists 

log.info("Calculated the distributions for contemporary taxa.") 

return 

 

def get_AVSD(self, glm, **keywords): 

""" 

Function retrieves all pap s for ancestor languages in a given tree. 

""" 

util.setdefaults(keywords, proto=False, force=False) 

 

# check for already calculated glm 

# check for previous analyses 

if glm in self.dists and not keywords['force'] and glm != 'mixed': 

log.info( 

"Gain-loss scenario {0} has already been calculated. For recalculation, " 

"set 'force' to 'True'.".format(glm)) 

log.info("For recalculation, set 'force' to True.") 

return 

 

acs, dst = get_acs(self, glm, **keywords) 

self.dists[glm] = dst 

 

self.acs[glm] = {} 

if keywords['proto']: 

paps = [self[k, self._pap_string] for k in self] 

protos = [self[k, keywords['proto']] for k in self] 

p2p = dict(zip(paps, protos)) 

pap2protos = lambda x: p2p[x] 

else: 

pap2protos = lambda x: x # dict(zip(paps,paps)) 

 

for k, v in acs.items(): 

self.acs[glm][k] = [(p, self.pap2con[p], pap2protos(p)) for p in v] 

 

# -># define concepts for convenience 

# ->concepts = self.concepts # XXX do we need this? XXX 

# -> 

# -># get all internal nodes, i.e. the nontips and also the root 

# ->nodes = ['root'] + sorted( 

# -> [node.Name for node in self.tree.nontips()], 

# -> key=lambda x: len(self.tree.getNodeMatchingName(x).tips()), 

# -> reverse = True 

# -> ) 

 

# -># retrieve scenarios 

# ->tmp = sorted([(a,b,c) for a,(b,c) in self.gls[glm].items()]) 

# ->cog_list = [t[0] for t in tmp] 

# ->gls_list = [t[1] for t in tmp] 

# ->noo_list = [t[2] for t in tmp] 

 

# -># create a list that stores the paps 

# ->paps = [[0 for i in range(len(nodes))] for j in range(len(cog_list))] 

 

# -># iterate and assign values 

# ->for i,cog in enumerate(cog_list): 

# -> 

# -> # sort the respective gls 

# -> gls = sorted( 

# -> gls_list[i], 

# -> key = lambda x: len(self.tree.getNodeMatchingName(x[0]).tips()), 

# -> reverse = True 

# -> ) 

 

# -> # retrieve the state of the root 

# -> if gls[0][1] == 1 and gls[0][0] == 'root': 

# -> state = 1 

# -> else: 

# -> state = 0 

 

# -> # assign the state of the root to all nodes 

# -> paps[i] = [state for node in nodes] 

 

# -> # iterate over the gls and assign the respective values to all 

# -> # children 

# -> # XXX note that here we assume that missing data is coded as 

# -> # 0, so this should probably be adapted XXX 

# -> for name,event in gls: 

# -> if event == 1: 

# -> this_state = 1 

# -> else: 

# -> this_state = 0 

 

# -> # get the subtree nodes 

# -> sub_tree_nodes = [node.Name for node in 

# -> self.tree.getNodeMatchingName(name).nontips()] 

 

# -> # assign this state to all subtree nodes 

# -> for node in sub_tree_nodes: 

# -> paps[i][nodes.index(node)] = this_state 

 

# -># get number of forms and number of meanings 

# -># extract cogs instead of numbers, XXX this can actually be done in the 

# -># step before, it's just for testing at the moment 

# ->for i,cog in enumerate(cog_list): 

# -> for j,t in enumerate(paps[i]): 

# -> if t == 1: 

# -> paps[i][j] = cog 

# -> else: 

# -> pass 

# -> 

# -># get forms and meanings 

# ->forms = [] 

# ->meanings = [] 

# ->for i in range(len(paps[0])): 

# -> f = set([x[i] for x in paps if x[i] != 0]) 

# -> m = set([x[i].split(':')[1] for x in paps if x[i] != 0]) 

# -> forms += [len(f)] 

# -> meanings += [len(m)] 

 

# -># store the number of forms as an attribute 

# ->self.dists[glm] = [x for x,y in zip(forms,meanings)] # XXX 

 

# -># store results of the analyses, that is, all paps for each ancestral 

# -># node 

# ->cogs = [k[self.header['pap']] for k in self._data.values()] 

 

# -># search for proto as keyword 

# ->if keywords['proto']: 

# -> protos = [k[self.header[keywords['proto']]] for k in 

# -> self._data.values()] 

# -> cogs2proto = dict(zip(cogs,protos)) 

# ->else: 

# -> cogs2proto = dict(zip(cogs,cogs)) 

 

# -># store data in acs attribute (ancestral cognate states) 

# ->self.acs[glm] = {} 

# ->for i,n in enumerate(nodes): 

# -> for j,p in enumerate(paps): 

# -> c = paps[j][i] 

# -> if c != 0: 

# -> m = self.pap2con[c] 

# -> p = cogs2proto[c] 

 

# -> if n != 'root': 

# -> node = self.tree.getNodeMatchingName(n) 

# -> node = n #''.join( 

# -> #[x for x in str(node) if x not in '";()'+"'"] 

# -> #)#.replace('(','').replace(')','').replace(',','-') 

# -> else: 

# -> node = n 

# -> 

# -> try: 

# -> self.acs[glm][node] += [(c,m,p)] 

# -> except: 

# -> self.acs[glm][node] = [(c,m,p)] 

 

log.info("Calculated the distributions for ancestral taxa.") 

return 

 

def plot_ACS(self, glm, **keywords): 

""" 

Plot a tree in which the node size correlates with the size of the ancestral node. 

""" 

util.setdefaults( 

keywords, 

scaler=0.1, 

degree=180, 

change=lambda x: 2.5 * x, 

figsize=(10, 5), 

colormap=mpl.cm.jet, 

colors=True) 

 

# check for the model 

if glm not in self.acs: 

self.get_ACS(glm, **keywords) 

 

# create a dictionary for all nodes 

node_dict = {} 

 

# iterate over contemporary taxa first 

vsizes = [] 

tmp = {} 

for taxon in self.taxa: 

# get all cognates that are not singletongs 

cogs = sorted(set([x for x in self.get_list( 

col=taxon, flat=True, entry='pap') if x in self.singletons])) 

 

# count the number of paps 

node_dict[taxon] = dict(nodesize=len(cogs) * keywords['scaler']) 

 

vsizes += [len(cogs)] 

tmp[taxon] = len(cogs) 

 

# iterate over internal nodes now 

for a, b in [(x, y) for x, y in self.tree.getNodesDict().items() if 

x not in self.taxa]: 

node = a if a != 'root' else 'root' 

node_dict[a] = dict(nodesize=len(self.acs[glm][node]) * keywords['scaler']) 

tmp[a] = len(self.acs[glm][node]) 

vsizes += [len(self.acs[glm][node])] 

 

if keywords['colors']: 

vsizes = sorted(set(vsizes)) 

cfunc = np.array(np.linspace(10, 256, 245), dtype='int') 

for node in node_dict: 

node_dict[node]['nodecolor'] = mpl.colors.rgb2hex( 

keywords['colormap'](cfunc[int(tmp[node] * 244 / max(vsizes))])) 

 

keywords['node_dict'] = node_dict 

 

# check for filename in keywords 

if 'filename' not in keywords: 

keywords['filename'] = self._output_path(glm + '_acs') 

 

plot_tree(self.tree, no_labels=True, **keywords) 

 

def get_IVSD( 

self, 

output_gml=False, 

output_plot=False, 

tar=True, 

leading_model=False, 

mixed_threshold=0.0, 

evaluation='mwu', 

**keywords 

): 

""" 

Calculate VSD on the basis of each item. 

 

""" 

kw = dict(fileformat='png', homoplasy=0.05) 

kw.update(keywords) 

 

# assign concept dict 

mixed_concepts = {} 

 

# define concepts and taxa for convenience 

concepts = self.concepts 

taxa = self.taxa 

 

# get all internal nodes, i.e. the nontips and also the root 

nodes = ['root'] + sorted( 

[node.Name for node in self.tree.nontips()], 

key=lambda x: len(self.tree.getNodeMatchingName(x).tips()), 

reverse=True) 

 

# make dictionary that stores the best models for each cognate set 

best_models = {} 

 

# make array for all nodes and a dict for the scenarios 

all_avsd = [0 for node in nodes] 

scenarios = {} 

 

# iterate over concepts 

for concept in concepts: 

# get paps 

tmp = self.get_dict(row=concept, entry=self._pap_string) 

 

# add to list if value is missing 

for taxon in taxa: 

if taxon not in tmp: 

tmp[taxon] = [] 

 

# calculate distribution for contemporary taxa 

cvsd = [len([i for i in tmp[j] if i in self.cogs]) for j in taxa] 

 

# calculate ancestral dists, get all paps first 

pap_set = [i for i in set( 

self.get_list(row=concept, entry=self._pap_string, flat=True) 

) if i not in self.singletons] 

 

# get the models 

if leading_model: 

models = [leading_model] + sorted( 

[k for k in self.gls.keys() if k != leading_model]) 

else: 

models = sorted(list(self.gls.keys())) 

 

models = [m for m in models if 

m != 'mixed' and self._pvalues[m] >= mixed_threshold] 

 

# get the scenarios 

avsd_list = [] 

for idx, glm in enumerate(models): 

tmp_list = [] 

queue = ['root'] 

while queue: 

# get the parent 

parent = queue.pop(0) 

 

# get paps of parent 

parent_paps = [p[0] for p in self.acs[glm][parent]] 

 

# count number of paps 

tmp_list += [len([f for f in pap_set if f in parent_paps])] 

for child in self.tree.getNodeMatchingName(parent).Children: 

if child not in self.taxa: 

queue += [child.Name] 

 

avsd_list += [[int(form - form * kw['homoplasy'] + 0.5) for 

form in tmp_list]] 

 

# calculate best distribution, we can use averages for this 

# purpose, since it seems that the kruskalwallis test or 

# mannwhitneyu does not really apply to this kind of data with lots 

# of small numbers XXX 

zp_vsd = [] 

cvsd_set = set(cvsd) 

for avsd in avsd_list: 

if len(cvsd_set) == 1 and set(avsd): 

zp_vsd.append((0, 0.0)) 

else: 

if evaluation in ['mwu', 'mannwhitneyu']: 

vsd = sp.stats.mstats.kruskalwallis(cvsd, avsd) 

zp_vsd.append((vsd[0], vsd[1])) 

elif evaluation in ['average']: 

# check for best median and best average 

ave_cvsd = sum(cvsd) / len(cvsd) 

ave_avsd = sum(avsd) / len(avsd) 

 

score = abs(ave_cvsd - ave_avsd) 

zp_vsd.append((1, score)) 

 

# extract p-values 

p_vsd = [p for z, p in zp_vsd] 

if evaluation in ['mwu', 'mannwhitneyu']: 

maxP = max(p_vsd) 

elif evaluation in ['average']: 

maxP = min(p_vsd) 

 

# check for threshold 

# if leading_model: 

# if True: #maxP >= mixed_threshold: 

# maxIdx = p_vsd.index(maxP) 

# best_model = models[maxIdx] 

# else: 

# maxIdx = 0 

# best_model = leading_model 

# maxP = p_vsd[0] 

# else: 

maxIdx = p_vsd.index(maxP) 

best_model = models[maxIdx] 

 

for p in pap_set: 

gls, noo = self.gls[best_model][p] 

best_models[p] = (best_model, noo, maxP) 

scenarios[p] = (gls, noo) 

 

# add sum to general model XXX start here XXX 

all_avsd = [a + b for a, b in zip(avsd_list[maxIdx], all_avsd)] 

 

# add to concepts 

mixed_concepts[concept] = {} 

mixed_concepts[concept]['mixed'] = maxP 

 

for i, m in enumerate(models): 

mixed_concepts[concept][m] = p_vsd[i] 

 

self.best_models = best_models 

# print(sum([n for m,n,o in best_models.values()]) / len(best_models)) 

 

# append to distributions 

 

# self.dists['mixed'] = all_avsd 

 

# append to available models 

self.gls['mixed'] = scenarios 

self.get_AVSD('mixed', **kw) 

 

# write the results to file 

# if output of gls is chosen, load the gml-graph 

if output_gml: 

self._plot('mixed', output_plot, tar, fileformat=kw['fileformat']) 

 

# store some statistics as attributes 

self.stats['mixed'] = {} 

self.stats['mode'] = 'mixed' 

self.stats['dataset'] = self.dataset 

self.stats['mixed']['ano'] = sum( 

[v[1] for v in self.gls['mixed'].values()] 

) / len(self.gls['mixed']) 

self.stats['mixed']['mno'] = max([v[1] for v in self.gls['mixed'].values()]) 

 

self.stats['mixed_concepts'] = mixed_concepts 

 

# store statistics and gain-loss-scenarios in textfiles 

log.info("Writing GLS data to file... ") 

 

# write gls-data to folder 

with util.TextFile( 

self._output_path('gls', '{0}-{1}.gls'.format(self.dataset, "mixed")), 

log=False 

) as f: 

f.write('PAP\tGainLossScenario\tNumberOfOrigins\n') 

for cog in sorted(self.gls["mixed"]): 

gls, noo = self.gls["mixed"][cog] 

f.write( 

"{0}\t".format(cog) + ','.join( 

["{0}:{1}".format(a, b) for a, b in gls] 

) + '\t' + str(noo) + '\n' 

) 

return 

 

def get_ACS(self, glm, **keywords): 

""" 

Compute the ancestral character states (ACS) for all internal nodes. 

 

""" 

util.setdefaults( 

keywords, 

proto=False, 

force=False, 

filename=self._output_path('acs-' + glm), 

fileformat='csv') 

 

if glm not in self.acs: 

self.get_AVSD(glm, **keywords) 

elif keywords['force']: 

self.get_AVSD(glm, **keywords) 

 

with util.TextFile(keywords['filename'] + '.' + keywords['fileformat']) as f: 

for key in sorted(self.acs[glm].keys(), key=lambda x: len(x)): 

for c, m, p in sorted(self.acs[glm][key], key=lambda x: x[1]): 

f.write('{0}\t{1}\t{2}\t{3}\n'.format(key, c, m, p)) 

 

def get_MLN(self, glm, threshold=1, method='mr'): 

""" 

Compute an Minimal Lateral Network for a given model. 

 

Parameters 

---------- 

glm : str 

The dictionary key for the gain-loss-model. 

threshold : int (default=1) 

The threshold used to exclude edges. 

method : str (default='mr') 

Select the method for MLN calculation. Choose between: 

* "mr": majority-rule, multiple links are resolved by selecting 

those which occur most frequently 

* "td": tree-distance, multiple links are resolved by selecting 

those which are closest on the tree 

* "bc": betweenness-centrality, multiple links are resolved by 

selecting those which have the highest betweenness centrality 

 

""" 

gPrm = nx.Graph() 

 

# make alias for tree and taxa for convenience 

taxa = self.taxa 

tree = self.tree 

 

# get the topological graph 

gTpl = self.tgraph 

 

# make alias for the current gls for convenience 

scenarios = self.gls[glm] 

 

# create dictionary for inferred lateral events 

ile = {} 

 

# create out graph 

gOut = nx.Graph() 

 

# load data for nodes into new graph 

for node, data in gTpl.nodes(data=True): 

if data['label'] in taxa: 

data['graphics']['fill'] = '#ff0000' 

data['graphics']['type'] = 'rectangle' 

data['graphics']['w'] = 80.0 

data['graphics']['h'] = 20.0 

else: 

data['graphics']['type'] = 'ellipse' 

data['graphics']['w'] = 30.0 

data['graphics']['h'] = 30.0 

data['graphics']['fill'] = '#ff0000' 

gPrm.add_node(data['label'], **data) 

 

# load edge data into new graph 

for nodeA, nodeB, data in gTpl.edges(data=True): 

if 'graphics' not in data: 

data['graphics'] = {} 

data['graphics']['width'] = 10.0 

data['graphics']['fill'] = '#000000' 

data['label'] = 'vertical' 

gPrm.add_edge(gTpl.node[nodeA]['label'], gTpl.node[nodeB]['label'], **data) 

 

# start to assign the edge weights 

for cog, (gls, noo) in scenarios.items(): 

# connect the origins with edges 

for oriA, oriB in util.combinations2(x[0] for x in gls if x[1] == 1): 

if not gPrm.has_edge(oriA, oriB): 

gPrm.add_edge(oriA, oriB, weight=1) 

else: 

gPrm[oriA][oriB]['weight'] += 1 

 

log.info("Calculated primary graph.") 

log.info("Inferring lateral edges...") 

 

gMST = nx.Graph() 

 

for cog, (gls, noo) in util.pb( 

scenarios.items(), desc='MLN-RECONSTRUCTION', total=len(scenarios)): 

ile[cog] = [] 

oris = [x[0] for x in gls if x[1] == 1] 

gWeights = nx.Graph() 

 

# calculate majority-rule edges 

if method in ['majority_rule', 'mr']: 

# iterate over nodes 

for nodeA, nodeB in util.combinations2(oris): 

gWeights.add_edge( 

nodeA, nodeB, weight=gPrm[nodeA][nodeB]['weight']) 

elif method in ['tree_distance', 'td']: 

for nodeA, nodeB in util.combinations2(oris): 

try: 

w = len(self.tree.getConnectingEdges(nodeA, nodeB)) 

except ValueError: 

if 'root' in (nodeA, nodeB): 

w = len(self.tree.getConnectingEdges(nodeB, nodeA)) 

else: 

w = len(self.tree.getConnectingEdges('root', nodeA)) +\ 

len(self.tree.getConnectingEdges('root', nodeB)) 

gWeights.add_edge(nodeA, nodeB, weight=w) 

elif method in ['betweenness_centrality', 'bc']: 

bc = nx.edge_betweenness_centrality( 

gPrm, normalized=True, weight='weight') 

for nodeA, nodeB in util.combinations2(oris): 

try: 

w = bc[nodeA, nodeB] 

except KeyError: 

w = bc[nodeB, nodeA] 

gWeights.add_edge(nodeA, nodeB, weight=int(100 * (1 - w))) 

elif method in ['central_node', 'cn']: 

# get the weighted degrees for the primary graph 

degrees = gPrm.degree(weight='weight') 

max_deg = sorted(degrees, key=lambda x: degrees[x], reverse=True)[0] 

 

# add all nodes as simple 

for nodeA, nodeB in util.combinations2(oris): 

gWeights.add_edge( 

nodeA, nodeB, weight=0 if max_deg in [nodeA, nodeB] else 10) 

 

# if the graph is not empty 

if gWeights: 

# check for identical weights and change them according to tree-distance 

tmp_weights = defaultdict(list) 

for a, b, d in gWeights.edges(data=True): 

tmp_weights[int(d['weight'])].append((a, b)) 

 

if method in ['mr', 'majority_rule']: 

# check for identical weights and calculate the tree distance 

for w in tmp_weights: 

elist = tmp_weights[w] 

 

# check whether there are more identical weights 

if len(elist) > 1: 

# if so, order all stuff according to branch 

# length, we need try-except statement for 

# branchdistances here, since cogent does not 

# calculate distances to the root and back 

branches = [] 

for a, b in elist: 

try: 

branch_distance = len( 

self.tree.getConnectingEdges(a, b)) 

branches += [(a, b, branch_distance)] 

except: 

if 'root' in (a, b): 

branch_distance = len( 

self.tree.getConnectingEdges(b, a)) 

branches += [(a, b, branch_distance)] 

else: 

bdA = len(self.tree.getConnectingEdges('root', a)) 

bdB = len(self.tree.getConnectingEdges('root', b)) 

branches += [(a, b, bdA + bdB)] 

 

# now change the weights according to the order 

scaler = 1 / len(branches) 

minus = 1 - scaler 

branches = sorted( 

branches, key=lambda x: (x[2], x[1], x[0]), reverse=True) 

for a, b, d in branches: 

gWeights[a][b]['weight'] += minus 

minus -= scaler 

 

# change maximum weights to distance weights 

for a, b, d in sorted(gWeights.edges(data=True), 

key=lambda x: x[2]['weight']): 

w = d['weight'] 

gWeights[a][b]['weight'] = int(1000 / w) ** 2 

 

# calculate the MST 

mst = nx.minimum_spanning_tree(gWeights, weight='weight') 

 

# assign the MST-weights to gMST 

for nodeA, nodeB in mst.edges(): 

if gMST.has_edge(nodeA, nodeB): 

gMST[nodeA][nodeB]['weight'] += 1 

gMST[nodeA][nodeB]['cogs'] += [cog] 

else: 

gMST.add_edge(nodeA, nodeB, weight=1, cogs=[cog]) 

ile[cog] += [(nodeA, nodeB)] 

 

# load data for nodes into new graph 

for node, data in gTpl.nodes(data=True): 

if data['label'] in taxa: 

data['graphics']['fill'] = '#ff0000' 

data['graphics']['type'] = 'rectangle' 

data['graphics']['w'] = 80.0 

data['graphics']['h'] = 20.0 

else: 

data['graphics']['type'] = 'ellipse' 

data['graphics']['w'] = 30.0 

data['graphics']['h'] = 30.0 

data['graphics']['fill'] = '#ff0000' 

 

gOut.add_node(data['label'], **data) 

 

# load edge data into new graph 

for nodeA, nodeB, data in gTpl.edges(data=True): 

data['graphics']['width'] = 10.0 

data['graphics']['fill'] = '#000000' 

data['label'] = 'vertical' 

try: 

del data['graphics']['Line'] 

except: 

pass 

gOut.add_edge(gTpl.node[nodeA]['label'], gTpl.node[nodeB]['label'], **data) 

 

# assign new edge weights 

for nodeA, nodeB, data in gMST.edges(data=True): 

w = data['weight'] 

data['graphics'] = {} 

data['cogs'] = ','.join([text_type(i) for i in data['cogs']]) 

data['label'] = 'horizontal' 

 

if w >= threshold: 

if not gOut.has_edge(nodeA, nodeB): 

gOut.add_edge(nodeA, nodeB, **data) 

 

log.info("Writing graph to file...") 

self._write_file('mln-' + glm + '.gml', nx.generate_gml(gOut)) 

 

# write the inferred borrowing events (ILS, inferred lateral event) 

# between all taxa to file 

log.info("Writing Inferred Lateral Events to file...") 

 

with util.TextFile(self._output_path('ile-' + glm + '.csv')) as f: 

for cog, events in ile.items(): 

if events: 

f.write( 

text_type(cog) + '\t' + ','.join( 

['{0}:{1}'.format(a, b) for a, b in events] 

) + '\n') 

 

# create file name for node labels (cytoscape output) 

lines = ["node.label (class=java.lang.String)"] 

for taxon in taxa: 

lines.append('{0} = {1}'.format(taxon, taxon)) 

self._write_file('node.label.NA', lines) 

 

# add gOut to graphattributes 

self.graph[glm] = gOut 

 

# write stats to file 

# get the degree 

nodes = tree.getNodeNames() 

 

dgr, wdgr = [], [] 

for taxon in nodes: 

horizontals = [g for g in gOut[taxon] if 'weight' in gOut[taxon][g]] 

 

dgr.append(len(horizontals)) 

wdgr.append(sum([gOut[taxon][g]['weight'] for g in horizontals])) 

 

sorted_nodes = sorted(zip(nodes, dgr, wdgr), key=lambda x: x[1], reverse=True) 

lines = [] 

for n, d, w in sorted_nodes: 

lines.append(util.tabjoin(( 

n, text_type(tree.getNodeMatchingName(n)), d, w))) 

self._write_file('taxa-' + glm + '.stats', lines) 

 

log.info("Wrote node degree distributions to file.") 

 

# write edge distributions 

edges = [g for g in gOut.edges(data=True) if 'weight' in g[2]] 

 

lines = [] 

for nA, nB, d in sorted(edges, key=lambda x: x[2]['weight'], reverse=True): 

lines.append(util.tabjoin(( 

nA, 

nB, 

d['weight'], 

d['cogs'], 

tree.getNodeMatchingName(nA), 

tree.getNodeMatchingName(nB)))) 

self._write_file('edge-' + glm + '.stats', lines) 

log.info("Wrote edge-weight distributions to file.") 

 

for taxon in self.taxa: 

with util.TextFile( 

self._output_path(os.path.join('taxa-' + glm, taxon + '.csv')), log=False 

) as f: 

keys = [n for n in gOut[taxon] if gOut[taxon][n]['label'] == 'horizontal'] 

for key in sorted(keys, key=lambda x: gOut[taxon][x]['weight']): 

for cog in sorted(gOut[taxon][key]['cogs'].split(',')): 

tmp = [x for x in self.etd[cog] if x != 0] 

idx = [x[0] for x in tmp][0] 

concept = self[idx, 'concept'] 

proto = cog 

 

# get the index of the current entry in dictionary representation 

idx = self.get_dict(col=taxon, entry='pap')[concept] 

idx = idx.index(cog) 

 

# get its real index 

idx = self.get_dict(col=taxon)[concept][idx] 

 

# include entries specified in keywords XXX modify later 

# for customization 

for entry in ['ipa', 'proto']: 

if entry in self.header: 

proto += '\t' + self[idx, entry] 

 

f.write('{0}\t{1}\t{2}\n'.format(key, proto, concept)) 

log.info("Wrote list of edges per taxa to file.") 

return 

 

def get_PDC(self, glm, **keywords): 

""" 

Calculate Patchily Distributed Cognates. 

""" 

util.setdefaults(keywords, aligned_output=True) 

patchy = {} 

paps = [] 

 

for key, (gls, noo) in self.gls[glm].items(): 

# get the origins 

oris = sorted( 

[x[0] for x in gls if x[1] == 1], 

key=lambda x: len(self.tree.getNodeMatchingName(x).getTipNames())) 

 

# get the tip-taxa for each origin 

tips = [] 

losses = [a for a, b in zip(self.taxa, self.paps[key]) if b == 0] 

 

tipsofar = [] 

for i, ori in enumerate(oris): 

new_tips = [ 

i + 1, 

[t for t in self.tree.getNodeMatchingName(ori).getTipNames() 

if t not in losses and t not in tipsofar]] 

tipsofar += new_tips[1] 

tips += [tuple(new_tips)] 

 

# now, all set of origins with their tips are there, we store them 

# in the patchy dictionary, where each taxon is assigned the 

# numerical value of the given patchy dist 

patchy[key] = {} 

if len(tips) > 1: 

for i, tip in tips: 

for taxon in tip: 

patchy[key][taxon] = i 

else: 

for i, tip in tips: 

for taxon in tip: 

patchy[key][taxon] = 0 

 

paps.append((key, noo)) 

 

log.info("[i] Retrieved patchy distributions.") 

 

# get the index for the paps in the wordlist 

papIdx = self.header['pap'] 

taxIdx = self._colIdx 

 

# create a dictionary as updater for the wordlist 

updater = {} 

for key in self: 

taxon = self[key][taxIdx] 

pap = self[key][papIdx] 

 

try: 

updater[key] = '{0}:{1}'.format(pap, patchy[pap][taxon]) 

except KeyError: 

updater[key] = '{0}:{1}'.format(pap, 0) 

 

# update the wordlist 

self.add_entries('patchy', updater, util.identity, override=True) 

 

# write data to file 

# self.output('csv',filename=self.dataset+'_phybo/wl-'+glm) 

# XXX change later 

 

log.info("[i] Updated the wordlist.") 

 

# write ranking of concepts to file 

with util.TextFile(self._output_path('paps-' + glm + '.stats')) as f: 

if 'proto' in self.entries: 

f.write('COGID\tGLID\tCONCEPT\tORIGINS\tREFLEXES\tORIG/REFL\tPROTO\n') 

else: 

f.write('COGID\tGLID\tCONCEPT\tORIGINS\tREFLEXES\tORIG/REFL\n') 

concepts = defaultdict(list) 

for a, b in sorted(paps, key=lambda x: x[1], reverse=True): 

a1, a2 = a.split(':') 

a3 = self._id2gl[int(a2)] 

 

# check for number of occurrences 

l = [k for k in self.etd[a] if k != 0] 

 

# append three vals: number of origins, number of words, and the 

# number of origins per number of words 

concepts[a3].append((b, len(l), b / len(l))) 

 

# check for proto 

if 'proto' in self.entries: 

proto = self[[k[0] for k in l][0], 'proto'] 

f.write('{0}\t{1}\t{2}\t{3}\t{4}\t{5:.2f}\t{6}\n'.format( 

a1, a2, a3, b, len(l), b / float(len(l)), proto)) 

else: 

f.write('{0}\t{1}\t{2}\t{3}\t{4}\t{5:.2f}\n'.format( 

a1, a2, a3, b, len(l), float(b) / len(l))) 

log.info("Wrote stats on paps to file.") 

 

# write stats on concepts 

with util.TextFile(self._output_path('concepts-' + glm + '.stats')) as f: 

f.write('CONCEPT\tORIGINS\tREFLEXES\tORI/REF\n') 

 

cstats = {} 

for key in concepts: 

# get origins per concept 

oriperc = sum([c[0] for c in concepts[key]]) / len(concepts[key]) 

 

# get patchy cognate sets per number of words 

patchyperw = sum([c[2] for c in concepts[key]]) / len(concepts[key]) 

 

# get the number of words per concept 

numperc = sum([c[1] for c in concepts[key]]) / len(concepts[key]) 

 

cstats[key] = (oriperc, numperc, patchyperw) 

# concepts[key] = sum(concepts[key])/len(concepts[key]) 

 

for a, b in sorted(cstats.items(), key=lambda x: x[1][2], reverse=True): 

f.write('{0}\t{1:.2f}\t{2:.2f}\t{3:.2f}\n'.format(a, b[0], b[1], b[2])) 

 

# write average to file 

f.write('TOTAL\t{0:.2f}\t{1:.2f}\t{2:.2f}\n'.format( 

sum([cstats[c][0] for c in cstats]) / len(cstats), 

sum([cstats[c][1] for c in cstats]) / len(cstats), 

sum([cstats[c][2] for c in cstats]) / len(cstats) 

)) 

log.info("Wrote stats on concepts to file.") 

 

# write alternative stats on concepts including information of 

# singletons (excluding them may bias the results) 

with util.TextFile(self._output_path('cognates-' + glm + '.stats')) as f: 

f.write('CONCEPT\tCOGNATES\tPATCHIES\tREFLEXES\tPCR\n') 

 

concepts = defaultdict(list) 

for pap in self.etd: 

gloss = self.pap2con[pap] 

idxs = [idx[0] for idx in self.etd[pap] if idx != 0] 

patchies = [self[idx, 'patchy'] for idx in idxs] 

cogs = [self[idx, self._pap_string] for idx in idxs] 

reflexes = len(patchies) 

patchies = len(set(patchies)) 

cogs = len(set(cogs)) 

concepts[gloss].append((cogs, patchies, reflexes)) 

 

for key, value in concepts.items(): 

concepts[key] = ( 

sum([v[0] for v in value]), 

sum([v[1] for v in value]), 

sum([v[2] for v in value]) 

) 

 

for k, (c, p, r) in sorted( 

concepts.items(), key=lambda x: x[1][2], reverse=True): 

f.write( 

'{0}\t{1}\t{2}\t{3}\t{4:.2f}\n'.format(k, c, p, r, (p - c + 1) / r)) 

# write mean 

mc = sum([x[0] for x in concepts.values()]) / len(concepts) 

mp = sum([x[1] for x in concepts.values()]) / len(concepts) 

mr = sum([x[2] for x in concepts.values()]) / len(concepts) 

 

f.write('{0}\t{1:.2f}\t{2:.2f}\t{3:.2f}\t{4:.2f}\n'.format( 

"MEAN", mc, mp, mr, (mp - mc + 1) / mr)) 

 

log.info("Wrote stats on concepts to file.") 

 

# store params in attribute stats 

self.stats["CONCEPTS"] = dict( 

cognates=sum([x[0] for x in concepts.values()]) / self.height, 

patchies=sum([x[1] for x in concepts.values()]) / self.height, 

reflexes=sum([x[2] for x in concepts.values()]) / self.height, 

origins=sum([x[0] for x in cstats.values()]) / self.height, 

# reflexes = sum([x[1] for x in cstats.values()]) / self.height, 

patchy_per_reflex=sum([x[2] for x in cstats.values()]) / self.height) 

 

# write results to alm-file 

# get all patchy cognates 

tmp = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) 

for key in self: 

patchy = self[key, 'patchy'] 

if not patchy.endswith('0'): 

concept = self[key, 'concept'] 

taxon = self[key, 'doculect'] 

pap = self[key, 'pap'] 

 

# XXX change this later for more flexibility XXX 

word = self[key, 'ipa'] if 'ipa' in self.header \ 

else self[key, 'counterpart'] 

if not word: 

raise NameError("[ERROR] Neither 'ipa' nor 'counterpart' is defined.") 

tmp[concept][pap][patchy].append((taxon, word)) 

 

if keywords["aligned_output"]: 

# write stuff to alm-file 

with util.TextFile( 

self._output_path(self.dataset + '-' + glm + '.alm.patchy'), log=False 

) as f: 

for concept in sorted(tmp.keys()): 

f.write('# Basic Concept: "{0}"\n\n'.format(concept)) 

 

for pap in sorted(tmp[concept].keys()): 

f.write('## Cognate-Set: "{0}"\n'.format(pap)) 

 

words = [] 

langs = [] 

patchies = [] 

 

for patchy in sorted(tmp[concept][pap].keys()): 

# get words and languages 

words += [t[1].replace("ˈ", '') for t in 

tmp[concept][pap][patchy]] 

langs += [t[0] for t in tmp[concept][pap][patchy]] 

 

patchies += [patchy[-1] for i in 

range(len(tmp[concept][pap][patchy]))] 

 

msa = Multiple(words) 

# XXX add for different alignment algorithm later XXX 

msa.prog_align() 

alms = msa.alm_matrix 

 

# get formatter for languages 

formatter = max([len(lang) for lang in langs]) 

 

for i, word in enumerate(words): 

string = '{0:' + text_type( 

formatter) + '}\t{1}\t|\t{2}\t|\t[{3}]\n' 

f.write(string.format( 

langs[i], patchies[i], '\t'.join(alms[i]), word)) 

f.write('\n') 

f.write('\n') 

 

def get_edge(self, glm, nodeA, nodeB, entries='', msn=False): 

""" 

Return the edge data for a given gain-loss model. 

""" 

# define a warning message 

warning = "No edge between {0} and {1} could be found".format(nodeA, nodeB) 

# check for entryB 

if isinstance(entries, text_type): 

entries = entries.split(',') 

 

# get the graph locally for convenience 

graph = self.geograph[glm] if msn else self.graph[glm] 

 

if not graph.has_edge(nodeA, nodeB): 

log.info(warning) 

return 

 

edge = graph[nodeA][nodeB] 

if not msn: 

if edge['label'] == 'horizontal': 

cogs = edge['cogs'].split(',') 

else: 

log.info(warning) 

return 

else: 

cogs = edge['cogs'].split(',') 

 

# check whether nodes are in list or not 

if nodeA in self.taxa: 

nodesA = [nodeA] 

else: 

nodesA = self.tree.getNodeMatchingName(nodeA).getTipNames() 

if nodeB in self.taxa: 

nodesB = [nodeB] 

else: 

nodesB = self.tree.getNodeMatchingName(nodeB).getTipNames() 

 

def assemble_output(nodes): 

out = defaultdict(list) 

for node in nodes: 

tmp = dict(zip( 

self.get_list(col=node, flat=True, entry='pap'), 

self.get_list(col=node, flat=True))) 

for cog in cogs: 

vals = [node] 

for entry in entries: 

try: 

vals += [self[tmp[cog], entry]] 

except: 

pass 

if len(vals) > 1: 

out[cog].append(tuple(vals)) 

return out 

 

outA = assemble_output(nodesA) 

outB = assemble_output(nodesB) 

 

output = [] 

for cog in cogs: 

try: 

output += [(self.pap2con[cog], outA[cog], outB[cog])] 

except: 

self.log.error( 

"Error encountered in cognate {0}.".format(self.pap2con[cog])) 

return output 

 

def analyze( 

self, 

runs="default", 

mixed=False, 

output_gml=False, 

tar=False, 

full_analysis=True, 

plot_dists=False, 

output_plot=False, 

plot_mln=False, 

plot_msn=False, 

**keywords 

): 

""" 

Carry out a full analysis using various parameters. 

 

Parameters 

---------- 

runs : {str list} (default="default") 

Define a couple of different models to be analyzed. Select between: 

 

* 'default': weighted analysis, using parsimony and weights for 

gains and losses 

* 'topdown': use the traditional approach by 

:evobib:`Nelson-Sathi2011` 

* 'restriction': use the restriction approach 

 

You can also define your own mix of models. 

 

usetex : bool (default=True) 

Specify whether you want to use LaTeX to render plots. 

mixed : bool (default=False) 

If set to c{True}, calculate a mixed model by selecting the best 

model for each item separately. 

output_gml : bool (default=False) 

Set to c{True} in order to output every gain-loss-scenario in 

GML-format. 

full_analysis : bool (default=True) 

Specifies whether a full analysis is carried out or not. 

plot_mln : bool (default=True) 

Select or unselect output plot for the MLN. 

plot_msn : bool (default=False) 

Select or unselect output plot for the MSN. 

 

""" 

util.setdefaults( 

keywords, 

colorbar=None, # mpl.cm.jet, 

threshold=1, 

fileformat=rcParams['phybo_fileformat'], 

usetex=False, 

only=[], 

colormap=None, # mpl.cm.jet 

proto=False, 

xticksize=6, 

method='mr', # majority rule 

gpl=1, 

push_gains=True, 

missing_data=0, 

aligned_output=False, 

homoplasy=0.05, 

evaluation='mwu') 

 

# define a default set of runs 

if runs in ['default', 'weighted']: 

runs = [('weighted', (3, 1)), 

('weighted', (5, 2)), 

('weighted', (2, 1)), 

('weighted', (3, 2)), 

('weighted', (1, 1))] 

elif runs in ['topdown', 'top-down']: 

runs = [('topdown', 2), 

('topdown', 3), 

('topdown', 4), 

('topdown', 5), 

('topdown', 6), 

('topdown', 7), 

('topdown', 8), 

('topdown', 9), 

('topdown', 10)] 

elif runs == 'restriction': 

runs = [('restriction', 2), 

('restriction', 3), 

('restriction', 4), 

('restriction', 5), 

('restriction', 6)] 

 

for mode, params in runs: 

log.info( 

"Analysing dataset with mode {0} and params {1}...".format(mode, params)) 

kw = dict( 

mode=mode, 

output_gml=output_gml, 

tar=tar, 

output_plot=output_plot, 

missing_data=keywords["missing_data"]) 

if mode == 'weighted': 

kw.update( 

gpl=keywords['gpl'], 

push_gains=keywords['push_gains'], 

ratio=params) 

elif mode == 'restriction': 

kw.update( 

gpl=keywords['gpl'], 

push_gains=keywords['push_gains'], 

restriction=params) 

elif mode == 'topdown': 

kw.update(restriction=params) 

self.get_GLS(**kw) 

 

# calculate the different distributions 

# start by calculating the contemporary distributions 

log.info("Calculating the Contemporary Vocabulary Distributions...") 

self.get_CVSD() 

 

# now calculate the rest of the distributions 

log.info("Calculating the Ancestral Vocabulary Distributions...") 

 

modes = list(self.gls.keys()) 

for m in util.pb(modes, desc='ANCESTRAL VOCABULARY DISTRIBUTIONS'): 

self.get_AVSD(m, **keywords) 

 

# compare the distributions using mannwhitneyu 

log.info("Comparing the distributions...") 

 

zp_vsd = [] 

for m in modes: 

vsd = sp.stats.mstats.kruskalwallis( # sp.stats.mannwhitneyu( 

self.dists['contemporary'], self.dists[m]) 

zp_vsd.append((vsd[0], vsd[1])) 

 

# determine the best model 

p_vsd = [p for z, p in zp_vsd] 

maxP = max(p_vsd) 

glm = modes[p_vsd.index(maxP)] 

 

# make a hash for all ps for all models 

self._pvalues = dict(zip(modes, p_vsd)) 

 

# set the best model 

self.best_model = glm 

 

# calculate mixed model 

if mixed: 

log.info("Calculating the mixed model...") 

self.get_IVSD( 

output_plot=output_plot, 

output_gml=output_gml, 

tar=tar, 

leading_model=glm, 

**keywords 

) 

 

# set the mixed model as the best one 

self.best_model = 'mixed' 

 

if 'mixed' not in modes: 

modes += ['mixed'] 

vsd = sp.stats.mstats.kruskalwallis( # sp.stats.mannwhitneyu( 

self.dists['contemporary'], self.dists['mixed']) 

zp_vsd.append((vsd[0], vsd[1])) 

 

# write results to file 

log.info("Writing stats to file.") 

with util.TextFile(self._output_path(self.dataset + '.stats')) as f: 

f.write("Mode\tANO\tMNO\tVSD_z\tVSD_p\n") 

for i in range(len(zp_vsd)): 

f.write( 

'{0}\t{1:.2f}\t{2}\t{3}\n'.format( 

modes[i], 

self.stats[modes[i]]['ano'], 

self.stats[modes[i]]['mno'], 

'{0[0]}\t{0[1]:.4f}'.format(zp_vsd[i]) 

) 

) 

 

# plot the stats if this is defined in the settings 

if plot_dists: 

log.info("Plotting distributions.") 

# specify latex 

mpl.rc('text', usetex=keywords['usetex']) 

 

# store distributions in lists 

dists_vsd = [self.dists[m] for m in modes] 

 

# store contemporary dists 

dist_vsd = self.dists['contemporary'] 

 

# get the average number of origins 

ano = [self.stats[m]['ano'] for m in modes] 

 

# create a sorter for the distributions 

sorter = [ 

s[0] for s in sorted(zip(range(len(modes)), ano), key=lambda x: x[1])] 

 

# sort the stuff 

dists_vsd = [dists_vsd[i] for i in sorter] 

modes = [modes[i] for i in sorter] 

mode_strings = [m for m in modes] 

 

# sort the zp-values 

zp_vsd = [zp_vsd[i] for i in sorter] 

 

# format the zp-values 

p_vsd = [] 

if keywords['usetex']: 

for i, (z, p) in enumerate(zp_vsd): 

if p < 0.001: 

p_vsd.append('p$<${0:.2f}'.format(p)) 

elif p >= 0.05: 

p_vsd.append(r'\textbf{{p$=${0:.2f}}}'.format(p)) 

 

# adjust the modes 

mode_strings[i] = r'\textbf{' + modes[i] + '}' 

else: 

p_vsd.append('p$=${0:.2f}'.format(p)) 

else: 

for z, p in zp_vsd: 

if p < 0.001: 

p_vsd.append('p<{0:.2f}'.format(p)) 

elif p >= 0.05: 

p_vsd.append(r'p={0:.2f}'.format(p)) 

else: 

p_vsd.append('p={0:.2f}'.format(p)) 

 

fig = plt.figure() 

ax = fig.add_subplot(111) 

b = ax.boxplot([dist_vsd] + dists_vsd) 

plt.setp(b['medians'], color='black') 

plt.setp(b['whiskers'], color='black') 

plt.setp(b['boxes'], color='black') 

for tick in ax.yaxis.get_major_ticks(): 

tick.label.set_fontsize(18) 

 

plt.xticks( 

range(1, len(modes) + 2), 

[''] + ['{0}\n{1}'.format(m, p) for m, p in zip(mode_strings, p_vsd)], 

size=keywords['xticksize'], 

rotation=45, 

ha='center') 

 

ax.yaxis.grid( 

True, 

linestyle='-', 

which='major', 

color='lightgrey', 

alpha=0.5, 

zorder=1) 

 

plt.subplots_adjust(bottom=0.2) 

plt.savefig(self._output_path('vsd.' + keywords['fileformat'])) 

plt.clf() 

log.info("Plotted the distributions.") 

 

if full_analysis: 

self.get_MLN( 

self.best_model, 

threshold=keywords['threshold'], 

method=keywords['method']) 

 

if plot_mln: 

self.plot_MLN( 

self.best_model, 

filename=self._output_path('mln-' + glm), 

threshold=keywords['threshold'], 

fileformat=keywords['fileformat'], 

usetex=keywords['usetex'], 

colormap=keywords['colormap'] 

) 

if plot_msn: 

self.plot_MSN( 

self.best_model, 

filename=self._output_path('msn-' + glm), 

fileformat=keywords['fileformat'], 

threshold=keywords['threshold'], 

only=keywords['only'], 

usetex=keywords['usetex'], 

colormap=keywords['colormap'] 

) 

 

self.get_PDC(self.best_model, **keywords) 

 

def plot_MLN( 

self, 

glm='', 

fileformat='pdf', 

threshold=1, 

usetex=False, 

taxon_labels='taxon_short_labels', 

alphat=False, 

alpha=0.75, 

**keywords 

): 

""" 

Plot the MLN with help of Matplotlib. 

 

glm : str (default='') 

Identifier for the gain-loss model that is plotted. Defaults to the 

model that had the best scores in terms of probability. 

filename : str (default='') 

If no filename is selected, the filename is identical with the 

dataset. 

fileformat : {'svg','png','jpg','pdf'} (default='pdf') 

Select the format of the output plot. 

threshold : int (default=1) 

Select the threshold for drawing lateral edges. 

usetex : bool (default=True) 

Specify whether you want to use LaTeX to render plots. 

colormap : {None matplotlib.cm} 

A :py:class:`matplotlib.colormap` instance. If set to c{None}, this 

defaults to :py:class:`~matplotlib.cm.jet`. 

taxon_labels : str (default='taxon.short_labels') 

Specify the taxon labels that should be included in the plot. 

 

""" 

# check for correct glm 

if not glm and hasattr(self, 'best_model'): 

glm = self.best_model 

elif not glm: 

raise ValueError("[i] You should select an appropriate model first.") 

 

# switch backend, depending on whether tex is used or not 

backend = mpl.get_backend() 

if usetex and backend != 'pgf': 

plt.switch_backend('pgf') 

mpl.rcParams['text.latex.unicode'] = True 

elif not usetex and backend != 'TkAgg': 

plt.switch_backend('TkAgg') 

 

util.setdefaults( 

keywords, 

figsize="optimal", # rcParams['phybo_figsize'], 

figure_width=10, 

figure_scale=1, 

colormap=mpl.cm.jet, 

filename=self.dataset, 

linescale=rcParams['phybo_linescale'], 

maxweight=rcParams['phybo_maxweight'], 

xlim=rcParams['phybo_xlim'], 

ylim=rcParams['phybo_ylim'], 

xlimr=rcParams['phybo_xlimr'], 

xliml=rcParams['phybo_xliml'], 

ylimt=rcParams['phybo_ylimt'], 

ylimb=rcParams['phybo_ylimb'], 

left=rcParams['phybo_left'], 

right=rcParams['phybo_right'], 

top=rcParams['phybo_top'], 

bottom=rcParams['phybo_bottom'], 

cbar_shrink=rcParams['phybo_cbar_shrink'], 

cbar_fraction=rcParams['phybo_cbar_fraction'], 

cbar_pad=rcParams['phybo_cbar_pad'], 

cbar_orientation=rcParams['phybo_cbar_orientation'], 

cbar_label=rcParams['phybo_cbar_label'], 

vedgestyle=rcParams['phybo_vedgestyle'], 

vedgecolor=rcParams['phybo_vedgecolor'], 

vedgelinewidth=rcParams['phybo_vedgelinewidth'], 

vedgeinnerline=rcParams['phybo_vedgeinnerline'], 

hedgescale=rcParams['phybo_hedgescale'], 

nodestyle=rcParams['phybo_nodestyle'], 

nodesize=rcParams['phybo_nodesize'], 

nodecolor=rcParams['phybo_nodecolor'], 

labels=rcParams['phybo_labels'], 

_prefix=rcParams['phybo_prefix'], 

_suffix=rcParams['phybo_suffix'], 

textsize=rcParams['phybo_textsize'], 

vsd_scale=rcParams['phybo_vsd_scale'], 

latex_preamble=rcParams['phybo_latex_preamble'], 

alpha_threshold=0.2) 

 

# get max and min values for coordinates 

xvals, yvals = [], [] 

for n, d in self.graph[glm].nodes(data=True): 

xvals += [d['graphics']['x']] 

yvals += [d['graphics']['y']] 

 

minX, minY, maxX, maxY = min(xvals), min(yvals), max(xvals), max(yvals) 

if keywords['figsize'] == 'optimal': 

w = maxX + abs(minX) 

h = maxY + abs(minY) 

keywords['figsize'] = ( 

keywords['figure_width'] + keywords['figure_scale'], 

h / (w / (keywords['figure_width']))) 

 

if keywords['latex_preamble']: 

mpl.rcParams['pgf.preamble'] = keywords['latex_preamble'] 

 

colormap = keywords['colormap'] 

filename = keywords['filename'] 

labels = {taxon: keywords['labels'].get(taxon, taxon) for taxon in self.taxa} 

node_dict = {} 

 

for taxon in self.taxa: 

cogs = [x for x in 

self.get_list(col=taxon, flat=True, entry='pap') if x in self.cogs] 

# count the number of paps 

node_dict[taxon] = len(cogs) * keywords['vsd_scale'] 

 

for a, b in [(x, y) for x, y in self.tree.getNodesDict().items() if 

x not in self.taxa]: 

node = a if a != 'root' else 'root' 

if node in self.acs[glm]: 

node_dict[a] = len(self.acs[glm][node]) * keywords['vsd_scale'] 

else: 

node_dict[a] = 1 * keywords['vsd_scale'] 

 

graph = self.graph[glm] 

 

# store in internal and external nodes 

inodes = [] 

enodes = [] 

 

# get colormap for edgeweights 

edge_weights = [d['weight'] for _, _, d in 

graph.edges(data=True) if d['label'] == 'horizontal'] 

 

# add max weight to edge_weights 

if keywords['maxweight']: 

edge_weights += range(keywords['maxweight']) 

 

# determine a colorfunction 

cfunc = np.array(np.linspace(10, 256, len(set(edge_weights))), dtype='int') 

 

weights = sorted(set(edge_weights)) 

 

# get the scale for the weights (needed for the line-width) 

try: 

scale = 20.0 / max(edge_weights) * keywords['linescale'] 

except ValueError: 

scale = 1.0 

 

# write colors and scale to graph 

for nA, nB, data in graph.edges(data=True): 

if data['label'] == 'horizontal': 

w = data['weight'] 

data['graphics'] = {} 

data['graphics']['fill'] = mpl.colors.rgb2hex( 

colormap(cfunc[weights.index(w)])) 

data['graphics']['width'] = scale * w 

 

# get the nodes 

for n, d in graph.nodes(data=True): 

g = d['graphics'] 

ns = keywords['nodesize'] 

if keywords['nodestyle'] == 'vsd': 

ns = node_dict.get(n, ns) 

 

if d['label'] not in self.taxa: 

inodes += [(g['x'], g['y'], ns)] 

else: 

enodes += [(g['x'], g['y'], d['label'], g.get('angle', 0), g['s'], ns)] 

 

# store vertical and lateral edges 

vedges, ledges, weights = [], [], [] 

 

for a, b, d in graph.edges(data=True): 

xA = graph.node[a]['graphics']['x'] 

yA = graph.node[a]['graphics']['y'] 

xB = graph.node[b]['graphics']['x'] 

yB = graph.node[b]['graphics']['y'] 

 

if d['label'] == 'vertical': 

vedges += [(xA, xB, yA, yB)] 

else: 

g = d['graphics'] 

w = g['width'] 

a = alpha 

if d['weight'] < threshold: 

if alphat: 

a = keywords['alpha_threshold'] 

else: 

w = 0.0 

 

ledges += [(xA, xB, yA, yB, g['fill'], w, a)] 

weights.append(d['weight']) 

 

weights = weights or [0] 

mpl.rc('text', usetex=usetex) 

 

fig = plt.figure(facecolor='white', figsize=keywords['figsize']) 

figsp = fig.add_subplot(111) 

 

plt.axes(frameon=False) 

plt.xticks([0], ['']) 

plt.yticks([0], ['']) 

plt.axis('equal') 

 

# draw the horizontal edges 

for xA, xB, yA, yB, f, w, a in sorted(ledges, key=lambda x: x[-2]): 

plt.plot( 

[xA, xB], 

[yA, yB], 

'-', 

color=f, 

linewidth=float(w) / keywords['hedgescale'], 

alpha=a) 

 

# draw the vertical edges 

for xA, xB, yA, yB in vedges: 

plt.plot( 

[xA, xB], 

[yA, yB], 

'-', 

color=keywords['vedgecolor'], 

linewidth=keywords['vedgelinewidth']) 

if keywords['vedgestyle'] == 'double': 

plt.plot( 

[xA, xB], 

[yA, yB], 

'-', 

color='1.0', 

linewidth=keywords['vedgeinnerline']) 

# store x,y values for ylim,xlim drawing 

xvals, yvals = [], [] 

 

for x, y, s in inodes: 

xvals += [x] 

yvals += [y] 

 

plt.plot(x, y, 'o', markersize=s, color=keywords['nodecolor']) 

if keywords['nodestyle'] == 'double': 

plt.plot(x, y, 'o', markersize=s, color='white') 

 

for x, y, t, r, ha, s in enodes: 

xvals += [x] 

yvals += [y] 

 

plt.plot( 

x, 

y, 

'o', 

markersize=s, # keywords['nodesize'], 

color=keywords['nodecolor'], 

zorder=200) 

 

if keywords['nodestyle'] == 'double': 

plt.plot(x, y, 'o', markersize=s, color='white') 

 

# this is a workaround to get the text away from the node 

if ha == 'left': 

text = keywords['_prefix'] + labels[t] 

else: 

text = labels[t] + keywords['_suffix'] 

 

plt.text( 

x, 

y, 

text, 

size=keywords['textsize'], 

verticalalignment='center', 

horizontalalignment=ha, 

fontweight='bold', 

color='black', 

rotation=r, 

rotation_mode='anchor', 

zorder=1) 

 

cbar = fig.colorbar( 

figsp.imshow([[1, 2], [1, 2]], cmap=colormap, visible=False), 

ticks=[1, 1.25, 1.5, 1.75, 2], 

orientation=keywords['cbar_orientation'], 

shrink=keywords['cbar_shrink'], 

fraction=keywords['cbar_fraction'], 

pad=keywords['cbar_pad']) 

 

# check for maxweights-keyword 

if keywords['maxweight']: 

weights += [keywords['maxweight']] 

 

cbar.set_clim(1.0) 

cbar.set_label('Inferred Links') 

cbar.ax.set_yticklabels([ 

text_type(min(weights)), 

'', 

text_type(int(max(weights) / 2)), 

'', 

text_type(max(weights))]) 

 

if keywords['xliml'] and keywords['xlimr']: 

xliml = keywords['xliml'] 

xlimr = keywords['xlimr'] 

else: 

xliml, xlimr = 2 * [keywords['xlim']] 

 

if keywords['ylimb'] and keywords['ylimt']: 

ylimb = keywords['ylimb'] 

ylimt = keywords['ylimt'] 

else: 

ylimb, ylimt = 2 * [keywords['ylim']] 

 

plt.ylim(min(yvals) - ylimb, max(yvals) + ylimt) 

plt.xlim(min(xvals) - xliml, max(xvals) + xlimr) 

plt.subplots_adjust( 

left=keywords['left'], 

right=keywords['right'], 

top=keywords['top'], 

bottom=keywords['bottom'] 

) 

# fig.axes.get_xaxis().set_visible(False) 

# fig.axes.get_yaxis().set_visible(False) 

plt.axis('off') 

 

# save the figure 

plt.savefig(filename + '.' + fileformat) 

plt.clf() 

log.file_written(filename + '.' + fileformat) 

return 

 

def plot_MLN_3d( 

self, 

glm='', 

filename='', 

fileformat='pdf', 

threshold=1, 

usetex=True, 

colormap=None, # mpl.cm.jet, 

taxon_labels='taxon_short_labels', 

alphat=False, 

alpha=0.75, 

**keywords 

): 

""" 

Plot the MLN with help of Matplotlib in 3d. 

 

glm : str (default='') 

Identifier for the gain-loss model that is plotted. Defaults to the 

model that had the best scores in terms of probability. 

filename : str (default='') 

If no filename is selected, the filename is identical with the 

dataset. 

fileformat : {'svg','png','jpg','pdf'} (default='pdf') 

Select the format of the output plot. 

threshold : int (default=1) 

Select the threshold for drawing lateral edges. 

usetex : bool (default=True) 

Specify whether you want to use LaTeX to render plots. 

colormap : {None matplotlib.cm} 

A :py:class:`matplotlib.colormap` instance. If set to c{None}, this 

defaults to :py:class:`~matplotlib.cm.jet`. 

taxon_labels : str (default='taxon.short_labels') 

Specify the taxon labels that should be included in the plot. 

 

""" 

kw = dict(azim=220, elev=22) 

kw.update(keywords) 

 

# check for correct glm 

if not glm and hasattr(self, 'best_model'): 

glm = self.best_model 

elif not glm: 

raise ValueError("[i] You should select an appropriate model first.") 

 

# switch backend, depending on whether tex is used or not 

backend = mpl.get_backend() 

if usetex and backend != 'pgf': 

plt.switch_backend('pgf') 

mpl.rcParams['text.latex.unicode'] = True 

 

elif not usetex and backend != 'TkAgg': 

plt.switch_backend('TkAgg') 

 

if not filename: 

filename = self.dataset 

 

if not colormap: 

colormap = mpl.cm.jet 

 

# set default, XXX change later 

if 'height' not in keywords: 

keywords['height'] = 7 

if 'width' not in keywords: 

keywords['width'] = 10 

 

# try to load the configuration file 

conf = self._config() 

 

# check for 'taxon.labels' in conf 

if taxon_labels in conf: # XXX change later 

tfunc = lambda x: conf[taxon_labels][x] 

else: 

tfunc = lambda x: x 

 

# get the graph 

graph = self.graph[glm] 

 

# store in internal and external nodes 

inodes = [] 

enodes = [] 

 

# get colormap for edgeweights 

edge_weights = [d['weight'] for _, _, d in 

graph.edges(data=True) if d['label'] == 'horizontal'] 

 

# determine a colorfunction 

cfunc = np.array(np.linspace(10, 256, len(set(edge_weights))), dtype='int') 

 

# sort the weights 

weights = sorted(set(edge_weights)) 

 

# get the scale for the weights (needed for the line-width) 

scale = 20.0 / max(edge_weights) 

 

# write colors and scale to graph 

for nA, nB, data in graph.edges(data=True): 

if data['label'] == 'horizontal': 

w = data['weight'] 

data['graphics'] = {} 

data['graphics']['fill'] = mpl.colors.rgb2hex( 

colormap(cfunc[weights.index(w)])) 

data['graphics']['width'] = scale * w 

 

# get the nodes 

for n, d in graph.nodes(data=True): 

g = d['graphics'] 

if d['label'] not in self.taxa: 

inodes += [(g['x'], g['y'], -g['z'], g['zorder'])] 

else: 

if usetex: 

label = r'\textbf{' + tfunc(d['label']).replace('_', r'\_') + r'}' 

else: 

label = tfunc(d['label']) 

enodes.append(( 

g['x'], 

g['y'], 

-g['z'], 

label, 

d['graphics'].get('angle', 0), 

g['s'], 

g['zorder'] 

)) 

 

# store vertical and lateral edges 

vedges = [] 

ledges = [] 

weights = [] 

 

# get the edges 

for a, b, d in graph.edges(data=True): 

xA = graph.node[a]['graphics']['x'] 

yA = graph.node[a]['graphics']['y'] 

zA = graph.node[a]['graphics']['z'] 

xB = graph.node[b]['graphics']['x'] 

yB = graph.node[b]['graphics']['y'] 

zB = graph.node[b]['graphics']['z'] 

zoA = graph.node[a]['graphics']['zorder'] 

zoB = graph.node[b]['graphics']['zorder'] 

zorder = int((zoA + zoB) / 2) 

 

if d['label'] == 'vertical': 

vedges += [(xA, xB, yA, yB, -zA, -zB, zorder)] 

else: 

g = d['graphics'] 

w = g['width'] 

a = alpha 

if d['weight'] < threshold: 

if alphat: 

a = 0.2 

else: 

w = 0.0 

 

ledges += [(xA, xB, yA, yB, -zA, -zB, zorder, g['fill'], w, a)] 

weights.append(d['weight']) 

 

mpl.rc('text', usetex=usetex) 

fig = plt.figure(facecolor='white', figsize=(keywords['width'], keywords['height'])) 

figsp = fig.add_subplot(111, projection='3d') 

 

# draw the horizontal edges 

for xA, xB, yA, yB, zA, zB, zorder, f, w, a in sorted( 

ledges, key=lambda x: x[-2]): 

figsp.plot( 

[xA, xB], 

[yA, yB], 

[zA, zB], 

color=f, 

linewidth=float(w) / 4, 

alpha=a, 

zorder=zorder # 100 # * abs(xA-xB) + 100 * abs(yA-yB) 

) 

 

# draw the vertical edges 

for xA, xB, yA, yB, zA, zB, zorder in vedges: 

figsp.plot( 

[xA, xB], 

[yA, yB], 

[zA, zB], 

color='0.0', 

linewidth=3, 

alpha=0.75, 

zorder=zorder # 100 * abs(xA-xB) + 100 * abs(yA-yB) 

) 

# store x,y values for ylim,xlim drawing 

xvals = [] 

yvals = [] 

zvals = [] 

 

# draw the nodes 

for x, y, z, zorder in inodes: 

xvals += [x] 

yvals += [y] 

zvals += [z] 

figsp.scatter(x, y, z, marker='o', s=20, c='black', zorder=zorder) 

 

# draw the leaves, store x and y-maxima for ylim, xlim drawing 

for x, y, z, t, r, ha, zorder in enodes: 

xvals += [x] 

yvals += [y] 

zvals += [z] 

 

figsp.text( 

x, 

y, 

z, 

t, 

size='5', 

verticalalignment='center', 

horizontalalignment='center', 

bbox=dict( 

facecolor='white', 

boxstyle='square,pad=0.2', 

ec="none", 

# alpha = 0.25 

), 

fontweight='bold', 

color='black', 

zorder=zorder + 200 # 120 # * x + 100 * y 

) 

 

figsp.view_init(azim=kw['azim'], elev=kw['elev']) 

figsp.set_ylim(min(yvals), max(yvals)) 

figsp.set_xlim(min(xvals), max(xvals)) 

figsp.set_zlim(min(zvals), max(zvals)) 

figsp.set_axis_off() 

plt.savefig(filename + '.' + fileformat, bbbox_inches='tight') 

plt.clf() 

 

def get_MSN(self, glm='', external_edges=False, deep_nodes=False, **keywords): 

""" 

Plot the Minimal Spatial Network. 

 

Parameters 

---------- 

glm : str (default='') 

A string that encodes which model should be plotted. 

filename : str 

The name of the file to which the plot shall be written. 

fileformat : str 

The output format of the plot. 

threshold : int (default=1) 

The threshold for the minimal amount of shared links that shall be 

plotted. 

usetex : bool (default=True) 

Specify whether LaTeX shall be used for the plot. 

 

""" 

# check for correct glm 

if not glm and hasattr(self, 'best_model'): 

glm = self.best_model 

elif not glm: 

raise ValueError("[i] You should select an appropriate model first.") 

 

# redefine taxa and tree for convenience 

taxa, tree = self.taxa, self.tree 

 

graph = self.graph[glm] 

 

# XXX check for coordinates of the taxa, otherwise load them from file and 

# add them to the wordlist XXX add later, we first load it from file 

if 'coords' in self._meta: 

coords = self._meta['coords'] 

else: 

coords = csv2dict(self.dataset, 'coords', dtype=[str, float, float]) 

 

# calculate all resulting edges, using convex hull as approximation 

geoGraph = nx.Graph() 

for node, data in graph.nodes(data=True): 

geoGraph.add_node(node, **data) 

 

edges = list(graph.edges(data=True)) 

for nA, nB, d in util.pb(edges, desc='MINIMAL SPATIAL NETWORK'): 

# get the labels 

lA = graph.node[nA]['label'] 

lB = graph.node[nB]['label'] 

 

# first check, whether edge is horizontal 

if d['label'] == 'horizontal': 

# if both labels occur in taxa, it is simple 

if lA in taxa and lB in taxa: 

try: 

geoGraph[lA][lB]['weight'] += d['weight'] 

geoGraph[lA][lB]['cogs'] += ',' + d['cogs'] 

except: 

geoGraph.add_edge(lA, lB, weight=d['weight'], cogs=d['cogs']) 

elif not external_edges: 

# if only one in taxa, we need the convex hull for that node 

if lA in taxa or lB in taxa: 

# check which node is in taxa 

if lA in taxa: 

this_label = lA 

other_nodes = tree.getNodeMatchingName(lB).getTipNames() 

elif lB in taxa: 

this_label = lB 

other_nodes = tree.getNodeMatchingName(lA).getTipNames() 

 

for cog in d['cogs'].split(','): 

# check whether the nodes have the respective cognate 

# and take only those that have it 

new_other_nodes = [] 

for other_node in other_nodes: 

paps = self.get_list( 

col=other_node, entry='pap', flat=True) 

if cog in paps and other_node != this_label: 

new_other_nodes += [other_node] 

 

# get the convex points of others 

these_coords = [ 

(round(coords[t][0], 5), round(coords[t][1], 5)) 

for t in new_other_nodes] 

hulls = getConvexHull(these_coords, polygon=False) 

 

# get the hull with the minimal euclidean distance 

distances = [] 

for hull in hulls: 

distances.append(np.linalg.norm( 

np.array(hull) - np.array(coords[this_label]))) 

this_hull = hulls[distances.index(min(distances))] 

other_label = new_other_nodes[these_coords.index( 

(round(this_hull[0], 5), round(this_hull[1], 5)))] 

 

# append the edge to the graph 

try: 

geoGraph[this_label][other_label]['weight'] += 1 

geoGraph[this_label][other_label]['cogs'] \ 

+= ',' + cog 

except: 

geoGraph.add_edge(this_label, other_label, weight=1, 

cogs=cog) 

 

elif deep_nodes: 

taxA = tree.getNodeMatchingName(lA).getTipNames() 

taxB = tree.getNodeMatchingName(lB).getTipNames() 

 

for cog in d['cogs'].split(','): 

newtaxA = [] 

newtaxB = [] 

 

for t in taxA: 

paps = self.get_list(col=t, entry='pap', flat=False) 

if cog in paps: 

newtaxA += [t] 

for t in taxB: 

paps = self.get_list(col=t, entry='pap', flat=False) 

if cog in paps: 

newtaxB += [t] 

 

# get the convex points 

coordsA = [ 

(round(coords[t][0], 5), round(coords[t][1], 5)) for t 

in newtaxA] 

coordsB = [ 

(round(coords[t][0], 5), round(coords[t][1], 5)) for t 

in newtaxB] 

hullsA = getConvexHull(coordsA, polygon=False) 

hullsB = getConvexHull(coordsB, polygon=False) 

 

distances = [] 

hulls = [] 

for hullA, hullB in itertools.product(hullsA, hullsB): 

distances.append(np.linalg.norm( 

np.array(hullA) - np.array(hullB))) 

hulls.append((hullA, hullB)) 

minHulls = hulls[distances.index(min(distances))] 

 

labelA = newtaxA[coordsA.index( 

(round(minHulls[0][0], 5), round(minHulls[0][1], 5)))] 

labelB = newtaxB[coordsB.index( 

(round(minHulls[1][0], 5), round(minHulls[1][1], 5)))] 

 

# append the edge to the graph 

try: 

geoGraph[labelA][labelB]['weight'] += 1 

geoGraph[labelA][labelB]['cogs'] += ',' + cog 

except: 

geoGraph.add_edge(labelA, labelB, weight=1, cogs=cog) 

 

# write stats to file 

with util.TextFile(self._output_path('taxa-msn-' + glm + '.stats')) as f: 

# get the degree 

nodes = tree.getTipNames() 

 

dgr, wdgr = [], [] 

for taxon in nodes: 

horizontals = [ 

g for g in geoGraph[taxon] if 'weight' in geoGraph[taxon][g]] 

dgr.append(len(horizontals)) 

wdgr.append(sum([geoGraph[taxon][g]['weight'] for g in horizontals])) 

 

sorted_nodes = sorted(zip(nodes, dgr, wdgr), key=lambda x: x[1], reverse=True) 

for n, d, w in sorted_nodes: 

f.write('{0}\t{1}\t{2}\t{3}\n'.format( 

n, text_type(tree.getNodeMatchingName(n)), d, w)) 

 

# write edge distributions 

with util.TextFile(self._output_path('edge-msn-' + glm + '.stats')) as f: 

edges = [g for g in geoGraph.edges(data=True) if 'weight' in g[2]] 

 

for nA, nB, d in sorted(edges, key=lambda x: x[2]['weight'], reverse=True): 

f.write('{0}\t{1}\t{2}\t{3}\t{4}\t{5}\n'.format( 

nA, 

nB, 

d['weight'], 

d['cogs'], 

tree.getNodeMatchingName(nA), 

tree.getNodeMatchingName(nB))) 

 

try: 

self.geograph[glm] = geoGraph 

except: 

self.geograph = {} 

self.geograph[glm] = geoGraph 

return 

 

def plot_MSN( 

self, 

glm='', 

fileformat='pdf', 

threshold=1, 

usetex=False, 

alphat=False, 

alpha=0.75, 

only=[], 

**keywords 

): 

""" 

Plot a minimal spatial network. 

""" 

util.setdefaults( 

keywords, 

latex_preamble=[], 

figsize=(10, 10), 

colormap=mpl.cm.jet, 

filename=self.dataset, 

linescale=1.0, 

maxweight=False, 

xlim=5, 

ylim=5, 

xlimr=False, 

xliml=False, 

ylimt=False, 

ylimb=False, 

left=0.02, 

right=0.98, 

top=1.00, 

bottom=0.00, 

cbar_shrink=0.55, 

cbar_fraction=0.1, 

cbar_pad=0.1, 

cbar_orientation='vertical', 

cbar_label='Inferred Links', 

cbar_fontsize=10, 

resolution='l', 

table_text_color='black', 

water_color='0.2', 

lw=2, 

cmap_max=250, 

continent_color='0.9', 

projection='merc', 

legend_size=18, 

linewidth=4, 

min_lon=False, 

max_lon=False, 

min_lat=False, 

max_lat=False, 

table_column_width=[0.025, 0.1325], 

coastline_color="0.5", 

table_location=3, 

legend_location=[0.85, 0.02], 

table_cell_height=0.024, 

table_text_size=10, 

alpha=0.75, 

cmap_min=30, 

markersize=20) 

 

# load the rc-file XXX add internal loading later 

conf = self._config() 

if not conf: 

try: 

conf = self._meta['conf'] 

except: 

raise ValueError('[!] Configuration is not specified!') 

 

only = only or self.taxa 

 

# switch backend, depending on whether tex is used or not 

backend = mpl.get_backend() 

if usetex and backend != 'pgf': 

plt.switch_backend('pgf') 

mpl.rcParams['text.latex.unicode'] = True 

elif not usetex and backend != 'TkAgg': 

plt.switch_backend('TkAgg') 

 

# check for preamble settings 

if keywords['latex_preamble']: 

mpl.rcParams['pgf.preamble'] = keywords['latex_preamble'] 

 

mpl.rc('text', usetex=usetex) 

filename = keywords['filename'] 

colormap = keywords['colormap'] 

 

# check for groups, add functionality for groups in qlc-file later XXX 

if 'groups' in self._meta: 

groups = self._meta['groups'] 

else: 

groups = {k: v for k, v in csv2list(self.dataset, 'groups')} 

 

conf.update(keywords) 

 

# set the graph variable 

geoGraph = self.geograph[glm] 

 

# get the weights for the lines 

weights = [d['weight'] for a, b, d in geoGraph.edges(data=True)] 

max_weight = max(weights) 

sorted_weights = sorted(set(weights)) 

 

color_dict = np.array(np.linspace(0, 256, len(set(weights))), dtype='int') 

line_dict = np.linspace(0.5, conf['linewidth'], len(set(weights))) 

 

# XXX check for coordinates of the taxa, otherwise load them from file and 

# add them to the wordlist XXX add later, we first load it from file 

if 'coords' in self._meta: 

coords = self._meta['coords'] 

else: 

coords = csv2dict(self.dataset, 'coords', dtype=[str, float, float]) 

 

# determine the maxima of the coordinates 

latitudes = [i[0] for i in coords.values()] 

longitudes = [i[1] for i in coords.values()] 

 

min_lat, max_lat = min(latitudes), max(latitudes) 

min_lon, max_lon = min(longitudes), max(longitudes) 

 

fig = plt.figure(figsize=keywords['figsize']) 

figsp = fig.add_subplot(111) 

 

# instantiate the basemap 

m = bmp.Basemap( 

llcrnrlon=min_lon + conf['min_lon'], 

llcrnrlat=min_lat + conf['min_lat'], 

urcrnrlon=max_lon + conf['max_lon'], 

urcrnrlat=max_lat + conf['max_lat'], 

resolution=conf['resolution'], 

projection=conf['projection'] 

) 

 

# draw first values 

m.drawmapboundary(fill_color=conf['water_color']) 

m.drawcoastlines(color=conf['continent_color'], linewidth=0.5) 

m.drawcountries(color=conf['coastline_color'], linewidth=0.5) 

m.fillcontinents(color=conf['continent_color'], lake_color=conf['water_color']) 

 

# plot the lines 

for a, b, d in sorted(geoGraph.edges(data=True), key=lambda x: x[2]['weight']): 

if a in coords and b in coords and a in only or b in only: 

w = d['weight'] 

 

color = colormap(color_dict[sorted_weights.index(w)]) 

linewidth = line_dict[sorted_weights.index(w)] 

 

if w < threshold: 

if alphat: 

alpha = 0.2 

else: 

linewidth = 0.0 

else: 

alpha = conf['alpha'] 

 

# retrieve the coords 

yA, xA = coords[a] 

yB, xB = coords[b] 

 

# get the points on the map 

xA, yA = m(xA, yA) 

xB, yB = m(xB, yB) 

 

# plot the points 

plt.plot( 

[xA, xB], 

[yA, yB], 

'-', 

color=color, 

alpha=alpha, 

linewidth=linewidth, 

zorder=w + 50) 

 

# plot the points for the languages 

cell_text = [] 

legend_check = [] 

 

# check for taxon.labels in conf 

if 'taxon_labels' in conf: 

tfunc = lambda x: conf['taxon_labels'][x] 

else: 

tfunc = lambda x: x 

if 'groups_labels' in conf: 

gfunc = lambda x: conf['groups_labels'][x] 

else: 

gfunc = lambda x: x 

 

defaults = {"markersize": 10, "table_cell_height": 0.025} 

for k in defaults: 

if k not in conf: 

conf[k] = defaults[k] 

 

for i, (taxon, (lng, lat)) in enumerate( 

sorted(coords.items(), key=lambda x: x[0])): 

 

# retrieve x and y from the map 

x, y = m(lat, lng) 

 

# get colors from conf 

this_group = groups[taxon] 

taxon_color = conf['groups_colors'][this_group] 

try: 

taxon_marker = conf['groups_markers'][this_group] 

except: 

taxon_marker = 'o' 

 

if gfunc(groups[taxon]) in legend_check: 

plt.plot( 

x, 

y, 

taxon_marker, 

markersize=conf['markersize'], 

color=taxon_color, 

zorder=max_weight + 52) 

else: 

plt.plot( 

x, 

y, 

taxon_marker, 

markersize=conf['markersize'], 

color=taxon_color, 

zorder=max_weight + 52, 

label=gfunc(groups[taxon])) 

legend_check.append(gfunc(groups[taxon])) 

 

# add number to celltext 

if usetex: 

cell_text.append([str(i + 1), tfunc(taxon).replace('_', r'\_')]) 

else: 

cell_text.append([str(i + 1), tfunc(taxon)]) 

 

# plot the text 

# check for darkness of color 

if taxon_color in ['black', 'gray'] or taxon_color[:3] in ['0.3', '0.2', 

'0.1', '0.0']: 

text_color = 'white' 

else: 

text_color = 'black' 

 

plt.text( 

x, 

y, 

str(i + 1), 

size=str(int(conf['markersize'] / 2)), 

color=text_color, 

label=taxon, 

horizontalalignment='center', 

fontweight="bold", 

verticalalignment='center', 

zorder=max_weight + 55) 

 

# add a colorbar 

cax = figsp.imshow([[1, 2], [1, 2]], visible=False, cmap=colormap) 

cbar = fig.colorbar( 

cax, 

ticks=[1, 1.25, 1.5, 1.75, 2], 

orientation=keywords['cbar_orientation'], 

shrink=keywords['cbar_shrink'], 

fraction=keywords['cbar_fraction'], 

pad=keywords['cbar_pad'], 

) 

cbar.set_clim(1.0) 

cbar.set_label(keywords['cbar_label'], fontsize=keywords['cbar_fontsize']) 

cbar.ax.set_yticklabels( 

[ 

str(min(weights)), 

'', 

str(int(max(weights) / 2)), 

'', 

str(max(weights)) 

], 

fontsize=keywords['cbar_fontsize'] 

) 

 

# add the legend 

this_table = plt.table( 

cellText=cell_text, 

colWidths=conf['table_column_width'], 

loc=conf['table_location'], 

) 

this_table.auto_set_font_size(False) 

this_table.set_fontsize(conf['table_text_size']) 

 

# adjust the table 

for line in this_table._cells: 

this_table._cells[line]._text._horizontalalignment = 'left' 

this_table._cells[line]._text._fontproperties.set_weight('bold') 

this_table._cells[line]._text.set_color(conf['table_text_color']) 

this_table._cells[line].set_height(conf['table_cell_height']) 

# this_table._cells[line]._text._fontproperties.set_size(conf['table.text.size']) 

this_table._cells[line].set_linewidth(0.0) 

this_table._cells[line].set_color(conf['table_cell_color']) 

 

this_table.set_zorder(100) 

 

plt.legend( 

loc=conf['legend_location'], 

numpoints=1, 

prop={'size': conf['legend_size'], 'weight': 'bold'}) 

 

plt.subplots_adjust( 

left=keywords['left'], 

right=keywords['right'], 

top=keywords['top'], 

bottom=keywords['bottom']) 

 

plt.savefig(filename + '.' + fileformat) 

plt.clf() 

log.file_written(filename + '.' + fileformat) 

 

def plot_two_concepts( 

self, 

concept, 

cogA, 

cogB, 

labels={1: '1', 2: '2', 3: '3', 4: '4'}, 

tcolor={1: 'white', 2: 'black', 3: '0.5', 4: '0.1'}, 

filename='pdf', 

fileformat='pdf', 

usetex=True 

): 

""" 

Plot the evolution of two concepts in space. 

 

Notes 

----- 

This function may be useful to contrast patterns of different words in 

geographic space. 

 

""" 

mpl.rc('text', usetex=True) 

taxa = self.taxa 

 

# XXX check for coordinates of the taxa, otherwise load them from file and 

# add them to the wordlist XXX add later, we first load it from file 

if 'coords' in self._meta: 

coords = self.coords 

else: 

coords = csv2dict(self.dataset, 'coords', dtype=[str, float, float]) 

 

conf = self._config() 

 

these_taxa = {} 

for taxon in taxa: 

# get the dictionary and the entry 

cogs = self.get_dict(col=taxon, entry='pap').get(concept, []) 

 

# check for identical cogs and assign them to the 4 categories 

if cogA in cogs and cogB in cogs: 

these_taxa[taxon] = 3 

elif cogA in cogs and cogB not in cogs: 

these_taxa[taxon] = 1 

elif cogA not in cogs and cogB in cogs: 

these_taxa[taxon] = 2 

else: 

these_taxa[taxon] = 4 

 

# determine the maxima of the coordinates 

latitudes = [i[0] for i in coords.values()] 

longitudes = [i[1] for i in coords.values()] 

 

min_lat, max_lat = min(latitudes), max(latitudes) 

min_lon, max_lon = min(longitudes), max(longitudes) 

 

# start to initialize the basemap 

fig = plt.figure() 

fig.add_subplot(111) 

 

# instantiate the basemap 

m = bmp.Basemap( 

llcrnrlon=min_lon + conf['min_lon'], 

llcrnrlat=min_lat + conf['min_lat'], 

urcrnrlon=max_lon + conf['max_lon'], 

urcrnrlat=max_lat + conf['max_lat'], 

resolution=conf['resolution'], 

projection=conf['projection'] 

) 

 

# draw first values 

m.drawmapboundary(fill_color=conf['water_color']) 

m.drawcoastlines(color=conf['continent_color'], linewidth=0.5) 

m.drawcountries(color=conf['coastline_color'], linewidth=0.5) 

m.fillcontinents(color=conf['continent_color'], lake_color=conf['water_color']) 

 

# plot the points for the languages 

cell_text = [] 

legend_check = [] 

for i, (taxon, (lng, lat)) in enumerate( 

sorted(coords.items(), key=lambda x: x[0])): 

 

# retrieve x and y from the map 

x, y = m(lat, lng) 

 

# get the color of the given taxon 

# taxon_color = colors[groups[taxon]] 

 

marker = '*' if these_taxa[taxon] == 4 else 's' 

 

if labels[these_taxa[taxon]] in legend_check: 

plt.plot( 

x, 

y, 

marker, 

markersize=conf['markersize'], 

color=tcolor[these_taxa[taxon]]) 

else: 

plt.plot( 

x, 

y, 

marker, 

markersize=conf['markersize'], 

color=tcolor[these_taxa[taxon]], 

label=labels[these_taxa[taxon]]) 

legend_check.append(labels[these_taxa[taxon]]) 

 

# add number to celltext 

if usetex: 

cell_text.append([str(i + 1), taxon.replace('_', r'\_')]) 

else: 

cell_text.append([str(i + 1), taxon]) 

 

plt.text( 

x, 

y, 

str(i + 1), 

size=str(int(conf['markersize'] / 2)), 

label=taxon, 

color='white' if tcolor[these_taxa[taxon]] == 'black' else 'black', 

horizontalalignment='center', 

verticalalignment='center') 

 

this_table = plt.table( 

cellText=cell_text, 

colWidths=conf['table.column.width'], 

loc=conf['table.location']) 

 

# adjust the table 

for line in this_table._cells: 

this_table._cells[line]._text._horizontalalignment = 'left' 

this_table._cells[line]._text._fontproperties.set_weight('bold') 

this_table._cells[line]._text.set_color(conf['table.text.color']) 

this_table._cells[line].set_height(conf['table.cell.height']) 

this_table._cells[line]._text._fontproperties.set_size( 

conf['table.text.size']) 

this_table._cells[line].set_linewidth(0.0) 

this_table._cells[line].set_color(conf['table.cell.color']) 

 

this_table.set_zorder(100) 

plt.legend( 

loc=conf['legend.location'], 

numpoints=1, 

prop={'size': conf['legend.size'], 'weight': 'bold'}) 

 

plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05) 

plt.savefig(filename + '.' + fileformat) 

plt.clf() 

 

def plot_GLS(self, glm, **keywords): 

""" 

Plot the inferred scenarios for a given model. 

""" 

kw = dict(fileformat='png') 

kw.update(keywords) 

 

# store the graph 

for cog in self.cogs: 

gls = self.gls[glm][cog][0] 

g = gls2gml( 

gls, 

self.tgraph, 

self.tree, 

filename=self._output_path( 

'gml', '{0}-{1}'.format(self.dataset, glm), cog)) 

 

# if plot of gml is chosen 

nodes = [] 

 

for n, d in g.nodes(data=True): 

x = d['graphics']['x'] 

y = d['graphics']['y'] 

f = d['graphics']['fill'] 

r = d['graphics'].get('angle') 

s = d['graphics'].get('s') 

o = d['origin'] 

l = d['label'] 

nodes.append((x, y, f, o, l, r, s)) 

 

edges = [] 

for a, b, d in g.edges(data=True): 

xA = g.node[a]['graphics']['x'] 

xB = g.node[b]['graphics']['x'] 

yA = g.node[a]['graphics']['y'] 

yB = g.node[b]['graphics']['y'] 

edges += [(xA, xB, yA, yB)] 

 

# mpl.rc('text',usetex=keywords['usetex']) 

fig = plt.figure() 

fig.add_subplot(111) 

plt.axes(frameon=False) 

plt.xticks([]) 

plt.yticks([]) 

 

plt.axis('equal') 

 

for xA, xB, yA, yB in edges: 

plt.plot([xA, xB], [yA, yB], '-', color='black', linewidth=5) 

plt.plot([xA, xB], [yA, yB], '-', color='0.2', linewidth=4) 

for x, y, f, o, l, r, s in nodes: 

if f == '#000000': 

f = '#a3a3a3' 

c = '#a3a3a3' 

else: 

c = '#000000' 

 

if o == 1: 

size = 20 

else: 

size = 10 

if l.startswith('edge') or l.startswith('root'): 

plt.plot(x, y, 'o', markersize=size, color=f) 

else: 

if not r: 

plt.text( 

x, 

y, 

l, 

horizontalalignment='center', 

verticalalignment='center', 

size=8, 

fontweight='bold', 

color=c, 

backgroundcolor=f 

) 

else: 

plt.text( 

x, 

y, 

l, 

ha=s, 

va='baseline', 

size=8, 

fontweight='bold', 

color=c, 

rotation=r, 

rotation_mode='anchor', 

bbox=dict( 

facecolor='white', 

boxstyle='square,pad=0.25', 

ec="none", 

alpha=0.25 

), 

) 

 

plt.savefig( 

self._output_path( 

'gml', 

'{0}-{1}-figures'.format(self.dataset, glm), 

'{0}-{1}.'.format(self.pap2con[cog], cog) + kw['fileformat'] 

) 

) 

plt.clf() 

 

def get_stats(self, glm, subset='', filename=''): 

""" 

Calculate basic statistics for a given gain-loss model. 

""" 

if not subset: 

gains = [b for a, b in self.gls[glm].values()] 

else: 

gains = [] 

for cog in self.cogs: 

# get the respective subset-item first 

item = self[[c[0] for c in self.etd[cog] if c != 0][0], subset[0]] 

 

# check whether subset is as specified 

if item in subset[1] or item == subset[1]: 

gains += [self.gls[glm][cog][1]] 

 

noo = sum(gains) / len(gains) 

ppc = sum([1 for g in gains if g > 1]) / len(gains) 

 

log.info('Number of Origins: {0:.2f}'.format(noo)) 

log.info('Percentage of Patchy Cognates: {0:.2f}'.format(ppc)) 

 

if not filename: 

return noo, ppc 

self._write_file( 

filename, 

'Number of origins: {0:.2f}\nPercentage of patchy cogs {1:.2f}\n'.format(noo, 

ppc)) 

 

def plot_concept_evolution(self, glm, concept='', fileformat='png', **keywords): 

""" 

Plot the evolution of specific concepts along the reference tree. 

""" 

util.setdefaults( 

keywords, 

figsize=(15, 15), 

left=0.05, 

top=0.95, 

bottom=0.05, 

right=0.95, 

colormap=mpl.cm.jet, 

edgewidth=5, 

radius=2.5, 

outer_radius=0.5, 

inner_radius=0.25, 

cognates='', 

ref='', 

usetex=False, 

latex_preamble=False, 

textsize=8, 

subset=[]) 

 

# check for the correct item 

if not concept: 

concepts = self.concepts 

else: 

concepts = [i for i in self.concepts if i == concept] 

 

# XXX customize later XXX 

colormap = keywords['colormap'] 

 

# start with the analysis 

for concept in concepts: 

log.info("Plotting concept '{0}'...".format(concept)) 

 

# switch backend, depending on whether tex is used or not 

backend = mpl.get_backend() 

if keywords['usetex'] and backend != 'pgf': 

plt.switch_backend('pgf') 

mpl.rcParams['text.latex.unicode'] = True 

elif not keywords['usetex'] and backend != 'TkAgg': 

plt.switch_backend('TkAgg') 

 

# check for preamble settings 

if keywords['latex_preamble']: 

mpl.rcParams['pgf.preamble'] = keywords['latex_preamble'] 

 

graph = nx.Graph() 

 

# get all paps that are no singletons 

paps = sorted(set([p for p in self.get_list( 

row=concept, flat=True, entry='pap') if p not in self.singletons])) 

 

if len(paps) <= 0: 

log.warn( 

"No entries for concept {0} could be found, skipping the plot.".format( 

concept)) 

else: 

# get the number of paps in order to get the right colors 

cfunc = np.array(np.linspace(10, 256, len(paps)), dtype='int') 

colors = dict([(paps[i], mpl.colors.rgb2hex(colormap(cfunc[i]))) for i in 

range(len(paps))]) 

 

# get the wedges for the paps 

wedges = {} 

linsp = np.linspace(0, 360, len(paps) + 1) 

for i, pap in enumerate(paps): 

theta1, theta2 = linsp[i], linsp[i + 1] 

wedges[pap] = (theta1, theta2) 

 

legendEntriesA = [] 

legendTextA = [] 

 

# add stuff for the legend 

for pap in paps: 

w = mpl.patches.Wedge( 

(0, 0), 

1, 

wedges[pap][0], 

wedges[pap][1], 

facecolor=colors[pap], 

zorder=1, 

linewidth=2, 

edgecolor='black' 

) 

legendEntriesA += [w] 

if keywords['cognates']: 

idx = [x[0] for x in self.etd[pap] if x != 0][0] 

legendTextA += [self[idx, keywords['cognates']]] 

else: 

legendTextA += [pap] 

 

# second legend explains evolution 

legendEntriesB = [] 

legendTextB = [] 

p = mpl.patches.Wedge( 

(0, 0), 1, 0, 360, facecolor='0.5', linewidth=2, edgecolor='black') 

legendEntriesB += [p] 

legendTextB += ['Loss Event'] 

p, = plt.plot(0, 0, '--', color='black', linewidth=2) 

legendEntriesB += [p] 

legendTextB += ['Gain Event'] 

 

# overwrite stuff 

plt.plot(0, 0, 'o', markersize=2, zorder=2, color='white') 

 

# iterate over the paps and append states to the graph 

for pap in paps: 

# get the graph with the model 

gls = self.gls[glm][pap][0] 

g = gls2gml(gls, self.tgraph, self.tree, filename='') 

 

for n, d in g.nodes(data=True): 

if n not in graph: 

graph.add_node(n) 

 

# add a pap-dictionary if it's not already there 

if 'pap' not in graph.node[n]: 

graph.node[n]['pap'] = {} 

 

graph.node[n]['pap'][pap] = d['state'] 

 

# create the figure 

fig = plt.figure(figsize=keywords['figsize']) 

figsp = fig.add_subplot(111) 

figsp.axes.get_xaxis().set_visible(False) 

figsp.axes.get_yaxis().set_visible(False) 

 

plt.axis('equal') 

 

xvals = [] 

yvals = [] 

 

# iterate over edges first 

for nA, nB in g.edges(): 

gA = g.node[nA]['graphics'] 

gB = g.node[nB]['graphics'] 

xA, yA = gA['x'], gA['y'] 

xB, yB = gB['x'], gB['y'] 

 

plt.plot( 

[xA, xB], 

[yA, yB], 

'-', 

color='black', 

linewidth=keywords['edgewidth']) 

 

# now iterate over the nodes 

for n, d in graph.nodes(data=True): 

cpaps = d['pap'] 

x, y = g.node[n]['graphics']['x'], g.node[n]['graphics']['y'] 

 

# get z-value which serves as zorder attribute 

try: 

z = 6 * len(self.tree.getConnectingEdges('root', n)) 

except: 

z = 0 

 

xvals += [x] 

yvals += [y] 

 

# plot the default marker 

plt.plot(x, y, 'o', markersize=5, color='black', zorder=50) 

# check for origins in cpaps 

wedge_args = ( 

(x, y), keywords['radius'] + keywords['outer_radius'], 0, 360) 

if 'O' in cpaps.values(): 

kw = dict( 

facecolor='white', 

zorder=57 + z, 

linewidth=2.5, 

linestyle='dashed') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **kw)) 

elif 'o' in cpaps.values(): 

kw = dict( 

facecolor='white', 

zorder=56 + z, 

linewidth=2.5, 

linestyle='solid') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **kw)) 

if 'L' in cpaps.values() and 'O' in cpaps.values(): 

kw = dict( 

facecolor='0.5', 

zorder=58 + z, 

linewidth=2.5, 

edgecolor='black', 

linestyle='dashed') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **kw)) 

elif "L" in cpaps.values(): 

kw = dict( 

facecolor='0.5', 

zorder=59 + z, 

linewidth=2.5, 

edgecolor='black') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **kw)) 

 

for pap in cpaps: 

theta1, theta2 = wedges[pap] 

color = colors[pap] 

wedge_args = ((x, y), keywords['radius'], theta1, theta2) 

wedge_kw = dict( 

facecolor=color, zorder=61 + z, linewidth=2, edgecolor='black' 

) 

 

# check for characteristics of this pap 

if cpaps[pap] == 'L': 

wedge_kw.update(alpha=0.25, linestyle='dotted') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **wedge_kw)) 

elif cpaps[pap] == 'o': 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **wedge_kw)) 

elif cpaps[pap] == 'O': 

wedge_kw.update(linestyle='dashed') 

figsp.add_artist(mpl.patches.Wedge(*wedge_args, **wedge_kw)) 

 

# add number for node 

if n in self.taxa: 

plt.text( 

x, 

y, 

n, 

size=keywords['textsize'], 

verticalalignment='baseline', 

backgroundcolor='white', 

horizontalalignment='center', 

fontweight='bold', 

color='black', 

bbox=dict( 

facecolor='white', 

boxstyle='square,pad=0.25', 

ec="none", 

alpha=1 

), 

zorder=300 

) 

 

plt.xlim((min(xvals or [0]) - 10, max(xvals or [0]) + 10)) 

plt.ylim((min(yvals or [0]) - 10, max(yvals or [0]) + 10)) 

 

legend1 = plt.legend(legendEntriesA, legendTextA, loc='upper right', 

numpoints=1) 

plt.legend(legendEntriesB, legendTextB, loc='lower right') 

figsp.add_artist(legend1) 

 

plt.subplots_adjust( 

left=keywords['left'], 

right=keywords['right'], 

top=keywords['top'], 

bottom=keywords['bottom']) 

plt.savefig(self._output_path( 

'items', 

'{0}-{1}'.format(self.dataset, glm), 

concept.replace('/', '_') + '.' + fileformat)) 

plt.close() 

 

return 

 

 

TreBor = PhyBo