[go: up one dir, main page]

Menu

[r60]: / minimpy.py  Maximize  Restore  History

Download this file

2826 lines (2673 with data), 134.2 kB

   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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import pickle
import tempfile
import ConfigParser
import shutil
import time
import functions
from model import Model
from minimclass import Minim
from minimpypreferences import PrefWin
from export import Export
from editvariable import EditVariable
from editallocation import EditAllocation
from viewer import Viewer
try:
import pysvn
except:
print("pysvn Not Availible")
sys.exit(1)
try:
import pygtk
pygtk.require("2.0")
import gobject
except:
print("pygtk Not Availible")
sys.exit(1)
try:
import gtk
except:
print("GTK Not Availible")
sys.exit(1)
class ModelInteface(object):
# invalid chars in trial title. Only applicable to network trials
if os.name == 'posix':
invalid_chars = '/'
else:
# Windows
invalid_chars = '\\/:* ?"<>|'
# translator function
def _(self, key):
# key must be supplied
assert len(key) > 0
# if key not in the dict, return the key itself
if self.tr_dict.has_key(key):
return self.tr_dict[key]
else:
return key.replace('_', '.')
def query_trial_dismis(self):
# this method checks whether the trial has unsaved data.
# if there are unsaved data, prompt a warning.
# output: True: means the dismis current state (e.g. start a new trial)
# if the trial file name is set, it means that we have saved the data
if self.trial_file_name:
return True
else:
# empty trial file name: check if changes happend to the interface
if len(self.group_liststore) or len(self.variable_liststore) or len(
self.trial_title_entry.get_text()) or len(functions.get_text_buffer(self.trial_description_text)):
msg = self._('query_trial_dismis_msg')
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._('query_trial_dismis_dialog_title'))
if dialog.run() == gtk.RESPONSE_NO:
dialog.destroy()
return False
dialog.destroy()
return True
def delete_event(self, widget, event):
# check if we have unsaved data and ask fir sure, if not cancel the close
for item in self.used_temp_files:
if tempfile._exists(item):
try:
self.remove_temp_file(item)
except:
pass
if not self.query_trial_dismis():
# do not exit
return True
self.window.destroy()
gtk.main_quit()
def group_cell_edited(self, cell, row, new_text, col):
# edit group data
# col = 0: group name
if col == 0:
# names must not be repeated
for r in range(len(self.group_liststore)):
if r != row and new_text == self.group_liststore[r][0]:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_group_name_already_in_use'))
return False
# empty cell not permitted
if len(new_text) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_group_name_can_not_be_empty'))
return False
# group allocation ration
if col == 1:
# must be digits
if not new_text.isdigit():
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_ratio_must_be_an_integer'))
return False
# convert to integer
new_text = int(new_text)
# should be within range
adj = cell.get_property('adjustment')
if adj.upper < new_text or new_text < adj.lower:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_ratio_must_be_in_range').format(int(adj.lower), int(adj.upper)))
return False
# save the value
self.group_liststore[row][col] = new_text
# update the interface
self.update_interface()
def group_add_button(self, widget, data=None):
# adding a group
# name and allocation ratio default to 'Group n' and 1
# name must be unique
n = 1
while True:
group_name = 'Group {0}'.format(n)
for row in range(len(self.group_liststore)):
if self.group_liststore[row][0] == group_name:
break
else:
break
n += 1
self.group_liststore.append((group_name, 1))
# update the interface
self.update_interface()
def group_delete_button(self, widget, data=None):
# if a group is selected
if self.group_treeview.get_cursor()[0]:
# row of the selection
row = self.group_treeview.get_cursor()[0][0]
# remove the selected group
self.group_liststore.remove(self.group_liststore.get_iter(row))
self.update_interface()
# nothing is selected
else:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_please_select_a_group_first'))
return False
def variable_add_button(self, widget, data=None):
# add avariable
# choose a default name for this new variable
# name must be unique. weight defaults to 1.0 and levels to 'Level 0, Level 1'
n = 1
while True:
var_name = 'Variable {0}'.format(n)
for row in range(len(self.variable_liststore)):
if self.variable_liststore[row][0] == var_name:
break
else:
break
n += 1
self.variable_liststore.append((var_name, 1.0, 'Level 0,Level 1'))
self.update_interface()
# scroll down to the new variable
row = len(self.variable_liststore) - 1
functions.treeview_scroll_select_row(self.window, self.variable_treeview, row)
EditVariable(self, row)
def variable_delete_button(self, widget, data=None):
# delete a var
if self.variable_treeview.get_cursor()[0]:
row = self.variable_treeview.get_cursor()[0][0]
self.variable_liststore.remove(self.variable_liststore.get_iter(row))
self.update_interface()
else:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_select_a_variable_first'))
return False
def build_variable_combos_dialog(self):
dlg = gtk.Dialog(title= self._('allocation_add'),
parent=self.window,
flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_ADD, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dlg.set_size_request(450, 300)
dlg.set_default_response(gtk.RESPONSE_OK)
dlg.set_has_separator(True)
lbl = gtk.Label(self._('select_variables_level'))
dlg.vbox.pack_start(lbl)
self.combo_vbox = gtk.VBox(False)
functions.make_scrolling(self.combo_vbox, dlg.vbox)
hb = gtk.HBox(False)
self.case_properties_liststore, self.case_properties_treeview = functions.make_treeview(
(str, str), [self._('name'), self._('value')],
editable=True, edit_handler=self.case_properties_cell_edited)
functions.make_scrolling(self.case_properties_treeview, hb)
vbuttonbox = gtk.VButtonBox()
vbuttonbox.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, gtk.STOCK_ADD)
button.connect("clicked", self.case_properties_add_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DELETE)
button.connect("clicked", self.case_properties_delete_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DATE)
button.connect("clicked", self.case_properties_date_button)
vbuttonbox.pack_start(button, False, False)
hb.pack_start(vbuttonbox, False, False)
lbl = gtk.Label(self._('new_case_extra_properties'))
dlg.vbox.pack_start(lbl, False, False)
dlg.vbox.pack_start(hb, False, False)
dlg.vbox.show_all()
dlg.connect('response', self.handle_variable_add_dialog_respnse)
return dlg
def handle_variable_add_dialog_respnse(self, dialog, response_id):
if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
dialog.hide()
return
for cbo in self.variable_combos:
if cbo.get_active() == -1:
cbo.popup()
return
dialog.hide()
def update_interface(self):
# update the interface after change in groups and variable
# first remove allocations columns
n = len(self.allocations_treeview.get_columns())
while n:
n = self.allocations_treeview.remove_column(self.allocations_treeview.get_column(n-1))
# then destroy the case selection widgets
widgets = self.combo_vbox.get_children()
for widget in widgets:
widget.destroy()
# selt the var combo list to empty
self.variable_combos = []
# a container table for var widgets
table = gtk.Table(2, len(self.variable_liststore)+1)
table.show()
n = 0
# adding variable widgets for selecting levels of new case
for variable in self.variable_liststore:
lbl = gtk.Label(variable[0])
lbl.show()
table.attach(lbl, 0, 1, n, n+1)
cbo = gtk.combo_box_new_text()
cbo.show()
# populating each cbo with levels of variable
for level in map(str.strip, variable[2].split(',')):
cbo.append_text(level)
cbo.set_active(0)
# saving the cbo in a global list
self.variable_combos.append(cbo)
table.attach(cbo, 1, 2, n, n+1)
n += 1
# placing the table inside the self.combo_vbox
self.combo_vbox.pack_start(table, False, False)
# setting up allocation table, one col for each variable, 3 extra cols for
# extra values (#, ui, group)
types = ((int,) + (str,) * (len(self.variable_liststore) + 2))
liststore = gtk.ListStore(*types)
# first col for sequence number
tvcolumn = gtk.TreeViewColumn('#')
self.allocations_treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 0)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
tvcolumn.set_sort_column_id(0)
# next col for UI
tvcolumn = gtk.TreeViewColumn('UI')
self.allocations_treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 1)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
tvcolumn.set_sort_column_id(1)
# third col for group of subject
tvcolumn = gtk.TreeViewColumn(self._('general_group'))
self.allocations_treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', 2)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
tvcolumn.set_sort_column_id(2)
# remaining cols for selected levels of each variable
# start at col 2 (third col)
n = 2
for variable in self.variable_liststore:
n += 1
tvcolumn = gtk.TreeViewColumn(variable[0])
self.allocations_treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', n)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
tvcolumn.set_sort_column_id(n)
# set the model to the treeview
self.allocations_treeview.set_model(liststore)
self.allocations_treeview.show()
# equivalent models of variable_combos
variable_models = [cbo.get_model() for cbo in self.variable_combos]
# now populating allocation table with subjects
for row, record in enumerate(self.allocations):
liststore.append()
# first three rows for #, UI and group of the subject
liststore[row][0] = row
UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
liststore[row][1] = str(record['UI']).zfill(UI_len)
liststore[row][2] = self.group_liststore[record['allocation']][0]
# remaining cols populate with the selected levels of each variable
for col, variable_model in enumerate(variable_models):
liststore[row][col+3] = variable_model[record['levels'][col]][0]
def min_allocation_ratio_group_index(self):
idx, r = 0, self.group_liststore[0][1]
for i in range(len(self.group_liststore)):
if self.group_liststore[i][1] < r:
idx, r = i, self.group_liststore[i][1]
return idx
def get_minimize_case(self, new_case):
# minimize a new case. Input is a new case
# a model for holding the minimization parameters
model = Model()
model.groups = range(len(self.group_liststore))
model.variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
model.variables_weight = [self.variable_liststore[row][1] for row in range(len(self.variable_liststore))]
model.allocation_ratio = [self.group_liststore[row][1] for row in range(len(self.group_liststore))]
model.allocations = self.allocations
model.prob_method = self.get_prob_method()
model.distance_measure = self.get_distance_measure()
model.high_prob = self.high_prob_spin.get_value()
model.min_group = self.min_allocation_ratio_group_index()
# a minimization object to do minimization. Setup based on the model and random as determined by
# program configuration
m = Minim(random=self.random, model=model)
# build probabilities table depending on the current allocations,
# var weights and group allocation ratios
m.build_probs(model.high_prob, model.min_group)
# the build the frequency table
m.build_freq_table()
# if an initial preload, add it to the current
if self.initial_freq_table:
self.add_to_initial(m.freq_table)
# now do the actual minimization
return m.enroll(new_case, m.freq_table)
def add_to_initial(self, freq_table):
# if an initial preload, add it to the current
for row, group in enumerate(freq_table):
for v, variable in enumerate(group):
for l, level in enumerate(variable):
freq_table[row][v][l] += self.initial_freq_table[row][v][l]
def remove_allocation(self, row=-1):
# remove the selected allocation
# row = -1 means the last allocation
model = self.allocations_treeview.get_model()
# list is empty
if model == None or len(model) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
return False
# row = -1 is sufficient, no need to change into len(model) -1. Only to clear the issue
if row == -1:
row = len(model) -1
ui = model[row][1]
# UI of deleted case back into the pool
# reorder the model to unsourted state
model.set_sort_column_id(0, gtk.SORT_ASCENDING)
# finding the new row which holds the ui
for row in range(len(model)):
# the selected subject still present in the list, so we got the row and exit the for loop
if model[row][1] == ui:
break
else:
# another user has changed the data
functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))
return False
del_case = self.allocations.pop(row)
self.ui_pool.append(del_case['UI'])
self.random.shuffle(self.ui_pool)
path = (row,)
iter = model.get_iter(path)
# removing the selected subject
model.remove(iter)
self.set_progressbar_status()
return True
def allocations_delete(self, ui, prompt=False):
# delete the subject with specified ui. No prompt by default
if self.network_sync_dict['sync'] and self.trial_file_name:
# update the network trial
repo_path = self.update_network_trial()
model = self.allocations_treeview.get_model()
# empty model
if model and len(model) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
return False
# check if the model has changed since the last save
for row in range(len(model)):
# the selected subject still present in the list, so we got the row and exit the for loop
if model[row][1] == ui:
break
else:
# another user has changed the data
functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))
return False
if prompt:
msg = self._('allocations_delete_msg').format(ui)
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._('allocations_delete_dialog_title'))
if dialog.run() == gtk.RESPONSE_NO:
dialog.destroy()
return False
dialog.destroy()
# removing the selected subject
self.remove_allocation(row)
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
# if the list is empty, check if the user likes to unlock the trial
if row != -1 and prompt:
if model == None or len(model) == 0:
if self.trial_file_name:
self.want_trial_unlock(True)
def allocations_delete_button(self, widget, data=None):
# event function for deleting selected subject
model = self.allocations_treeview.get_model()
# if list is empty, consider trial unlock
if model and len(model) == 0:
# unlock
if self.trial_file_name:
self.want_trial_unlock(True)
return False
# no unloack wanted. Say the list is empty and return
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
return False
# if a subject is selected, obtain the row and UI of it
if self.allocations_treeview.get_cursor()[0]:
selected_row = self.allocations_treeview.get_cursor()[0][0]
selected_ui = model[selected_row][1]
else:
# no selection, exit
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_please_select_an_allocation_first'))
return False
# updating the model
model = self.allocations_treeview.get_model()
if model == None or len(model) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_no_subject_allocated'))
return False
# It is required to select based on the UI of the selected row,
# because another user may have changed the data or has deleted the selected recoded and
# therefore the displayed data are not uptodate
self.waiting_function(self.allocations_delete, (selected_ui, True))
def allocations_clear(self):
# clear subjects list
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
model = self.allocations_treeview.get_model()
if model == None or len(model) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_allocation_table_is_empy'))
return
model = self.allocations_treeview.get_model()
# first recycling the UIs
for row in range(len(model)):
self.ui_pool.append(self.allocations[row]['UI'])
self.random.shuffle(self.ui_pool)
# then clear the list
model.clear()
# and the aloocations list
self.allocations = []
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
def allocations_clear_button(self, widget, data=None):
# event function for allocations clear
self.waiting_function(self.allocations_clear, ())
def add_one_allocation(self, add_random_case=False):
ui = self.ui_pool.pop()
new_case = {'levels': [], 'allocation': -1, 'UI': ui}
# set the levels of this new case
for cbo in self.variable_combos:
# if random
if add_random_case:
new_case['levels'].append(self.random.choice(range(len(cbo.get_model()))))
else:
# appending the selected level to the levels of new case
new_case['levels'].append(cbo.get_active())
# we have our case, now minimize it
m_group = self.get_minimize_case(new_case)
# if no error, use the generated group
if m_group > -1:
# set the allocation of the new case
new_case['allocation'] = m_group
# append the new case to the list of subjects
case_properties = self.get_case_properties()
if case_properties:
new_case['properties'] = case_properties
self.allocations.append(new_case)
def refresh_allocations_treeview(self):
model = self.allocations_treeview.get_model()
# now refresh the allocations treeview
model.clear()
# process one case each time
for row, case in enumerate(self.allocations):
model.append()
# the seq (#)
model[row][0] = row
# UI
UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
model[row][1] = str(case['UI']).zfill(UI_len)
# group
model[row][2] = self.group_liststore[case['allocation']][0]
# set the levels of each variable for this case
for i, level in enumerate(case['levels']):
# labels of levels in this variable
cbo_model = self.variable_combos[i].get_model()
# using this label
model[row][3+i] = cbo_model[level][0]
model.clear()
# process one case each time
for row, case in enumerate(self.allocations):
model.append()
# the seq (#)
model[row][0] = row
# UI
UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
model[row][1] = str(case['UI']).zfill(UI_len)
# group
model[row][2] = self.group_liststore[case['allocation']][0]
# set the levels of each variable for this case
for i, level in enumerate(case['levels']):
# labels of levels in this variable
cbo_model = self.variable_combos[i].get_model()
# using this label
model[row][3+i] = cbo_model[level][0]
return model[-1][0], model[-1][1]
def allocations_add_all(self):
# for research: all remaining subjects will be minimized
# first update the trial
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
model = self.allocations_treeview.get_model()
# empty model
if not model:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_groups_prognostic_factors_must_be_defined'))
return False
# empty UI pool
if not self.ui_pool:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_trial_finished_or_not_saved'))
return False
# consume all UIs
model.set_sort_column_id(0, gtk.SORT_ASCENDING)
while self.ui_pool:
self.add_one_allocation(add_random_case=True)
row, ui = self.refresh_allocations_treeview()
functions.treeview_scroll_select_row(self.window, self.allocations_treeview, row)
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
def allocations_add_all_button(self, widget, data=None):
# event function for adding all allocations
self.waiting_function(self.allocations_add_all, ())
def random_case_button(self, button, data=None):
# generate a random case and set the variable widgets with it
# go through every variable widget
for cbo in self.variable_combos:
# set its active text randomly
item = self.random.choice(range(len(cbo.get_model())))
cbo.set_active(item)
self.allocations_add_button(None, None)
def allocations_add(self):
# add one allocation (uses self.add_one_allocation to complete its job)
# we have to save the current selections of variable widgets prior to update. because
# the network update resets all variable widgets
cbo_selects = []
# gor through each variable widget and capture its current value (level)
for cbo in self.variable_combos:
# if nothing is selected, warn and exit
if cbo.get_active() == -1:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_factor_levels_not_selected'))
return False
# capture the current selection
cbo_selects.append(cbo.get_active())
# update network trial
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
# restore the selections of variable widgets
for i, cbo in enumerate(self.variable_combos):
cbo.set_active(cbo_selects[i])
model = self.allocations_treeview.get_model()
# trial not initialized. factors and groups not defined
if not model:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_groups_factors_defined_first'))
return False
# UI pool is empty
if not self.ui_pool:
# sample size completed
if len(model):
if not self.set_extra_sample_size():
return False
self.allocations_add()
return
# trial not saved
else:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_trial_not_saved'))
return False
# add one allocation and get the row and UI of new subject
self.add_one_allocation()
row, ui = self.refresh_allocations_treeview()
# report the new allocation and ask confirmation (may be it is safer to update
# network trial, then delete the case). Ignore this if this is for research
if not self.config.getboolean('interface', 'batch_allocation'):
if not self.report_allocation(model):
# not confirmed, delete it.
# recycle the UI
del_case = self.allocations.pop(row)
self.ui_pool.append(del_case['UI'])
self.random.shuffle(self.ui_pool)
# delete the new case from the allocations treeview and allocations list
path = (row,)
iter = model.get_iter(path)
model.remove(iter)
return
# save the changes
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
# scroll down to the new case
functions.treeview_scroll_select_row(self.window, self.allocations_treeview, row)
# if this was the last case, ask for sample size extension
if len(self.ui_pool) == 0:
self.end_trial()
def trial_refresh(self):
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
def trial_refresh_button(self, widget, data=None):
self.waiting_function(self.trial_refresh, ())
def allocations_add_button(self, widget, data=None):
if not self.trial_file_name: return
if self.variable_combos_dialog.run() != gtk.RESPONSE_OK: return
# event function for adding an allocation
self.waiting_function(self.allocations_add, ())
def report_allocation(self, model):
# textual reporting of a new allocation and asking for confirmation
column = self.allocations_treeview.get_columns()
row = len(model)-1
ret = []
# obtaining all information of the new case
for col, column in enumerate(column):
ret.append(column.get_title() + ': {0}'.format(model[row][col]))
# if dialog is not desired return here
# display the dialog and ask to confirm the case
msg = self._('allocating_new_case').format('\n'.join(ret))
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._('new_allocation'))
if dialog.run() == gtk.RESPONSE_YES:
dialog.destroy()
# case is valid
return True
dialog.destroy()
# case is not valid
return False
def end_trial(self):
# ask if user wants to extend the sample
msg = self._('extend_sample').format(len(self.allocations))
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._('trial_finished'))
if dialog.run() == gtk.RESPONSE_YES:
dialog.destroy()
# if yes, then ask how much to extend and save the change in sample size
return self.set_extra_sample_size()
dialog.destroy()
def set_extra_sample_size(self):
# manage extra sample size
# extra sample defaults to 0
extra_sample = 0
# this function prompts the user to enter an extra sample size
extra_sample = functions.simple_spin_dialog(self._('extra_sample'), self.window)
# if it zero return
if extra_sample == 0: return False
# total sample size
ss = len(self.allocations)+int(extra_sample)
# set the new total sample size
self.trial_sample_size_spin.set_value(ss)
# build extra UIs. Pass the list of extra UIs to the method for format it
self.build_ui_pool(range(len(self.allocations), ss))
# saving changes. Set the save_sample_size flag to save the sample size
self.save_trial_changes(save_sample_size=True)
return True
def refresh_freq_table(self):
# refresh the frequency table
# create a Model object and setting it parameters
model = Model()
model.groups = range(len(self.group_liststore))
model.variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
model.variables_weight = [self.variable_liststore[row][1] for row in range(len(self.variable_liststore))]
model.allocation_ratio = [self.group_liststore[row][1] for row in range(len(self.group_liststore))]
model.allocations = self.allocations
# create a Minim object based on the supplied Model and random
m = Minim(random=self.random, model=model)
# rebuild the frequency table
m.build_freq_table()
# if an initial table add to it
if self.initial_freq_table:
self.add_to_initial(m.freq_table)
# no subject
if not len(m.freq_table):
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_no_allocation'))
return False
# refreshin. First delete the frequency table cols
n = len(self.freq_table_treeview.get_columns())
while n:
n = self.freq_table_treeview.remove_column(self.freq_table_treeview.get_column(n-1))
# then build a list containing names of varable levels
# first an empty list
column_names = []
# extend it for levels of each variable
for variable in self.variable_liststore:
column_names.extend([level for level in map(str.strip, variable[2].split(','))])
# prepend a col for group names and append another col for row total
column_names = [self._('general_group')] + column_names + [self._('general_total')]
# how many cols this table has
cols = 0
for var in m.freq_table[0]:
cols += len(var)
# types of cols. first one is for group names, others are numeric
col_types = [str] + [int] * (cols + 1)
# create the liststore
liststore = gtk.ListStore(*col_types)
# create the columns
for n in range(len(column_names)):
tvcolumn = gtk.TreeViewColumn(column_names[n])
self.freq_table_treeview.append_column(tvcolumn)
cell = gtk.CellRendererText()
tvcolumn.pack_start(cell, True)
tvcolumn.add_attribute(cell, 'text', n)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
# set the model of treeview
self.freq_table_treeview.set_model(liststore)
# adding data to the model
for row, group in enumerate(m.freq_table):
liststore.append()
# first col is group names
liststore[row][0] = self.group_liststore[row][0]
col = 1
# other cols are for levels of variables
for variable in group:
for level in variable:
liststore[row][col] = level
col += 1
# last col is row total
liststore[row][col] = sum(variable)
# finally addan extra row for col totals
liststore.append()
liststore[len(m.freq_table)][0] = self._('general_total')
# calculating col totals
total = 0
for c in range(1, col):
col_total = sum([liststore[row][c] for row in range(len(m.freq_table))])
# calculating grand total too
total += col_total
# setting col total
liststore[len(m.freq_table)][c] = col_total
# since grand total have need calculated many times (each for one variable,
# so we have to divide the sum by the number of variables
liststore[len(m.freq_table)][c+1] = total / len(self.variable_liststore)
# set editable property to true, if the button label is ...
if self.freq_table_enable_edit_button.get_label() == self._("button_save_as_initial_table"):
self.freq_table_enable_edit()
def notebook_switch_page(self, page_num):
# function to manage notebook page switch
# display a status bar message specific to each page
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self.notbook_tabs[page_num])
# nothing for 4 pages
if page_num < 4: return
# if trial data are not valid do not rebuild the frequency table
if not self.trial_is_valid(show_msg=False, table_edit=True): return
# it table is still editable, do not change it
if self.freq_table_enable_edit_button.get_label() == self._("button_save_as_initial_table"): return
# refresh the table
self.refresh_freq_table()
# and the balance table
self.balance_table_refresh()
def notebook_switch_page_event(self, notebook, page, page_num, data=None):
if page_num == 6: # help
self.window.set_focus(self.about_text)
# event function for switch page event
# only for table and balance pages
if not page_num in (4, 5): return
self.waiting_function(self.notebook_switch_page, (page_num,))
def trial_properties_cell_edited(self, cell, row, new_text, col):
# event function for cell edit event
self.trial_properties_liststore[row][col] = new_text
def case_properties_cell_edited(self, cell, row, new_text, col):
# event function for cell edit event
self.case_properties_liststore[row][col] = new_text
def trial_properties_add_button(self, widget, data=None):
# event function for add trial property event
self.trial_properties_liststore.append((self._('property_name'), self._('property_value')))
def case_properties_add_button(self, widget, data=None):
# event function for add trial property event
self.case_properties_liststore.append((self._('property_name'), self._('property_value')))
def trial_properties_date_button(self, widget, data=None):
# event function for add date property event
self.trial_properties_liststore.append((self._('started_on'), time.ctime()))
def case_properties_date_button(self, widget, data=None):
# event function for add date property event
self.case_properties_liststore.append((self._('enrolled_on'), time.ctime()))
def trial_properties_delete_button(self, widget, data=None):
# event function for delete property event
if self.network_sync_dict['sync'] and self.trial_file_name:
# with network trials, deleting trial properties after saving the trials may be too complicated.
return False
if self.trial_properties_treeview.get_cursor()[0]:
row = self.trial_properties_treeview.get_cursor()[0][0]
self.trial_properties_liststore.remove(self.trial_properties_liststore.get_iter(row))
def case_properties_delete_button(self, widget, data=None):
# event function for delete property event
if self.case_properties_treeview.get_cursor()[0]:
row = self.case_properties_treeview.get_cursor()[0][0]
self.case_properties_liststore.remove(self.case_properties_liststore.get_iter(row))
def show_info_message(self, widget, event, message, tooltip):
# a general porpuse function for displaying extended info about an item
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, message_format = message)
dialog.set_title(tooltip)
dialog.run()
dialog.destroy()
def create_image_info(self, parent, tooltip, message=""):
# a function for creating tootip and clickable extended help
eb = gtk.EventBox()
img = gtk.Image()
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'b_info.png')
img.set_from_file(image_file)
eb.add(img)
if len(message):
eb.connect("button-press-event", self.show_info_message, message, tooltip)
tooltip += self._("click_to_see_more")
img.set_tooltip_text(tooltip)
img.set_has_tooltip(True)
parent.pack_start(eb, False, False)
def network_sync_ssl_server_trust_prompt(self, trust_dict):
# function for providing ssl certificate, if necessary
return True, 3, True
def network_sync_get_login(self, realm, username, may_save):
# function for providing account info for network trial, if necessary
self.get_repo_login()
return self.network_sync_dict['auth'], self.network_sync_user, self.network_sync_pw, True
def network_sync_chk_toggled(self, chk, data=None):
# network sync checkbox toggled
# if it goes active, display the network sync dialog
if not chk.get_active():
self.network_sync_dict['sync'] = False
return
# building the dialog
dlg = gtk.Dialog(title= self._('network_sync'),
parent=self.window,
flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dlg.set_default_response(gtk.RESPONSE_APPLY)
dlg.set_has_separator(True)
lbl = gtk.Label(self._('enter_base_url'))
lbl.set_line_wrap(True)
dlg.vbox.pack_start(lbl)
sep = gtk.HSeparator()
dlg.vbox.pack_start(sep)
hb = gtk.HBox(False)
lbl = gtk.Label(self._('repository_url'))
hb.pack_start(lbl, False, False)
# base usrl of the repository for network sync
url = gtk.Entry()
if self.network_sync_dict.has_key('url'):
url.set_text(self.network_sync_dict['url'])
hb.pack_start(url, True, True)
dlg.vbox.pack_start(hb)
auth = gtk.CheckButton(self._('requires_authentication'))
auth.set_active(True)
dlg.vbox.show_all()
controls = url, auth, chk
# event function for different dialog responses
dlg.connect('response', self.network_sync_dialog_respnse, controls)
dlg.run()
def network_sync_dialog_respnse(self, dialog, response_id, controls):
# if cancel ot close, unset the network sync checkbox
if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
controls[-1].set_active(False)
dialog.hide()
return
# an apply response
url, auth, chk = controls
# url can not be empty
if url.get_text() == '':
dialog.set_focus(url)
return
# setting the sync dict
self.network_sync_dict['sync'] = True
# trailing slashes abort the program suddenly and print
# "svn_path_is_canonical(path, pool)" to the sdout
# so this is to resolve this problem
self.network_sync_dict['url'] = url.get_text().strip('/')
self.network_sync_dict['auth'] = auth.get_active()
dialog.hide()
def get_repo_login(self):
# return if not authentication required
if not self.network_sync_dict['auth']: return False
# building the dialog for entering user and pw
dlg = gtk.Dialog(title= self._('network_login'),
parent=self.window,
flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
dlg.set_default_response(gtk.RESPONSE_OK)
dlg.set_has_separator(True)
lbl = gtk.Label(self._('enter_user_pw').format(self.network_sync_dict['url']))
dlg.vbox.pack_start(lbl)
hb = gtk.HBox(False)
lbl = gtk.Label(self._('username') + ': ')
hb.pack_start(lbl, False, False)
user = gtk.Entry()
user.set_text(self.network_sync_user)
hb.pack_start(user, True, True)
dlg.vbox.pack_start(hb)
hb = gtk.HBox(False)
lbl = gtk.Label(self._('password') + ': ')
hb.pack_start(lbl, False, False)
pw = gtk.Entry()
pw.set_visibility(False)
pw.set_text(self.network_sync_pw)
hb.pack_start(pw, True, True)
dlg.vbox.pack_start(hb)
dlg.vbox.show_all()
controls = user, pw
dlg.connect('response', self.get_repo_login_respnse, controls)
controls = user, pw, dlg
# either of two textboxes may be pressed by enter key
user.connect('activate', self.user_pw_event, controls)
pw.connect('activate', self.user_pw_event, controls)
dlg.run()
def user_pw_event(self, entry, controls):
# event function for enter key press in user or pw textboxes
user, pw, dialog = controls
if user.get_text() == '':
dialog.set_focus(user)
return
if pw.get_text() == '':
dialog.set_focus(pw)
return
self.network_sync_user = user.get_text()
self.network_sync_pw = pw.get_text()
dialog.hide()
def get_repo_login_respnse(self, dialog, response_id, controls):
# event function for clicking login dialog button or closing it
if response_id in (gtk.RESPONSE_CANCEL, gtk.RESPONSE_DELETE_EVENT):
dialog.hide()
self.network_sync_cancel_command = True
return
user, pw = controls
if user.get_text() == '':
dialog.set_focus(user)
return
if pw.get_text() == '':
dialog.set_focus(pw)
return
self.network_sync_user = user.get_text()
self.network_sync_pw = pw.get_text()
dialog.hide()
def variable_treeview_row_activated(self, treeview, path, view_column, data=None):
# event function for editing a variable
if self.variable_vbuttonbox.get_property('visible'):
EditVariable(self, path[0])
def filemenu_response(self, widget, data=None):
# this correction is needed, because of different locale data
dot_pos = data.index('.')
data = data[dot_pos+1:]
if data == "new":
self.new_trial_clicked()
elif data == "open":
self.load_trial_clicked()
elif data == "save":
self.save_trial_clicked()
elif data == "refresh":
self.trial_refresh_button(None, None)
elif data == "quit":
self.delete_event(None, None)
elif data == "add":
pass
#self.delete_event(None, None)
def toolmenu_response(self, widget, data=None):
# this correction is needed, because of different locale data
dot_pos = data.index('.')
data = data[dot_pos+1:]
if data == "import":
self.allocations_import_button()
elif data == "export":
self.allocations_export_button()
elif data == "information":
self.trial_info_button_clicked()
elif data == "preferences":
self.pref_clicked()
def helpmenu_response(self, widget, data=None):
# this correction is needed, because of different locale data
dot_pos = data.index('.')
data = data[dot_pos+1:]
if data == "help":
self.notebook.set_current_page(6)
elif data == "about":
dialog = gtk.AboutDialog()
dialog.set_name("MinimPy Program")
dialog.set_version("0.3")
dialog.set_copyright("Copyright (c) 2010-2011 Mahmoud Saghaei")
dialog.set_license("Distributed under the GNU GPL v3.\nFor full terms refer to http://www.gnu.org/copyleft/gpl.html.")
dialog.set_website("http://minimpy.sourceforge.net")
dialog.set_authors(["Mahmoud Saghaei"])
dialog.set_logo(self.pixbuf)
dialog.run()
dialog.destroy()
return False
def addmenu_response(self, widget, data=None):
# this correction is needed, because of different locale data
dot_pos = data.index('.')
data = data[dot_pos+1:]
if data == "group":
self.notebook.set_current_page(1)
if self.group_vbuttonbox.get_property("visible"):
self.group_add_button(None, None)
self.window.set_focus(self.group_treeview)
elif data == "variable":
self.notebook.set_current_page(2)
if self.variable_vbuttonbox.get_property("visible"):
self.variable_add_button(None, None)
self.window.set_focus(self.variable_treeview)
elif data == "allocation":
self.notebook.set_current_page(3)
self.allocations_add_button(None, None)
elif data == "trial_property":
self.notebook.set_current_page(0)
self.trial_properties_add_button(None, None)
self.window.set_focus(self.trial_properties_treeview)
def __init__(self):
# restart only after locale change
self.restart = False
# reading local configuration
self.config_file = os.path.join(os.path.dirname(sys.argv[0]), 'config.cfg')
self.config = ConfigParser.RawConfigParser()
self.config.read(self.config_file)
# setting the interface direction
if self.config.get('interface', 'layout_dir') == 'rtl':
gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
elif self.config.get('interface', 'layout_dir') == 'ltr':
gtk.widget_set_default_direction(gtk.TEXT_DIR_LTR)
# loading locale specific translatable strings into a dict
fp = open(os.path.join(os.path.dirname(sys.argv[0]), 'locale', self.config.get('interface', 'locale'), 'locale.dat'), 'rb')
self.tr_dict = pickle.load(fp)
fp.close()
# addin some stock items
self.factory = gtk.IconFactory()
self.factory.add_default()
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'undo-last.png')
functions.add_icon('UNDO_LAST', self._('undo_last'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'import.png')
functions.add_icon('IMPORT', self._('import'), image_file, self.factory)
gtk.STOCK_IMPORT = 'IMPORT'
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'export.png')
functions.add_icon('EXPORT', self._('export'), image_file, self.factory)
gtk.STOCK_EXPORT = 'EXPORT'
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'random-case.png')
functions.add_icon('RANDOM_CASE', self._('random_case'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'add-all.png')
functions.add_icon('ADD_ALL', self._('add_all'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'start-edit.png')
functions.add_icon('START_EDIT', self._('start_edit'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'clear-refresh.png')
functions.add_icon('CLEAR_REFRESH', self._('clear_refresh'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-apply.png')
functions.add_icon(gtk.STOCK_APPLY, self._('apply'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-cancel.png')
functions.add_icon(gtk.STOCK_CANCEL, self._('cancel'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-apply.png')
functions.add_icon(gtk.STOCK_OK, self._('ok'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'network-transmit-receive.png')
functions.add_icon(gtk.STOCK_CONNECT, self._('connected'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'list-add.png')
functions.add_icon(gtk.STOCK_ADD, self._('add'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'edit-delete.png')
functions.add_icon(gtk.STOCK_DELETE, self._('delete'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'document-new.png')
functions.add_icon(gtk.STOCK_NEW, self._('new'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'document-open.png')
functions.add_icon(gtk.STOCK_OPEN, self._('open'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'document-save.png')
functions.add_icon(gtk.STOCK_SAVE, self._('save'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'preferences-system.png')
functions.add_icon(gtk.STOCK_PREFERENCES, self._('preferences'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-information.png')
functions.add_icon(gtk.STOCK_INFO, self._('information'), image_file, self.factory)
gtk.STOCK_INFORMATION = gtk.STOCK_INFO
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'gtk-edit.png')
functions.add_icon(gtk.STOCK_EDIT, self._('edit'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'edit-clear.png')
functions.add_icon(gtk.STOCK_CLEAR, self._('clear'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'help-about.png')
functions.add_icon(gtk.STOCK_ABOUT, self._('about'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'network-offline.png')
functions.add_icon(gtk.STOCK_DISCONNECT, self._('disconnect'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-cancel.png')
functions.add_icon(gtk.STOCK_CLOSE, self._('close'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-cancel.png')
functions.add_icon(gtk.STOCK_NO, self._('no'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'dialog-apply.png')
functions.add_icon(gtk.STOCK_YES, self._('yes'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'view-refresh.png')
functions.add_icon(gtk.STOCK_REFRESH, self._('refresh'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'print.png')
functions.add_icon(gtk.STOCK_PRINT, self._('print'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'quit.png')
functions.add_icon(gtk.STOCK_QUIT, self._('quit'), image_file, self.factory)
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'date.png')
gtk.STOCK_DATE = 'gtk.STOCK_DATE'
functions.add_icon(gtk.STOCK_DATE, self._('date'), image_file, self.factory)
self.used_temp_files = []
# persisting the working directory
self.file_chooser_current_folder = os.getcwd()
# if this become true, the network_sync_cancel function will terminate the current connecting attempt
self.network_sync_cancel_command = False
# the default random number generator. This can be chnaged in the preferences
self.random = functions.get_app_random(self.config)
# setting the trial file name, based on the program configuration, to either the last one or to None
if self.config.getboolean('project', 'load_recent'):
self.trial_file_name = self.config.get('project', 'recent_trial')
else:
self.trial_file_name = None
# setting info for each tab. Switching the pages will display this in the statusbar
self.notbook_tabs = []
# unique identifier of each allocation from this pool
self.ui_pool = []
# optional preloading of trial with an already allocated sample. The default is and empty table
self.initial_freq_table = False
# empy list of allocations
self.allocations = []
# sync = true: use network syncing, url is the repository url, auth = true: authentication required
self.network_sync_dict = dict(sync=False, url='', auth=False)
# user and pw of the repository when auth = true
self.network_sync_user = ''
self.network_sync_pw = ''
# gtk window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("delete_event", self.delete_event)
self.window.set_border_width(2)
# window size will ne near maximal depending on the screen resolution. No maximize (problem in some Linuxs)
self.window.set_size_request(int(0.99 * gtk.gdk.screen_width()), int(0.85 * gtk.gdk.screen_height()))
# required modlues: most are installed by default. Exceptions may be: pygtk, gtk, gobject, pysvn
module_list = ['os', 'sys', 'pickle', 'tempfile', 'ConfigParser', 'shutil', 'time', 'math', 'random', 'pygtk', 'gtk', 'gobject', 'pickle', 'pysvn']
# a function to check the dependency and displaying an error dialog if missing. This may be useless if
# the program can not display the dialog due to lack of gtk ad related. May be it is better to use
# python's intrinsic GUI classes and functions (tkinter) for this purpose
ret = functions.check_dependencies(module_list)
if ret:
msg = self._('required_module_msq').format('\t'.join(ret))
functions.error_dialog(self.window, msg, self._('module_not_found'))
self.window.destroy()
gtk.main_quit()
# a dialog to display when syncing
label = gtk.Label("")
label.show()
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
dialog.set_title("")
dialog.vbox.pack_end(label)
self.network_sync_dialog = dialog
self.network_sync_dialog_label = label
self.variable_combos_dialog = self.build_variable_combos_dialog()
# interface notebook
self.accel_group = gtk.AccelGroup()
self.window.add_accel_group(self.accel_group)
menu_items = ("New:<Control>N", "Open:<Control>O", "-", "Save:<Control>S", "-", "Refresh:F5", "-", "Quit:<Control>Q")
file_item = functions.create_menu(self._("_file"), menu_items, self.accel_group, self.filemenu_response)
menu_items = ("Import:<Control>M", "Export:<Control>E", "-", "Information:<Control>I", "-", "Preferences:<Control>R")
tool_item = functions.create_menu(self._("_tools"), menu_items, self.accel_group, self.toolmenu_response)
menu_items = ("Help:F1", "-", "_About")
help_item = functions.create_menu(self._("_help"), menu_items, self.accel_group, self.helpmenu_response)
menu_bar = gtk.MenuBar()
menu_bar.append(file_item)
menu_bar.append(tool_item)
menu_bar.append(help_item)
self.top_menu_bar_hbox = gtk.HBox(False, 2)
self.top_menu_bar_hbox.pack_start(menu_bar, True, True)
toolbar = gtk.Toolbar()
tool_button = functions.add_tool_button(toolbar, self._("add"), gtk.STOCK_ADD, self.filemenu_response, "file.add")
self.top_menu_bar_hbox.pack_start(toolbar, True, True)
menu_items = ("Allocation:<Control>A", "Group:<Control>G", "Variable:<Control>V", "Trial Property:<Control>T")
add_item = functions.create_menu(self._("_add"), menu_items, self.accel_group, self.addmenu_response)
submenu = add_item.get_submenu()
add_item.remove_submenu()
tool_button.set_menu(submenu)
tool_button.connect('clicked', self.allocations_add_button)
self.notebook = gtk.Notebook()
# tab position preference
self.notebook.set_tab_pos(self.config.getint('interface', 'tab_pos'))
# right clicking and displaying a manu composed of tabs
self.notebook.popup_enable()
# switching the pages bring something depend on the page
self.notebook.connect("switch-page", self.notebook_switch_page_event)
# program logo
img = gtk.Image()
image_file = os.path.join(os.path.dirname(sys.argv[0]), 'images', 'logo.png')
img.set_from_file(image_file)
img.show()
self.pixbuf = img.get_pixbuf()
# main container for notebook and statusbar
win_vbox = gtk.VBox(False)
win_vbox.pack_start(self.top_menu_bar_hbox, False, False)
win_vbox.pack_start(self.notebook, True, True)
# a container for statusbar and network sync icon
hb = gtk.HBox(False)
self.statusbar = gtk.Statusbar()
hb.pack_start(self.statusbar, True, True)
# progressbar showing the progress of trial
self.allocations_progressbar = gtk.ProgressBar()
if self.config.get('interface', 'layout_dir') == 'rtl':
self.allocations_progressbar.set_orientation(gtk.PROGRESS_RIGHT_TO_LEFT)
elif self.config.get('interface', 'layout_dir') == 'ltr':
self.allocations_progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
hb.pack_start(self.allocations_progressbar, True, True)
# container for network syncing
icon_box = gtk.HBox(False)
self.network_sync_icon = gtk.Image()
self.network_sync_icon.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
self.network_sync_icon.set_tooltip_text(self._('network_sync_enabled'))
icon_box.pack_start(self.network_sync_icon, False, False)
hb.pack_start(icon_box, False, False)
win_vbox.pack_start(hb, False, False, 0)
# setting the statusbar context id. This will be used when displaying text on statusbar
self.sb_context_id = self.statusbar.get_context_id("Statusbar")
# container for trial title and sample size
nb_vbx = gtk.VBox(False)
hbx1 = gtk.HBox(False)
label = gtk.Label(self._("trial_title") + ": ")
hbx1.pack_start(label, False, False)
# a compact function to set an informative icon for tooltip and further help
self.create_image_info(hbx1, self._("trial_title"), self._("trial_title_info"))
# textbox for trial title
self.trial_title_entry = gtk.Entry()
hbx1.pack_start(self.trial_title_entry, True, True)
# label and spin button for sample size
label = gtk.Label(self._("sample_size") + ": ")
hbx1.pack_start(label, False, False)
self.create_image_info(hbx1, self._("sample_size"), self._("sample_size_info"))
# an adjustment object for sample size spin button
adj = gtk.Adjustment(value=30, lower=5, upper=1000000, step_incr=1, page_incr=10)
self.trial_sample_size_spin = gtk.SpinButton(adj)
hbx1.pack_start(self.trial_sample_size_spin, False, False)
nb_vbx.pack_start(hbx1, False, False)
# next row is the trial discription
hbx2 = gtk.HBox(False)
label = gtk.Label(self._("description") + ": ")
hbx2.pack_start(label, False, False)
self.create_image_info(hbx2, self._("trial_description"), self._("trial_description_info"))
nb_vbx.pack_start(hbx2, False, False)
# horizontal separator line
sep = gtk.HSeparator()
nb_vbx.pack_start(sep, False, False)
hbx3 = gtk.HBox(False)
sep = gtk.VSeparator()
hbx3.pack_start(sep, False, False)
self.trial_description_text = gtk.TextView()
hbx3.pack_start(self.trial_description_text, True, True)
sep = gtk.VSeparator()
hbx3.pack_start(sep, False, False)
nb_vbx.pack_start(hbx3, True, True)
sep = gtk.HSeparator()
nb_vbx.pack_start(sep, False, False)
# setting the probability method radios
hbx4 = gtk.HBox(False)
nb_vbx.pack_start(hbx4, True, True)
label = gtk.Label(self._("probability_method") + ": ")
hb = gtk.HBox(False)
hb.pack_start(label, False, False)
self.create_image_info(hb, self._("probability_method"), self._("probability_method_info"))
# biased coin
vbox_prob = gtk.VBox(False)
vbox_prob.pack_start(hb, False, False)
radio = gtk.RadioButton(None, label= self._("biased_coin_minimization"))
vbox_prob.pack_start(radio, False, False)
# naive
radio = gtk.RadioButton(radio, label= self._("naive_minimization"))
vbox_prob.pack_start(radio, False, False)
# this method returns the radios in revese order
self.prob_method_radios = radio.get_group()
# so we need to invert the returned list
self.prob_method_radios.reverse()
# the value of high probability for the group with the least allocation ratio
hb = gtk.HBox(False)
lbl = gtk.Label(self._("high_probability") + ": ")
hb.pack_start(lbl, False, False)
self.create_image_info(hb, self._("high_probability_tip"), self._("high_probability_info"))
# adjustment object for the high probabilty spin button
adj = gtk.Adjustment(value=0.7, lower=0.1, upper=1.0, step_incr=0.01, page_incr=0.1)
self.high_prob_spin = gtk.SpinButton(adj, digits=2)
hb.pack_start(self.high_prob_spin, False, False)
vbox_prob.pack_start(hb, False, False)
hbx4.pack_start(vbox_prob, False, False)
sep = gtk.VSeparator()
hbx4.pack_start(sep, False, False)
# distance measure
label = gtk.Label(self._("distance_measure") + ": ")
hb = gtk.HBox(False)
hb.pack_start(label, False, False)
self.create_image_info(hb, self._("distance_measure_tip"))
vbox = gtk.VBox(False)
vbox.pack_start(hb, False, False)
# marginal balance
radio = gtk.RadioButton(None, label= self._("marginal_balance") + ": ")
hb = gtk.HBox(False)
hb.pack_start(radio, False, False)
self.create_image_info(hb, self._("marginal_balance"), self._("marginal_balance_info"))
vbox.pack_start(hb, False, False)
# range
radio = gtk.RadioButton(radio, label= self._("range") + ": ")
hb = gtk.HBox(False)
hb.pack_start(radio, False, False)
vbox.pack_start(hb, False, False)
self.create_image_info(hb, self._("range"), self._("range_info"))
# SD
radio = gtk.RadioButton(radio, label= self._("standard_deviation") + ": ")
hb = gtk.HBox(False)
hb.pack_start(radio, False, False)
vbox.pack_start(hb, False, False)
self.create_image_info(hb, self._("standard_deviation"), self._("standard_deviation_info"))
# variance
radio = gtk.RadioButton(radio, label= self._("variance") + ": ")
hb = gtk.HBox(False)
hb.pack_start(radio, False, False)
vbox.pack_start(hb, False, False)
self.create_image_info(hb, self._("variance"), self._("variance_info"))
hbx4.pack_start(vbox, False, False)
self.distance_measure_radios = radio.get_group()
self.distance_measure_radios.reverse()
sep = gtk.VSeparator()
hbx4.pack_start(sep, False, False)
# miscelaneous trial properties
vbox = gtk.VBox(False)
lbl = gtk.Label(self._("trial_properties") + ": ")
hb = gtk.HBox(False)
hb.pack_start(lbl, False, False)
vbox.pack_start(hb, False, False)
self.create_image_info(hb, self._("trial_properties"), self._("trial_properties_info"))
hb = gtk.HBox(False)
self.trial_properties_liststore, self.trial_properties_treeview = functions.make_treeview(
(str, str), [self._('name'), self._('value')],
editable=True, edit_handler=self.trial_properties_cell_edited)
functions.make_scrolling(self.trial_properties_treeview, hb)
vbuttonbox = gtk.VButtonBox()
vbuttonbox.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, gtk.STOCK_ADD)
button.connect("clicked", self.trial_properties_add_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DELETE)
button.connect("clicked", self.trial_properties_delete_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DATE)
button.connect("clicked", self.trial_properties_date_button)
vbuttonbox.pack_start(button, False, False)
hb.pack_start(vbuttonbox, False, False)
vbox.pack_start(hb, False, False)
hbx4.pack_start(vbox, True, True)
sep = gtk.VSeparator()
hbx4.pack_start(sep, False, False)
sep = gtk.HSeparator()
nb_vbx.pack_start(sep, False, False)
# container for buttons in the lower edge of the first notebook page
hbuttonbox = gtk.HButtonBox()
hbuttonbox.set_layout(gtk.BUTTONBOX_START)
self.network_sync_chk = gtk.CheckButton(self._('network_sync'))
self.network_sync_chk.set_sensitive(False)
self.network_sync_chk_event_id = self.network_sync_chk.connect("toggled", self.network_sync_chk_toggled)
hbx1.pack_start(self.network_sync_chk, False, False)
# pysvn module is needed for syncing
self.network_sync_chk.set_sensitive(True)
# till here was the settings
lbl = gtk.Label(self._("settings_tab"))
self.notbook_tabs.append(self._("settings_tab_info"))
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
sw.add_with_viewport(nb_vbx)
self.notebook.append_page(sw, lbl)
# next tab is to manage trial groups
hbox = gtk.HBox(False)
# each group has a name and an allocation ration
# table listing showing the group info is editable
column_types = (gobject.TYPE_STRING, gobject.TYPE_INT)
column_names = (self._('group_name'), self._('allocation_ratio'))
liststore = gtk.ListStore(*column_types)
treeview = gtk.TreeView(liststore)
treeview.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
for n in range(len(column_names)):
if n == 0:
cell = gtk.CellRendererText()
elif n == 1:
cell = gtk.CellRendererSpin()
adj = gtk.Adjustment(value=1, lower=1, upper=100, step_incr=1, page_incr=2)
cell.set_property('adjustment', adj)
cell.set_property('editable', True)
cell.connect("edited", self.group_cell_edited, n)
tvcolumn = gtk.TreeViewColumn(self._('group_name'), cell, text=n)
treeview.append_column(tvcolumn)
tvcolumn.set_resizable(True)
tvcolumn.set_expand(True)
self.group_liststore = liststore
self.group_treeview = treeview
vb = gtk.VBox(False)
self.create_image_info(vb, self._('group_table'), self._('group_table_info'))
functions.make_scrolling(self.group_treeview, vb)
hbox.pack_start(vb, True, True)
# add and delete buttons
vbuttonbox = gtk.VButtonBox()
vbuttonbox.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, gtk.STOCK_ADD)
button.connect("clicked", self.group_add_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DELETE)
button.connect("clicked", self.group_delete_button)
vbuttonbox.pack_start(button, False, False)
hbox.pack_start(vbuttonbox, False, False)
lbl = gtk.Label(self._('groups_tab'))
self.notbook_tabs.append(self._("groups_tab_info"))
self.group_vbuttonbox = vbuttonbox
self.notebook.append_page(hbox, lbl)
# next tab is trial variables tab (prognostic factors)
hbox = gtk.HBox(False)
# list is editable. each variable has a name, a weight and some levels
self.variable_liststore, self.variable_treeview = functions.make_treeview(
(str, float, str), [self._('variable_name'), self._('weight'), self._('levels')],
editable=False)
self.variable_treeview.connect('row-activated', self.variable_treeview_row_activated)
# make the third col uneditable. So the edit is only via EditVariable class
vb = gtk.VBox(False)
self.create_image_info(vb, self._("variable_table"), self._("variable_table_info"))
functions.make_scrolling(self.variable_treeview, vb)
hbox.pack_start(vb, True, True)
# buttons for add and delete variables
vbuttonbox = gtk.VButtonBox()
vbuttonbox.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, gtk.STOCK_ADD)
button.connect("clicked", self.variable_add_button)
vbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DELETE)
button.connect("clicked", self.variable_delete_button)
vbuttonbox.pack_start(button, False, False)
hbox.pack_start(vbuttonbox, False, False)
lbl = gtk.Label(self._('variables_tab'))
self.notbook_tabs.append(self._("variables_tab_info"))
self.variable_vbuttonbox = vbuttonbox
self.notebook.append_page(hbox, lbl)
hbox = gtk.HBox(False)
vbox = gtk.VBox(False)
# next tab is to display allocation management. Minimization perform here
vb = gtk.VBox(False)
self.create_image_info(vb, self._("allocations_table"), self._("allocations_table_info"))
hb_button_box = gtk.HBox()
# button for bacth allocation (research uses): Add all, random case and clear the list
self.hbuttonbox_batch_mode = gtk.HButtonBox()
self.hbuttonbox_batch_mode.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, "ADD_ALL")
button.connect("clicked", self.allocations_add_all_button)
self.hbuttonbox_batch_mode.pack_start(button, False, False)
button = gtk.Button(None, "RANDOM_CASE")
button.connect("clicked", self.random_case_button)
self.hbuttonbox_batch_mode.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_CLEAR)
button.connect("clicked", self.allocations_clear_button)
self.hbuttonbox_batch_mode.pack_start(button, False, False)
hb_button_box.pack_start(self.hbuttonbox_batch_mode, True, True)
# normal button for adding and deleting subjects
hbuttonbox = gtk.HButtonBox()
hbuttonbox.set_layout(gtk.BUTTONBOX_START)
button = gtk.Button(None, gtk.STOCK_ADD)
button.connect("clicked", self.allocations_add_button)
hbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_DELETE)
button.connect("clicked", self.allocations_delete_button)
hbuttonbox.pack_start(button, False, False)
button = gtk.Button(None, gtk.STOCK_REFRESH)
button.connect("clicked", self.trial_refresh_button)
hbuttonbox.pack_start(button, False, False)
hb_button_box.pack_start(hbuttonbox, True, True)
vb.pack_start(hb_button_box, False, False)
# allocation list is editable, in case some error occured
self.allocations_treeview = gtk.TreeView()
self.allocations_treeview.connect('row-activated', self.allocations_edit_event)
functions.make_scrolling(self.allocations_treeview, vb)
hbox.pack_start(vb, True, True)
#self.combo_vbox = gtk.VBox(False)
#vbox.pack_start(self.combo_vbox, False, False)
hbox.pack_start(vbox, False, False)
lbl = gtk.Label(self._('allocations_tab'))
self.notbook_tabs.append(self._('allocations_tab_info'))
self.notebook.append_page(hbox, lbl)
# next tab is the subjects frequency table
vbox = gtk.VBox(False)
self.create_image_info(vbox, self._("frequency_table"), self._("frequency_table_info"))
self.freq_table_treeview = gtk.TreeView()
functions.make_scrolling(self.freq_table_treeview, vbox)
self.initial_table_hbox = gtk.HBox(False)
# buttons for editing and setting the initial frequency table (preloading the allocation)
self.freq_table_enable_edit_button = gtk.Button(None, "START_EDIT")
self.freq_table_enable_edit_button.connect("clicked", self.freq_table_start_edit_clicked)
self.initial_table_hbox.pack_start(self.freq_table_enable_edit_button, False, False)
button = gtk.Button(None, "CLEAR_REFRESH")
button.connect("clicked", self.freq_table_delete_initial_clicked)
self.initial_table_hbox.pack_start(button, False, False)
vbox.pack_start(self.initial_table_hbox, False, False)
lbl = gtk.Label(self._('table_tab'))
self.notbook_tabs.append(self._("table_tab_info"))
self.notebook.append_page(vbox, lbl)
# next tab is the balance tab, showing the trial balance in different scales for different trial items
hbox = gtk.HBox(False)
vb = gtk.VBox(False)
self.create_image_info(vb, self._("balance_table"), self._("balance_table_info"))
treestore = gtk.TreeStore(str, float, float, float, float)
self.balance_table_treeview = gtk.TreeView(treestore)
col_names = [self._('variable_level'), self._('marginal_balance'), self._('range'), self._('variance'), 'SD']
for i in range(5):
cell = gtk.CellRendererText()
column = gtk.TreeViewColumn(col_names[i], cell, text=i)
self.balance_table_treeview.append_column(column)
functions.make_scrolling(self.balance_table_treeview, vb)
hbox.pack_start(vb, True, True)
lbl = gtk.Label(self._('balance_tab'))
self.notbook_tabs.append(self._("balance_tab_info"))
self.notebook.append_page(hbox, lbl)
# next is the help and about tab
hbox = gtk.HBox(True)
self.about_text = gtk.TextView()
self.about_text.set_wrap_mode(gtk.WRAP_WORD)
self.about_text.set_editable(False)
self.about_text.set_cursor_visible(False)
self.about_text.set_left_margin(20)
self.about_text.set_right_margin(20)
about_text = self._('about_text')
functions.set_text_buffer(self.about_text, about_text)
functions.make_scrolling(self.about_text, hbox)
self.add_quick_help_content()
self.notbook_tabs.append(self._("help_tab_info"))
lbl = gtk.Label(self._('help_tab'))
self.notebook.append_page(hbox, lbl)
vb = gtk.VBox(True, spacing=5)
self.notebook.set_show_tabs(True)
self.window.add(win_vbox)
self.window.show_all()
# if there is a previous trial to load
if self.trial_file_name:
# loading the last trial
self.waiting_function(self.load_trial, (self.trial_file_name,))
if not self.trial_file_name:
# usuallay load error will handel in the loading function. This is as a last backup
functions.error_dialog(self.window, self._('load_error_msg'))
# so start a new trial
self.set_new_trial()
else:
# no previous trial, or not according to configuration
self.set_new_trial()
# hide the research tools if not indicated in the config
if not self.config.getboolean('interface', 'batch_allocation'):
self.hbuttonbox_batch_mode.hide()
def add_quick_help_content(self):
# this function adds content to the help text view
# address of help file
file_name = os.path.join('doc', 'index.info')
# a general function for adding texts and images to text views
functions.textview_from_file(file_name, self.about_text)
def allocations_edit_event(self, tw, path, col, data=None):
# a function for editing allocations. Main indications are when
# a subject enrolled but received a different treatment (by error) than the one
# determined by minimization. Another is when the incorrect subjects data has been entered
# first determinign the UI of the selected subject.
model = self.allocations_treeview.get_model()
row = path[0]
ui = int(model[row][1])
if self.network_sync_dict['sync'] and self.trial_file_name:
# if network sync, first check out a have an updated local copy
save_path = self.update_network_trial()
else:
save_path = self.trial_file_name
model = self.allocations_treeview.get_model()
# this updated model may be different from the one before update
if not model or len(model) == 0:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_no_subject_allocated"))
return False
# another user may have deleted the selcted subject
for case in self.allocations:
if case['UI'] == ui:
break
else:
functions.error_dialog(self.window, self._('non_updated_data'), self._('data_not_updated'))
return False
# Edit the subject
model.set_sort_column_id(0, gtk.SORT_ASCENDING)
EditAllocation(self, ui, save_path)
def allocations_import(self):
# importing a file containing previously allocated subject (by any method)
if self.network_sync_dict['sync'] and self.trial_file_name:
# have an update
repo_path = self.update_network_trial()
# updated model
model = self.allocations_treeview.get_model()
# empty model
if not model:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_groups_prognostic_factors_must_be_defined"))
return False
# trial ended or not initialized
if not self.ui_pool:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._('statusbar_trial_finished_or_not_saved'))
return False
# import file
file_name = self.select_file(self._("select_file"), gtk.FILE_CHOOSER_ACTION_OPEN)
if not file_name:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_import_canceled"))
return False
# lines
rows = open(file_name).readlines()
# empty file
if not rows:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_empty_file"))
return False
# working of each line
for cnt, row in enumerate(rows):
# work till the end of ui pool
if len(self.ui_pool) == 0:
# give the final success message and go for save
msg = '{0} record{1} imported'.format(cnt, ('', 's')[cnt>0])
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_OK, message_format = msg)
dialog.set_title(self._("finished_importing"))
dialog.run()
dialog.destroy()
break
try:
# each line is a record of fields separated by commas
row = map(str.strip, row.split(','))[2:]
# first field is the group. It must be numeric
group = row[0]
if not group.isdigit():
raise Exception, self._('bad_file_format')
group = int(group)
row = row[1:]
# number of remaining fields must be the same as number of variables
if len(row) != len(self.variable_combos):
raise Exception, self._('bad_file_format')
# all must be digits
if not all(map(str.isdigit, row)):
raise Exception, self._('bad_file_format')
# capturing remaining fields
for idx, level in enumerate(row):
cbo = self.variable_combos[idx]
cbo.set_active(int(level))
model.append()
# consume one ui for each record
ui = self.ui_pool.pop()
# building the new case to add to allocations
new_case = {'levels': [], 'allocation': -1, 'UI': ui}
row = len(model)-1
# building the model. sequence and ui of the record
model[row][0] = row
UI_len = len(str(self.trial_sample_size_spin.get_value_as_int()-1))
model[row][1] = str(ui).zfill(UI_len)
# adding variable levels to the model and new case
for col, cbo in enumerate(self.variable_combos):
model[row][col+3] = cbo.get_active_text()
new_case['levels'].append(cbo.get_active())
# setting the group of modle and new case
new_case['allocation'] = group
model[row][2] = self.group_liststore[group][0]
# appending the new case to the allocations
self.allocations.append(new_case)
except Exception as err:
# any error will be captured here. Mainly bad file format
msg = self._('error_in_import') + str(err) + self._('original_data_will_resotre')
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_OK, message_format = msg)
dialog.set_title(self._("import_failed"))
dialog.run()
dialog.destroy()
# restoring the original trial if any
if self.trial_file_name:
self.load_trial(self.trial_file_name)
if not self.trial_file_name:
functions.error_dialog(self.window, self._('critical_error_restoring_trial'), self._('trial_restore_failed'))
self.set_new_trial()
else:
# otherwise start a new one
self.set_new_trial()
return
# commiting the changes
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
def allocations_import_button(self):
# event function for importing data
self.waiting_function(self.allocations_import, ())
def allocations_export(self):
# function for export data
# updating
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
self.remove_folder(repo_path)
if not self.trial_file_name:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_save_trial_first"))
return False
# export class
Export(self)
def allocations_export_button(self):
# event function for export
self.waiting_function(self.allocations_export, ())
def trial_info_button_clicked(self):
# getting details and saving into a file
det_file_name = self.save_trial_details_temp()
# view the file in a generic viewer
Viewer(parent=self, file_name=det_file_name)
def pref_clicked(self):
# event function for preferences
# start the PrefWin class
PrefWin(self)
def new_trial_clicked(self):
# we have unsaved data?
if not self.query_trial_dismis():
return False
# start a new trial
self.set_new_trial()
def set_new_trial(self):
# trial name set to empty, clear title, set the sample size to 30, clear the description,
# clear trial properties table, set the high property to 0.7, clear groups,
# variables and allocations, clear frequency and initial frequency table, clear the UI pool,
# clear the network sync parameters, unlock the trial, goto the first (settings) tab
self.trial_file_name = None
self.trial_title_entry.set_text('')
self.trial_sample_size_spin.set_value(30)
functions.set_text_buffer(self.trial_description_text, '')
self.trial_properties_liststore.clear()
self.high_prob_spin.set_value(0.7)
self.prob_method_radios[0].set_active(True)
self.distance_measure_radios[0].set_active(True)
self.group_liststore.clear()
self.variable_liststore.clear()
self.allocations_treeview.set_model()
self.allocations = []
self.freq_table_treeview.set_model()
self.initial_freq_table = False
self.freq_table_treeview.set_model()
self.update_interface()
self.lock_trial(unlock=True)
self.ui_pool = []
self.network_sync_chk.set_active(False)
self.network_sync_dict = dict(sync=False, url='', auth=False)
self.window.set_title(self._('window_untitled'))
self.notebook.set_current_page(0)
self.set_progressbar_status()
def balance_table_refresh(self):
# refreshing the balance table
# update
if self.network_sync_dict['sync'] and self.trial_file_name:
repo_path = self.update_network_trial()
# only update is required, no need for a working copy
self.remove_folder(repo_path)
# getting the frequency data model
liststore = self.freq_table_treeview.get_model()
if not liststore:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_no_allocation"))
return False
# start with an empty table
table = []
for row in range(len(liststore)-1):
# for each group append one row to the table,
# last row in the model is the col totals, so we do not use it
table.append([])
for col in range(1, len(liststore[0])-1):
# each col in the model represent successive levels of veriables
# last col is the row totals, so we do not use it
table[row].append(liststore[row][col])
# populating the table with the balance data
balance = self.get_trial_balances(table)
# first clear the balance table model
treestore = self.balance_table_treeview.get_model()
treestore.clear()
# a list of level lists each for one variable
variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
row = 0
# correcting balances for variable weights
for idx, variable in enumerate(variables):
wt = self.variable_liststore[idx][1]
var_total = [0] * 4
level_rows = []
for level in variable:
for i in range(4):
# here I applied the var weights to the final balance.
# may be a better way to do this
balance[row][i] *= float(wt)
var_total[i] += balance[row][i]
level_rows.append(balance[row])
row += 1
# appending total of balances to the balances, one for each variable
var_total = [self.variable_liststore[idx][0]] + [var_total[i] / len(variable) for i in range(4)]
# populating the model with balance data, begining with total variable balance data
variable_node = treestore.append(None, var_total)
level_names = map(str.strip, self.variable_liststore[idx][2].split(','))
# adding balances for each level under each variable
for level, level_row in enumerate(level_rows):
treestore.append(variable_node, [level_names[level]] + level_row)
# last row is the mean and max
last_row = row
rows = len(balance)-2
for col in range(4):
balance[rows].append(1.0 * sum([balance[row][col] for row in range(rows)]) / rows)
balance[rows+1].append(max([balance[row][col] for row in range(rows)]))
treestore.append(None, [self._('mean')] + balance[last_row])
treestore.append(None, [self._('max')] + balance[last_row+1])
def get_trial_balances(self, table):
# a general dispatching function for obtaining balance for each type of balance measure
# table: input is the counts of different levels in each group
# a Model object for passing to Minim object
model = Model()
# a Minim object for calculating different balances
m = Minim(random=self.random, model=model)
# an emapy list for each level
levels = [[] for col in table[0]]
# two extra list for mean and max
balances = [[] for col in table[0]] + [[], []]
# populating the levels list with count data
for row in table:
for col, value in enumerate(row):
levels[col].append(value)
# a list of allocation ratios
allocation_ratio = [self.group_liststore[r][1] for r in range(len(self.group_liststore))]
for row, level_count in enumerate(levels):
# obtaining adjuted count for each level based on the allocation ratios
adj_count = [(1.0 * level_count[i]) / allocation_ratio[i] for i in range(len(level_count))]
# calculating marignal balance
balances[row].append(m.get_marginal_balance(adj_count))
# range
balances[row].append(max(adj_count) - min(adj_count))
# variance
balances[row].append(m.get_variance(adj_count))
# SD
balances[row].append(m.get_standard_deviation(adj_count))
return balances
def freq_table_disable_edit(self):
# disabling frequency table edit
functions.treeview_disable_edit(self.freq_table_treeview)
def freq_table_enable_edit(self):
# enabling frequency table edit
functions.treeview_enable_edit(self.freq_table_treeview, self.freq_table_treeview_edit_handler)
def freq_table_start_edit_clicked(self, button, data=False):
# enable of disable frequency table edit
# frequency model
initial_freq_model = self.freq_table_treeview.get_model()
# empty model, groups and variables have not been defined yet
if not initial_freq_model:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
return False
if not len(initial_freq_model):
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
return False
# disable or enable, check the button label, then change the button label
if button.get_label() == self._("start_edit"):
self.freq_table_enable_edit()
button.set_label(self._("save_as_initial_table"))
else:
# if the label is 'save_as_initial_table', first check for inconsistencies in
# rows and cols totals. A value of -1 means inconsistency
if initial_freq_model[-1][-1] == -1:
functions.error_dialog(self.window, self._('initial_frequency_table_error'), self._('frequency_table_error'))
return False
# group list
groups = range(len(self.group_liststore))
# list of level lists
variables = [range(len(self.variable_liststore[row][2].split(','))) for row in range(len(self.variable_liststore))]
# initializing a table to hold the frequency data
table = [[[0 for l in v] for v in variables] for g in groups]
for row, group in enumerate(table):
col = 1
for v, variable in enumerate(group):
for l, level in enumerate(variable):
table[row][v][l] = initial_freq_model[row][col]
col += 1
# setting the table as the initial frequency table
self.initial_freq_table = table
# changing the button
button.set_label(self._("start_edit"))
# disabling the edit
self.freq_table_disable_edit()
def freq_table_treeview_edit_handler(self, cell, row, new_text, col):
# an event handler for editing cells of fequency table
# the model
model = self.freq_table_treeview.get_model()
# some cells can not be edited
if (col == 0) or (int(row) == (len(model) - 1)) or (col == (len(model[0]) - 1)):
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_cell_can_not-be_changed"))
return False
# non digit values entered
if not new_text.isdigit():
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_only_interger_values"))
return False
# the value is OK, so set the cell to the value
model[row][col] = int(new_text)
# calculating rows and cols total
col_sum = 0
for r in range(len(model)-1):
col_sum += model[r][col]
model[-1][col] = col_sum
# list of level list
variables = [range(len(self.variable_liststore[r][2].split(','))) for r in range(len(self.variable_liststore) )]
# level list initited to zeros
table_row = [[0 for L in v] for v in variables]
cum_cols = 0
for v, variable in enumerate(table_row):
# cols are successive, so add up to find the current col
cum_cols += len(variable)
# if we reach to the edited col
# if yes, return to the start col of the varable whose cell is edited
if cum_cols >= col:
# cols of this variable
sel_cols = range(cum_cols - len(variable) + 1, cum_cols + 1)
break
# calculating row sum for all cols of this variable (the variable which one of its cols is edited)
row_sum = 0
for c in sel_cols:
row_sum += model[row][c]
# a flag to signal discrepancies in row or col totals
err_sum = False
cum_cols = 0
# all row sums must be equal, otherwise ther is an error in entering values
for v, variable in enumerate(table_row):
# stacking up cols to get into the range of cols for each variable
cum_cols += len(variable)
# list of cols for each variable
sel_cols = range(cum_cols - len(variable) + 1, cum_cols + 1)
# row sum for this cols
row_sum_ext = 0
for c in sel_cols:
row_sum_ext += model[row][c]
# row sums must be equal
if row_sum_ext != row_sum: err_sum = True
# no error! set the total
if not err_sum:
model[row][-1] = row_sum
else:
# error: set the value to -1, to be checkable
model[row][-1] = -1
# total of totals
total = 0
for r in range(len(model)-1):
total += model[r][-1]
# if not error: set the total of totals
if not err_sum:
model[-1][-1] = total
else:
# error: set value to -1
model[-1][-1] = -1
def freq_table_delete_initial_clicked(self, button, data=None):
# delete and refresh the frequency table. useful to apply changes in group and variable settings
# ofcours manually entered frequency data will be lost
initial_freq_model = self.freq_table_treeview.get_model()
# no group and variable has been defined
if not initial_freq_model:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_trial_not_initialized"))
return False
# warn against data loss
msg = self._("warning_initial_frequency_table_delete")
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._("initial_table_delete_refresh"))
if dialog.run() == gtk.RESPONSE_NO:
dialog.destroy()
return False
dialog.destroy()
# refresh the table
self.refresh_freq_table()
# negating initial trial preload
self.initial_freq_table = False
# disabling edit
self.freq_table_disable_edit()
# stting the button label
self.freq_table_enable_edit_button.set_label(self._("start_edit"))
def load_trial_clicked(self):
# event function for trial load
# first check if we have unsaved data
if not self.query_trial_dismis():
return False
# get loading file name
file_name = self.select_file(self._("enter_file_name"), gtk.FILE_CHOOSER_ACTION_OPEN)
# cancel button
if not file_name:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_trial_save_canceled"))
return False
# loading the trial
self.waiting_function(self.load_trial, (file_name,))
def try_network_info_file(self, file_name):
# this function checks whether a file is a valid network trial info file
# network trial info file contains required data for loading the trial over the network
try:
# first open it, any error here means file is not accessible or no accesible content
fp = open(file_name, 'rb')
data = pickle.load(fp)
fp.close()
except:
# file is invalid
return -1
# then checking individual keyword elements
if data.has_key('network_sync') and data.has_key('trial_name'):
# if has two elementary network sync keywords, try to load the trial
self.trial_file_name = file_name
if self.update_network_trial():
# successful, lock the trial
self.lock_trial()
# file is valid and trial loaded
# return success
return 1
else:
# load failed, nothing can be done except starting a new trial
self.set_new_trial()
# file is valid but trial not loaded
# return failure, perhaps the file is invalid
return 0
else:
# necessary keyword are missing, so start a new trial and retrun -1, means lack of keywords
self.set_new_trial()
# file is invalid
return -1
def save_trial_changes(self, save_sample_size=False):
# this function saves minor changes in trial settings (title, description, properties)
# first having a copy of the trial title, description, properties and
# variable combos setting, to set them again after update. Then we can safely save changes
trial_title = self.trial_title_entry.get_text()
trial_description = functions.get_text_buffer(self.trial_description_text)
# saving this UI pool is necessary when changing sample size
sample_size = self.trial_sample_size_spin.get_value()
ui_pool = self.ui_pool
# this list hold the states of cbos
cbo_selects = []
for cbo in self.variable_combos:
cbo_selects.append(cbo.get_active())
# getting trial properties
trial_properties = self.get_trial_properties()
# only if network sync, restore the saved values
if self.network_sync_dict['sync'] and self.trial_file_name:
# updating the trial, this will reset all variable combos, but we have a backup of them
repo_path = self.update_network_trial()
# restoring values to make then ready for save changes
self.trial_title_entry.set_text(trial_title)
functions.set_text_buffer(self.trial_description_text, trial_description)
# only of changing sample size, restore these two values before the update
if save_sample_size:
self.trial_sample_size_spin.set_value(sample_size)
self.ui_pool = ui_pool
for i, cbo in enumerate(self.variable_combos):
cbo.set_active(cbo_selects[i])
self.set_trial_properties(trial_properties)
# finally save changes
if self.network_sync_dict['sync']:
path = repo_path
else:
path = self.trial_file_name
self.save_trial(path)
def save_trial_event(self):
# is this an update or save
if self.trial_file_name:
# so save the changes only
self.save_trial_changes()
return False
if not self.trial_is_valid():
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("trial_not_ready_to_save"))
return False
# asking for the file name
file_name = self.select_file(self._("enter_file_name"), gtk.FILE_CHOOSER_ACTION_SAVE)
# cancel
if not file_name:
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, self._("statusbar_trial_save_canceled"))
return False
# build the UI pool
self.build_ui_pool()
# actual save
self.trial_file_name = self.save_trial(file_name, initial=True)
def save_trial_clicked(self):
# event function for saving trial
self.waiting_function(self.save_trial_event, ())
def set_groups_data(self, groups):
# gathering group liststore data
self.group_liststore.clear()
for group in groups:
self.group_liststore.append((group['name'], group['allocation_ratio']))
def set_variables_data(self, variables):
# setting variable liststore from the supplied data
self.variable_liststore.clear()
for variable in variables:
self.variable_liststore.append((variable['name'], variable['weight'], variable['levels']))
def build_ui_pool(self, lst=None):
# building the UI pool
# if this is an original save, build a new pool
if not lst:
# it's a new save, so build a list containing range of numbers from zero to
# the sample size minus one
ss = self.trial_sample_size_spin.get_value_as_int()
lst = range(ss)
# if this is an increase in sample size, work on the supplied list
# shuffle the list
self.random.shuffle(lst)
# set the final UI pool.
self.ui_pool = lst
def get_trial_properties(self):
# getting trial properties
table = [['', ''] for row in range(len(self.trial_properties_liststore))]
for row in range(len(table)):
for col in range(len(table[0])):
table[row][col] = self.trial_properties_liststore[row][col]
return table
def get_case_properties(self):
# getting case properties
table = [['', ''] for row in range(len(self.case_properties_liststore))]
for row in range(len(table)):
for col in range(len(table[0])):
table[row][col] = self.case_properties_liststore[row][col]
return table
def set_trial_properties(self, table):
# setting the trial propeties liststore from the supplied table
self.trial_properties_liststore.clear()
for row in range(len(table)):
self.trial_properties_liststore.append(table[row])
def trial_is_valid(self, show_msg=True, ret_code=None, table_edit=False):
# checking whether the trial has required data and the data are valid
# trial title
if not self.trial_title_entry.get_text() and not table_edit:
if show_msg:
functions.error_dialog(self.window, self._("trial_title_first"), self._("trial_title"))
self.notebook.set_current_page(0)
self.window.set_focus(self.trial_title_entry)
return False
# in case of network sync check if any invalid character in title
if self.trial_title_entry.get_text():
if self.network_sync_dict['sync']:
title = '_'.join(self.trial_title_entry.get_text().split())[:10]
for char in title:
if char in self.invalid_chars:
if show_msg:
functions.error_dialog(self.window, self._("invalid_character").format(char), self._("trial_title"))
return False
# descript is required, except when editing a table
if not functions.get_text_buffer(self.trial_description_text) and not table_edit:
if show_msg:
functions.error_dialog(self.window, self._("enter_trial_description"), self._("trial_description"))
self.notebook.set_current_page(0)
self.window.set_focus(self.trial_description_text)
return False
# at least two groups are required
if len(self.group_liststore) < 2:
if show_msg:
functions.error_dialog(self.window, self._("two_groups_needed"), self._("trial_groups"))
self.notebook.set_current_page(1)
self.window.set_focus(self.group_treeview)
return False
# at least one variable is required
if len(self.variable_liststore) < 1:
if show_msg:
functions.error_dialog(self.window, self._("prognostic_factor_required"), self._("trial_variables"))
self.notebook.set_current_page(2)
self.window.set_focus(self.variable_treeview)
return False
# check if there is unsaved initial freq table
if self.freq_table_enable_edit_button.get_label() == self._("button_save_as_initial_table"):
if show_msg:
functions.error_dialog(
self.window, self._("initial_frequency_table_not_saved"), self._("frequency_table"))
self.notebook.set_current_page(4)
self.window.set_focus(self.freq_table_treeview)
return False
# final asking to save the rial
if not show_msg: return True
# display trial details and asking confirmation for save
return self.display_trial_details_response()
def save_trial_details_temp(self):
# save a temp file containg trial detains, to be used later in dialogs
details = self._('trial_details') + '\n' + self.get_trial_info()
det_file_name = tempfile.mkstemp(suffix='.info')[1]
self.used_temp_files.append(det_file_name)
fp = open(det_file_name, 'w')
fp.write(details)
fp.flush()
fp.close()
# return the file name
return det_file_name
def display_trial_details_response(self):
# function for displaying trial details and asking for confirmation
msg = self._("want_save_trial")
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._("trial_save"))
det_file_name = self.save_trial_details_temp()
hbb = gtk.HButtonBox()
hbb.show()
# addin a button to display trial details
button = gtk.Button(self._("trial_details"))
button.connect('clicked', self.save_dialog_button_clicked, det_file_name)
button.show()
hbb.pack_start(button)
dialog.vbox.pack_start(hbb)
if dialog.run() == gtk.RESPONSE_YES:
# remove temp file
dialog.destroy()
# save the trial
return True
dialog.destroy()
# don't save
return False
def save_dialog_button_clicked(self, button, file_name):
# event function for dialog button to display trial details
Viewer(parent=self, file_name=file_name)
def remove_temp_file(self, path):
if not os.path.exists(path): return
if os.path.isdir(path):
items = os.listdir(path)
if len(items) == 0:
os.rmdir(path)
else:
for item in items:
self.remove_temp_file(item)
else:
os.remove(path)
def want_trial_unlock(self, prompt=True):
if prompt:
msg = self._("want_unlock_trial")
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._("unlock_trial"))
if dialog.run() == gtk.RESPONSE_NO:
dialog.destroy()
return False
dialog.destroy()
self.lock_trial(unlock=True)
self.ui_pool = []
self.trial_file_name = None
def lock_trial(self, unlock=False):
self.network_sync_chk.set_property("sensitive", unlock)
self.trial_sample_size_spin.set_property("sensitive", unlock)
for radio in self.prob_method_radios:
radio.set_property("sensitive", unlock)
self.high_prob_spin.set_property("sensitive", unlock)
for radio in self.distance_measure_radios:
radio.set_property("sensitive", unlock)
self.group_vbuttonbox.set_property("visible", unlock)
if unlock:
functions.treeview_enable_edit(self.group_treeview)
else:
functions.treeview_disable_edit(self.group_treeview)
self.variable_vbuttonbox.set_property("visible", unlock)
self.initial_table_hbox.set_property("visible", unlock)
self.statusbar.pop(self.sb_context_id)
self.statusbar.push(self.sb_context_id, (self._("trial_locked"), self._("trial_unlocked"))[unlock])
def get_trial_info(self):
ret = []
ret.append(self._("title") + ": " + self.trial_title_entry.get_text())
ret.append(self._("sample_size") + ": " + str(self.trial_sample_size_spin.get_value_as_int()))
if self.network_sync_dict['sync'] and self.network_sync_dict['url']:
ret.append(self._('repository_url') + ' = {0}'.format(self.network_sync_dict['url']))
ret.append(self._('trial_info_file') + ' = {0}'.format(self.trial_file_name))
else:
ret.append(self._('local_trial_file_name') + ' = {0}'.format(self.trial_file_name))
ret.append(self._("description") + ": " + functions.get_text_buffer(self.trial_description_text))
ret.append(self._("probability_method") + ": " + self.get_prob_method_name())
ret.append(self._("distance_measure") + ": " + self.get_distance_measure_name())
ret.append(self._("high_probability") + ": " + str(self.high_prob_spin.get_value()))
ret.append(self._("groups") + ":\n" + str(self.get_groups_info()))
ret.append(self._("variables") + ":\n" + str(self.get_variables_info()))
return '\n'.join(ret)
def load_trial_from_file(self, file_name):
fp = open(file_name, 'rb')
data = pickle.load(fp)
fp.close()
self.ui_pool = data['ui_pool']
self.trial_title_entry.set_text(data['trial_title'])
if len(data['trial_title']) > 60:
trial_title = data['trial_title'][:57] + '...'
else:
trial_title = data['trial_title']
win_title = self._('main_window_title').format(trial_title)
self.window.set_title(win_title)
functions.set_text_buffer(self.trial_description_text, data['trial_description'])
self.set_trial_properties(data['trial_properties'])
self.allocations = data['allocations']
self.trial_sample_size_spin.set_value(data['sample_size'])
self.high_prob_spin.set_value(data['high_prob'])
self.initial_freq_table = data['initial_freq_table']
self.prob_method_radios[data['prob_method']].set_active(True)
self.distance_measure_radios[data['distance_measure']].set_active(True)
self.set_groups_data(data['groups'])
self.set_variables_data(data['variables'])
self.update_interface()
self.set_progressbar_status()
if data.has_key('network_sync'):
# previous versions of data files may not have this field
self.network_sync_dict = data['network_sync']
self.network_sync_chk.handler_block(self.network_sync_chk_event_id)
self.network_sync_chk.set_active(self.network_sync_dict['sync'])
self.network_sync_chk.handler_unblock(self.network_sync_chk_event_id)
def waiting_function(self, func, args):
gdk_cursor = gtk.gdk.Cursor(gtk.gdk.WATCH)
win = gtk.gdk.get_default_root_window()
win.set_cursor(gdk_cursor)
gobject.idle_add(func, *args)
gobject.idle_add(self.exit_waiting, win)
self.network_sync_dialog.show()
def exit_waiting(self, win):
gdk_cursor = gtk.gdk.Cursor(gtk.gdk.ARROW)
win.set_cursor(gdk_cursor)
self.network_sync_dialog.hide()
def load_trial(self, file_name):
# checking the file if this is a network sync info file. If yes, then we checkout and
# load the trial from the checkout
self.network_sync_dialog_label.set_text(self._('please_wait').format(self.network_sync_dict['url']))
ret = self.try_network_info_file(file_name)
self.file_chooser_current_folder = os.path.dirname(file_name)
if ret > 0:
self.network_sync_dialog_label.set_text(self._('network_syncing_wait').format(self.network_sync_dict['url']))
self.config.set('project', 'recent_trial', file_name)
self.notebook.set_current_page(3)
with open(self.config_file, 'wb') as config_file:
self.config.write(config_file)
config_file.flush()
config_file.close()
self.config.read(self.config_file)
return
if ret == 0: return
try:
self.load_trial_from_file(file_name)
self.lock_trial()
self.trial_file_name = file_name
self.notebook.set_current_page(3)
self.config.set('project', 'recent_trial', file_name)
self.notebook.set_current_page(3)
with open(self.config_file, 'wb') as config_file:
self.config.write(config_file)
config_file.flush()
config_file.close()
self.config.read(self.config_file)
except Exception as ex:
functions.error_dialog(self.window, self._("trial_load_failed").format(file_name), self._("error_loading_file"))
self.lock_trial(unlock=True)
self.set_new_trial()
self.trial_file_name = False
def get_svn_client(self):
self.network_sync_cancel_command = False
client = pysvn.Client()
client.callback_cancel = self.network_sync_cancel
client.callback_get_login = self.network_sync_get_login
client.callback_ssl_server_trust_prompt = self.network_sync_ssl_server_trust_prompt
client.callback_notify = self.network_sync_notify
client.set_auth_cache(self.config.getboolean('operations', 'cach_cred'))
client.set_store_passwords(self.config.getboolean('operations', 'cach_cred'))
client.exception_style = 1
return client
def network_sync_notify(self, event_dict):
return
def save_trial_to_file(self, file_name):
data = {}
data['ui_pool'] = self.ui_pool
data['trial_title'] = self.trial_title_entry.get_text()
data['sample_size'] = self.trial_sample_size_spin.get_value_as_int()
data['trial_description'] = functions.get_text_buffer(self.trial_description_text)
data['trial_properties'] = self.get_trial_properties()
data['high_prob'] = self.high_prob_spin.get_value()
data['initial_freq_table'] = self.initial_freq_table
data['prob_method'] = self.get_prob_method()
data['distance_measure'] = self.get_distance_measure()
data['allocations'] = self.allocations
data['groups'] = self.get_groups_data()
data['variables'] = self.get_variables_data()
data['network_sync'] = self.network_sync_dict
fp = open(file_name, 'wb')
pickle.dump(data, fp)
fp.flush()
fp.close()
if len(data['trial_title']) > 60:
trial_title = data['trial_title'][:57] + '...'
else:
trial_title = data['trial_title']
win_title = self._('main_window_title').format(trial_title)
self.window.set_title(win_title)
self.set_progressbar_status()
if self.network_sync_dict['sync']:
if self.config.getboolean('operations', 'backup_network'):
backup_folder_name = self.config.get('operations', 'backup_network_path')
if backup_folder_name:
back_file_name = os.path.join(backup_folder_name, os.path.basename(file_name))
# turning sync off to enable offline opening of the backup file
data['network_sync'] = dict(sync=False, url='', auth=False)
fp = open(back_file_name, 'wb')
pickle.dump(data, fp)
fp.flush()
fp.close()
def save_trial_local(self, file_name):
self.save_trial_to_file(file_name)
self.config.set('project', 'recent_trial', file_name)
with open(self.config_file, 'wb') as config_file:
self.config.write(config_file)
config_file.flush()
config_file.close()
self.config.read(self.config_file)
return file_name
def load_network_trial_info(self):
fp = open(self.trial_file_name, 'rb')
data = pickle.load(fp)
fp.close()
try:
if data.has_key('network_sync'):
self.network_sync_dict = data['network_sync']
else:
raise Exception, self._("trial_info_file_not_valid")
if data.has_key('trial_name'):
trial_name = data['trial_name']
else:
raise Exception, self._("trial_info_file_not_valid")
return trial_name
except Exception as ex:
functions.error_dialog(self.window, self._("network_trial_info_file_problem") + repr(ex), self._("trial_info_file"))
return False
def update_network_trial(self):
# this method checkout the repo, load the trial from it, and then return the local path
if not self.trial_file_name:
self.set_new_trial()
return False
trial_name = self.load_network_trial_info()
if not trial_name:
self.set_new_trial()
return False
try:
client = self.get_svn_client()
url = self.network_sync_dict['url'] + '/' + trial_name
tempfolder = tempfile.mkdtemp()
self.used_temp_files.append(tempfolder)
rev = False
while True:
rev = client.checkout(url, tempfolder)
if rev:
if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
temp_file_name = os.path.join(tempfolder, trial_name)
self.load_trial_from_file(temp_file_name)
return tempfolder
except Exception as ex:
functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
return False
def checkin_trial(self, path):
if not self.trial_file_name:
self.set_new_trial()
return False
trial_name = self.load_network_trial_info()
if not trial_name:
self.set_new_trial()
return False
url = self.network_sync_dict['url'] + '/' + trial_name
file_name = os.path.join(path, trial_name)
self.save_trial_to_file(file_name)
client = self.get_svn_client()
try:
rev = False
while True:
rev = client.checkin(path, time.ctime())
if rev:
if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
stats = client.status(path)
for stat in stats:
if stat.repos_text_status == pysvn.wc_status_kind.modified:
break
else:
break
self.config.set('project', 'recent_trial', self.trial_file_name)
with open(self.config_file, 'wb') as config_file:
self.config.write(config_file)
config_file.flush()
config_file.close()
self.remove_folder(path)
except pysvn.ClientError, e:
for message, code in e.args[1]:
if code == 160024 or 'Conflict' in message:
msg = self._("network_sync_conflict")
dialog = gtk.MessageDialog(self.window, flags = gtk.DIALOG_MODAL, type = gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format = msg)
dialog.set_title(self._("trial_conflict"))
if dialog.run() == gtk.RESPONSE_YES:
dialog.destroy()
self.update_network_trial()
dialog.destroy()
break
else:
functions.error_dialog(self.window, self._("unknown_error_network_sync") + str(e.args[0]), self._("network_sync_error"))
if os.path.exists(path):
self.remove_folder(path)
return False
except Exception as ex:
functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
if os.path.exists(path):
self.remove_folder(path)
return False
def set_progressbar_status(self):
fraction = 1.0 * len(self.allocations) / self.trial_sample_size_spin.get_value_as_int()
self.allocations_progressbar.set_fraction(fraction)
self.allocations_progressbar.set_text('{0} / {1}'.format(
len(self.allocations), self.trial_sample_size_spin.get_value_as_int()))
def import_trial(self, file_name):
trial_name = '_'.join(self.trial_title_entry.get_text().split())[:10] + str.partition(str(time.time()), '.')[0]
temp_dir = tempfile.mkdtemp(prefix=trial_name)
self.used_temp_files.append(temp_dir)
temp_file = os.path.join(temp_dir, trial_name)
self.save_trial_to_file(temp_file)
try:
client = self.get_svn_client()
url = self.network_sync_dict['url'] + '/' + trial_name
rev = False
while True:
rev = client.import_(temp_dir, url, self._('minimization_initialized'))
if rev:
if type(rev) == type(pysvn.Revision(pysvn.opt_revision_kind.head)): break
self.set_progressbar_status()
data = {}
data['network_sync'] = self.network_sync_dict
data['trial_name'] = trial_name
fp = open(file_name, 'wb')
pickle.dump(data, fp)
fp.flush()
fp.close()
self.config.set('project', 'recent_trial', file_name)
with open(self.config_file, 'wb') as config_file:
self.config.write(config_file)
config_file.flush()
config_file.close()
self.remove_folder(temp_dir)
self.lock_trial()
return file_name
except Exception as ex:
functions.error_dialog(self.window, self._("unknown_error_network_sync") + repr(ex), self._("network_sync_error"))
if os.path.exists(temp_dir):
self.remove_folder(temp_dir)
return False
def remove_folder(self, folder):
try:
shutil.rmtree(folder)
except:
pass
def save_trial(self, file_name, initial=False):
if self.network_sync_dict['sync']:
if initial:
# here file_name is the file containing trial info: rep url etc
self.trial_file_name = self.import_trial(file_name)
else:
# here file name is the path. A temp folder for checkin into the repo.
self.checkin_trial(file_name)
self.network_sync_icon.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
self.network_sync_icon.set_tooltip_text(self._('network_sync_enabled'))
else:
self.trial_file_name = self.save_trial_local(file_name)
self.network_sync_icon.set_from_stock(gtk.STOCK_DISCONNECT, gtk.ICON_SIZE_SMALL_TOOLBAR)
self.network_sync_icon.set_tooltip_text(self._('network_sync_disabled'))
if self.trial_file_name: self.lock_trial()
return file_name
def network_sync_cancel(self):
return self.network_sync_cancel_command
def get_distance_measure_name(self):
for distance_measure_radio in self.distance_measure_radios:
if distance_measure_radio.get_active():
return distance_measure_radio.get_label()
return self._("unknown")
def get_distance_measure(self):
for idx, distance_measure_radio in enumerate(self.distance_measure_radios):
if distance_measure_radio.get_active():
return idx
return 0
def get_prob_method_name(self):
for prob_method_radio in self.prob_method_radios:
if prob_method_radio.get_active():
return prob_method_radio.get_label()
return self._("unknown")
def get_prob_method(self):
for idx, prob_method_radio in enumerate(self.prob_method_radios):
if prob_method_radio.get_active():
return idx
return 0
def get_variables_info(self):
variables = []
n = 0
for row in self.variable_liststore:
n += 1
variable = self._("weight_levels").format(n, *row)
variables.append(variable)
return '\n'.join(variables)
def get_variables_data(self):
variables = []
for row in self.variable_liststore:
variable = {}
variable['name'] = row[0]
variable['weight'] = row[1]
variable['levels'] = row[2]
variables.append(variable)
return variables
def get_groups_info(self):
groups = []
n = 0
for row in self.group_liststore:
n += 1
group = self._("allocation_ratio_format").format(n, *list(row))
groups.append(group)
return '\n'.join(groups)
def get_groups_data(self):
groups = []
for row in self.group_liststore:
group = {}
group['name'] = row[0]
group['allocation_ratio'] = row[1]
groups.append(group)
return groups
def select_file(self, title, action):
"""
A generic method returning file name
"""
stock = {
gtk.FILE_CHOOSER_ACTION_OPEN: gtk.STOCK_OPEN,
gtk.FILE_CHOOSER_ACTION_SAVE: gtk.STOCK_SAVE,
gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER: gtk.STOCK_SAVE}
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, stock[action], gtk.RESPONSE_OK)
fdialog = gtk.FileChooserDialog(title, self.window, action, buttons)
if action == gtk.FILE_CHOOSER_ACTION_SAVE:
fdialog.set_do_overwrite_confirmation(True)
fdialog.set_default_response(gtk.RESPONSE_OK)
fdialog.set_current_folder(self.file_chooser_current_folder)
response = fdialog.run()
if response == gtk.RESPONSE_OK:
file_name = fdialog.get_filename()
self.file_chooser_current_folder = os.path.dirname(file_name)
else:
file_name = None
fdialog.destroy()
return file_name
def main():
gtk.main()
return 0
if __name__ == "__main__":
m = ModelInteface()
ret = main()
while m.restart:
m = ModelInteface()
ret = main()