Spaces:
Runtime error
Runtime error
File size: 73,212 Bytes
fc22863 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "21cb09bb",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"from random import randint\n",
"import random\n",
"import time\n",
"import uuid\n",
"from datetime import datetime\n",
"import math\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import logging\n",
"import logging.handlers\n",
"import pickle\n",
"from contextlib import contextmanager\n",
"\n",
"tokens = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\n",
" \"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n",
"numTokens = tokens[:10]\n",
"alphaTokens = tokens[10:36]\n",
"loCaseChars = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\",\"l\",\"m\",\"n\",\"o\",\n",
"\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n",
"\n",
"typeInt = \"int\"\n",
"typeFloat = \"float\"\n",
"typeString = \"string\"\n",
"\n",
"secInMinute = 60\n",
"secInHour = 60 * 60\n",
"secInDay = 24 * secInHour\n",
"secInWeek = 7 * secInDay\n",
"secInYear = 365 * secInDay\n",
"secInMonth = secInYear / 12\n",
"\n",
"minInHour = 60\n",
"minInDay = 24 * minInHour\n",
"\n",
"ftPerYard = 3\n",
"ftPerMile = ftPerYard * 1760\n",
"\n",
"\n",
"def genID(size):\n",
" \"\"\"\n",
" generates ID\n",
"\n",
" Parameters\n",
" size : size of ID\n",
" \"\"\"\n",
" id = \"\"\n",
" for i in range(size):\n",
" id = id + selectRandomFromList(tokens)\n",
" return id\n",
"\n",
"def genIdList(numId, idSize):\n",
" \"\"\"\n",
" generate list of IDs\n",
"\n",
" Parameters:\n",
" numId: number of Ids\n",
" idSize: ID size\n",
" \"\"\"\n",
" iDs = []\n",
" for i in range(numId):\n",
" iDs.append(genID(idSize))\n",
" return iDs\n",
"\n",
"def genNumID(size):\n",
" \"\"\"\n",
" generates ID consisting of digits onl\n",
"\n",
" Parameters\n",
" size : size of ID\n",
" \"\"\"\n",
" id = \"\"\n",
" for i in range(size):\n",
" id = id + selectRandomFromList(numTokens)\n",
" return id\n",
"\n",
"def genLowCaseID(size):\n",
" \"\"\"\n",
" generates ID consisting of lower case chars\n",
"\n",
" Parameters\n",
" size : size of ID\n",
" \"\"\"\n",
" id = \"\"\n",
" for i in range(size):\n",
" id = id + selectRandomFromList(loCaseChars)\n",
" return id\n",
"\n",
"def genNumIdList(numId, idSize):\n",
" \"\"\"\n",
" generate list of numeric IDs\n",
"\n",
" Parameters:\n",
" numId: number of Ids\n",
" idSize: ID size\n",
" \"\"\"\n",
" iDs = []\n",
" for i in range(numId):\n",
" iDs.append(genNumID(idSize))\n",
" return iDs\n",
"\n",
"def genNameInitial():\n",
" \"\"\"\n",
" generate name initial\n",
" \"\"\"\n",
" return selectRandomFromList(alphaTokens) + selectRandomFromList(alphaTokens)\n",
"\n",
"def genPhoneNum(arCode):\n",
" \"\"\"\n",
" generates phone number\n",
"\n",
" Parameters\n",
" arCode: area code\n",
" \"\"\"\n",
" phNum = genNumID(7)\n",
" return arCode + str(phNum)\n",
"\n",
"def selectRandomFromList(ldata):\n",
" \"\"\"\n",
" select an element randomly from a lis\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" \"\"\"\n",
" return ldata[randint(0, len(ldata)-1)]\n",
"\n",
"def selectOtherRandomFromList(ldata, cval):\n",
" \"\"\"\n",
" select an element randomly from a list excluding the given one\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" cval : value to be excluded\n",
" \"\"\"\n",
" nval = selectRandomFromList(ldata)\n",
" while nval == cval:\n",
" nval = selectRandomFromList(ldata)\n",
" return nval\n",
"\n",
"def selectRandomSubListFromList(ldata, num):\n",
" \"\"\"\n",
" generates random sublist from a list without replacemment\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" num : output list size\n",
" \"\"\"\n",
" assertLesser(num, len(ldata), \"size of sublist to be sampled greater than or equal to main list\")\n",
" i = randint(0, len(ldata)-1)\n",
" sel = ldata[i]\n",
" selSet = {i}\n",
" selList = [sel]\n",
" while (len(selSet) < num):\n",
" i = randint(0, len(ldata)-1)\n",
" if (i not in selSet):\n",
" sel = ldata[i]\n",
" selSet.add(i)\n",
" selList.append(sel)\n",
" return selList\n",
"\n",
"def selectRandomSubListFromListWithRepl(ldata, num):\n",
" \"\"\"\n",
" generates random sublist from a list with replacemment\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" num : output list size\n",
" \"\"\"\n",
" return list(map(lambda i : selectRandomFromList(ldata), range(num)))\n",
"\n",
"def selectRandomFromDict(ddata):\n",
" \"\"\"\n",
" select an element randomly from a dictionary\n",
"\n",
" Parameters\n",
" ddata : dictionary data\n",
" \"\"\"\n",
" dkeys = list(ddata.keys())\n",
" dk = selectRandomFromList(dkeys)\n",
" el = (dk, ddata[dk])\n",
" return el\n",
"\n",
"def setListRandomFromList(ldata, ldataRepl):\n",
" \"\"\"\n",
" sets some elents in the first list randomly with elements from the second list\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" ldataRepl : list with replacement data\n",
" \"\"\"\n",
" l = len(ldata)\n",
" selSet = set()\n",
" for d in ldataRepl:\n",
" i = randint(0, l-1)\n",
" while i in selSet:\n",
" i = randint(0, l-1)\n",
" ldata[i] = d\n",
" selSet.add(i)\n",
"\n",
"def genIpAddress():\n",
" \"\"\"\n",
" generates IP address\n",
" \"\"\"\n",
" i1 = randint(0,256)\n",
" i2 = randint(0,256)\n",
" i3 = randint(0,256)\n",
" i4 = randint(0,256)\n",
" ip = \"%d.%d.%d.%d\" %(i1,i2,i3,i4)\n",
" return ip\n",
"\n",
"def curTimeMs():\n",
" \"\"\"\n",
" current time in ms\n",
" \"\"\"\n",
" return int((datetime.utcnow() - datetime(1970,1,1)).total_seconds() * 1000)\n",
"\n",
"def secDegPolyFit(x1, y1, x2, y2, x3, y3):\n",
" \"\"\"\n",
" second deg polynomial \t\n",
"\n",
" Parameters\n",
" x1 : 1st point x\n",
" y1 : 1st point y\n",
" x2 : 2nd point x\n",
" y2 : 2nd point y\n",
" x3 : 3rd point x\n",
" y3 : 3rd point y\n",
" \"\"\"\n",
" t = (y1 - y2) / (x1 - x2)\n",
" a = t - (y2 - y3) / (x2 - x3)\n",
" a = a / (x1 - x3)\n",
" b = t - a * (x1 + x2)\n",
" c = y1 - a * x1 * x1 - b * x1\n",
" return (a, b, c)\n",
"\n",
"def range_limit(val, minv, maxv):\n",
" \"\"\"\n",
" range limit a value\n",
"\n",
" Parameters\n",
" val : data value\n",
" minv : minimum\n",
" maxv : maximum\n",
" \"\"\"\n",
" if (val < minv):\n",
" val = minv\n",
" elif (val > maxv):\n",
" val = maxv\n",
" return val\n",
"\n",
"def isInRange(val, minv, maxv):\n",
" \"\"\"\n",
" checks if within range\n",
"\n",
" Parameters\n",
" val : data value\n",
" minv : minimum\n",
" maxv : maximum\n",
" \"\"\"\n",
" return val >= minv and val <= maxv\n",
"\n",
"def stripFileLines(filePath, offset):\n",
" \"\"\"\n",
" strips number of chars from both ends\n",
"\n",
" Parameters\n",
" filePath : file path\n",
" offset : offset from both ends of line \n",
" \"\"\"\n",
" fp = open(filePath, \"r\")\n",
" for line in fp:\n",
" stripped = line[offset:len(line) - 1 - offset]\n",
" print (stripped)\n",
" fp.close()\n",
"\n",
"def genLatLong(lat1, long1, lat2, long2):\n",
" \"\"\"\n",
" generate lat log within limits\n",
"\n",
" Parameters\n",
" lat1 : lat of 1st point\n",
" long1 : long of 1st point\n",
" lat2 : lat of 2nd point\n",
" long2 : long of 2nd point\n",
" \"\"\"\n",
" lat = lat1 + (lat2 - lat1) * random.random()\n",
" longg = long1 + (long2 - long1) * random.random()\n",
" return (lat, longg)\n",
"\n",
"def geoDistance(lat1, long1, lat2, long2):\n",
" \"\"\"\n",
" find geo distance in ft\n",
"\n",
" Parameters\n",
" lat1 : lat of 1st point\n",
" long1 : long of 1st point\n",
" lat2 : lat of 2nd point\n",
" long2 : long of 2nd point\n",
" \"\"\"\n",
" latDiff = math.radians(lat1 - lat2)\n",
" longDiff = math.radians(long1 - long2)\n",
" l1 = math.sin(latDiff/2.0)\n",
" l2 = math.sin(longDiff/2.0)\n",
" l3 = math.cos(math.radians(lat1))\n",
" l4 = math.cos(math.radians(lat2))\n",
" a = l1 * l1 + l3 * l4 * l2 * l2\n",
" l5 = math.sqrt(a)\n",
" l6 = math.sqrt(1.0 - a)\n",
" c = 2.0 * math.atan2(l5, l6)\n",
" r = 6371008.8 * 3.280840\n",
" return c * r\n",
"\n",
"def minLimit(val, limit):\n",
" \"\"\"\n",
" min limit\n",
" Parameters\n",
" \"\"\"\n",
" if (val < limit):\n",
" val = limit\n",
" return val;\n",
"\n",
"def maxLimit(val, limit):\n",
" \"\"\"\n",
" max limit\n",
" Parameters\n",
" \"\"\"\n",
" if (val > limit):\n",
" val = limit\n",
" return val;\n",
"\n",
"def rangeSample(val, minLim, maxLim):\n",
" \"\"\"\n",
" if out side range sample within range\n",
"\n",
" Parameters\n",
" val : value\n",
" minLim : minimum\n",
" maxLim : maximum\n",
" \"\"\"\n",
" if val < minLim or val > maxLim:\n",
" val = randint(minLim, maxLim)\n",
" return val\n",
"\n",
"def genRandomIntListWithinRange(size, minLim, maxLim):\n",
" \"\"\"\n",
" random unique list of integers within range\n",
"\n",
" Parameters\n",
" size : size of returned list\n",
" minLim : minimum\n",
" maxLim : maximum\n",
" \"\"\"\n",
" values = set()\n",
" for i in range(size):\n",
" val = randint(minLim, maxLim)\n",
" while val not in values:\n",
" values.add(val)\n",
" return list(values)\n",
"\n",
"def preturbScalar(value, vrange):\n",
" \"\"\"\n",
" preturbs a mutiplicative value within range\n",
"\n",
" Parameters\n",
" value : data value\n",
" vrange : value delta fraction\n",
" \"\"\"\n",
" scale = 1.0 - vrange + 2 * vrange * random.random() \n",
" return value * scale\n",
"\n",
"def preturbScalarAbs(value, vrange):\n",
" \"\"\"\n",
" preturbs an absolute value within range\n",
"\n",
" Parameters\n",
" value : data value\n",
" vrange : value delta absolute\n",
" \"\"\"\n",
" delta = - vrange + 2.0 * vrange * random.random() \n",
" return value + delta\n",
"\n",
"def preturbVector(values, vrange):\n",
" \"\"\"\n",
" preturbs a list within range\n",
"\n",
" Parameters\n",
" values : list data\n",
" vrange : value delta fraction\n",
" \"\"\"\n",
" nValues = list(map(lambda va: preturbScalar(va, vrange), values))\n",
" return nValues\n",
"\n",
"def randomShiftVector(values, smin, smax):\n",
" \"\"\"\n",
" shifts a list by a random quanity with a range\n",
"\n",
" Parameters\n",
" values : list data\n",
" smin : samplinf minimum\n",
" smax : sampling maximum\n",
" \"\"\"\n",
" shift = np.random.uniform(smin, smax)\n",
" return list(map(lambda va: va + shift, values))\n",
"\n",
"def floatRange(beg, end, incr):\n",
" \"\"\"\n",
" generates float range\n",
"\n",
" Parameters\n",
" beg :range begin\n",
" end: range end\n",
" incr : range increment\n",
" \"\"\"\n",
" return list(np.arange(beg, end, incr))\n",
"\n",
"def shuffle(values, *numShuffles):\n",
" \"\"\"\n",
" in place shuffling with swap of pairs\n",
"\n",
" Parameters\n",
" values : list data\n",
" numShuffles : parameter list for number of shuffles\n",
" \"\"\"\n",
" size = len(values)\n",
" if len(numShuffles) == 0:\n",
" numShuffle = int(size / 2)\n",
" elif len(numShuffles) == 1:\n",
" numShuffle = numShuffles[0]\n",
" else:\n",
" numShuffle = randint(numShuffles[0], numShuffles[1])\n",
" print(\"numShuffle {}\".format(numShuffle))\n",
" for i in range(numShuffle):\n",
" first = random.randint(0, size - 1)\n",
" second = random.randint(0, size - 1)\n",
" while first == second:\n",
" second = random.randint(0, size - 1)\n",
" tmp = values[first]\n",
" values[first] = values[second]\n",
" values[second] = tmp\n",
"\n",
"\n",
"def splitList(itms, numGr):\n",
" \"\"\"\n",
" splits a list into sub lists of approximately equal size, with items in sublists randomly chod=sen\n",
"\n",
" Parameters\n",
" itms ; list of values\t\t\n",
" numGr : no of groups\n",
" \"\"\"\n",
" tcount = len(itms)\n",
" cItems = list(itms)\n",
" sz = int(len(cItems) / numGr)\n",
" groups = list()\n",
" count = 0\n",
" for i in range(numGr):\n",
" if (i == numGr - 1):\n",
" csz = tcount - count\n",
" else:\n",
" csz = sz + randint(-2, 2)\n",
" count += csz\n",
" gr = list()\n",
" for j in range(csz):\n",
" it = selectRandomFromList(cItems)\n",
" gr.append(it)\n",
" cItems.remove(it)\n",
" groups.append(gr)\n",
" return groups\n",
"\n",
"def multVector(values, vrange):\n",
" \"\"\"\n",
" multiplies a list within value range\n",
"\n",
" Parameters\n",
" values : list of values\n",
" vrange : fraction of vaue to be used to update\n",
" \"\"\"\n",
" scale = 1.0 - vrange + 2 * vrange * random.random()\n",
" nValues = list(map(lambda va: va * scale, values))\n",
" return nValues\n",
"\n",
"def weightedAverage(values, weights):\n",
" \"\"\"\n",
" calculates weighted average\n",
"\n",
" Parameters\n",
" values : list of values\n",
" weights : list of weights\n",
" \"\"\"\t\t\n",
" assert len(values) == len(weights), \"values and weights should be same size\"\n",
" vw = zip(values, weights)\n",
" wva = list(map(lambda e : e[0] * e[1], vw))\n",
" #wa = sum(x * y for x, y in vw) / sum(weights)\n",
" wav = sum(wva) / sum(weights)\n",
" return wav\n",
"\n",
"def extractFields(line, delim, keepIndices):\n",
" \"\"\"\n",
" breaks a line into fields and keeps only specified fileds and returns new line\n",
"\n",
" Parameters\n",
" line ; deli separated string\n",
" delim : delemeter\n",
" keepIndices : list of indexes to fields to be retained\n",
" \"\"\"\n",
" items = line.split(delim)\n",
" newLine = []\n",
" for i in keepIndices:\n",
" newLine.append(line[i])\n",
" return delim.join(newLine)\n",
"\n",
"def remFields(line, delim, remIndices):\n",
" \"\"\"\n",
" removes fields from delim separated string\n",
"\n",
" Parameters\n",
" line ; delemeter separated string\n",
" delim : delemeter\n",
" remIndices : list of indexes to fields to be removed\n",
" \"\"\"\n",
" items = line.split(delim)\n",
" newLine = []\n",
" for i in range(len(items)):\n",
" if not arrayContains(remIndices, i):\n",
" newLine.append(line[i])\n",
" return delim.join(newLine)\n",
"\n",
"def extractList(data, indices):\n",
" \"\"\"\n",
" extracts list from another list, given indices\n",
"\n",
" Parameters\n",
" remIndices : list data\n",
" indices : list of indexes to fields to be retained\n",
" \"\"\"\n",
" if areAllFieldsIncluded(data, indices):\n",
" exList = data.copy()\n",
" #print(\"all indices\")\n",
" else:\n",
" exList = list()\n",
" le = len(data)\n",
" for i in indices:\n",
" assert i < le , \"index {} out of bound {}\".format(i, le)\n",
" exList.append(data[i])\n",
"\n",
" return exList\n",
"\n",
"def arrayContains(arr, item):\n",
" \"\"\"\n",
" checks if array contains an item \n",
"\n",
" Parameters\n",
" arr : list data\n",
" item : item to search\n",
" \"\"\"\n",
" contains = True\n",
" try:\n",
" arr.index(item)\n",
" except ValueError:\n",
" contains = False\n",
" return contains\n",
"\n",
"def strToIntArray(line, delim=\",\"):\n",
" \"\"\"\n",
" int array from delim separated string\n",
"\n",
" Parameters\n",
" line ; delemeter separated string\n",
" \"\"\"\n",
" arr = line.split(delim)\n",
" return [int(a) for a in arr]\n",
"\n",
"def strToFloatArray(line, delim=\",\"):\n",
" \"\"\"\n",
" float array from delim separated string\n",
"\n",
" Parameters\n",
" line ; delemeter separated string\n",
" \"\"\"\n",
" arr = line.split(delim)\n",
" return [float(a) for a in arr]\n",
"\n",
"def strListOrRangeToIntArray(line):\n",
" \"\"\"\n",
" int array from delim separated string or range\n",
"\n",
" Parameters\n",
" line ; delemeter separated string\n",
" \"\"\"\n",
" varr = line.split(\",\")\n",
" if (len(varr) > 1):\n",
" iarr = list(map(lambda v: int(v), varr))\n",
" else:\n",
" vrange = line.split(\":\")\n",
" if (len(vrange) == 2):\n",
" lo = int(vrange[0])\n",
" hi = int(vrange[1])\n",
" iarr = list(range(lo, hi+1))\n",
" else:\n",
" iarr = [int(line)]\n",
" return iarr\n",
"\n",
"def toStr(val, precision):\n",
" \"\"\"\n",
" converts any type to string\t\n",
"\n",
" Parameters\n",
" val : value\n",
" precision ; precision for float value\n",
" \"\"\"\n",
" if type(val) == float or type(val) == np.float64 or type(val) == np.float32:\n",
" format = \"%\" + \".%df\" %(precision)\n",
" sVal = format %(val)\n",
" else:\n",
" sVal = str(val)\n",
" return sVal\n",
"\n",
"def toStrFromList(values, precision, delim=\",\"):\n",
" \"\"\"\n",
" converts list of any type to delim separated string\n",
"\n",
" Parameters\n",
" values : list data\n",
" precision ; precision for float value\n",
" delim : delemeter\n",
" \"\"\"\n",
" sValues = list(map(lambda v: toStr(v, precision), values))\n",
" return delim.join(sValues)\n",
"\n",
"def toIntList(values):\n",
" \"\"\"\n",
" convert to int list\n",
"\n",
" Parameters\n",
" values : list data\n",
" \"\"\"\n",
" return list(map(lambda va: int(va), values))\n",
"\n",
"def toFloatList(values):\n",
" \"\"\"\n",
" convert to float list\n",
"\n",
" Parameters\n",
" values : list data\n",
" \"\"\"\n",
" return list(map(lambda va: float(va), values))\n",
"\n",
"def toStrList(values, precision=None):\n",
" \"\"\"\n",
" convert to string list\n",
"\n",
" Parameters\n",
" values : list data\n",
" precision ; precision for float value\n",
" \"\"\"\n",
" return list(map(lambda va: toStr(va, precision), values))\n",
"\n",
"def toIntFromBoolean(value):\n",
" \"\"\"\n",
" convert to int\n",
"\n",
" Parameters\n",
" value : boolean value\n",
" \"\"\"\n",
" ival = 1 if value else 0\n",
" return ival\n",
"\n",
"def typedValue(val, dtype=None):\n",
" \"\"\"\n",
" return typed value given string, discovers data type if not specified\n",
"\n",
" Parameters\n",
" val : value\n",
" dtype : data type\n",
" \"\"\"\n",
" tVal = None\n",
"\n",
" if dtype is not None:\n",
" if dtype == \"num\":\n",
" dtype = \"int\" if dtype.find(\".\") == -1 else \"float\"\n",
"\n",
" if dtype == \"int\":\n",
" tVal = int(val)\n",
" elif dtype == \"float\":\n",
" tVal = float(val)\n",
" elif dtype == \"bool\":\n",
" tVal = bool(val)\n",
" else:\n",
" tVal = val\n",
" else:\n",
" if type(val) == str:\n",
" lVal = val.lower()\n",
"\n",
" #int\n",
" done = True\n",
" try:\n",
" tVal = int(val)\n",
" except ValueError:\n",
" done = False\n",
"\n",
" #float\n",
" if not done:\n",
" done = True\n",
" try:\n",
" tVal = float(val)\n",
" except ValueError:\n",
" done = False\n",
"\n",
" #boolean\n",
" if not done:\n",
" done = True\n",
" if lVal == \"true\":\n",
" tVal = True\n",
" elif lVal == \"false\":\n",
" tVal = False\n",
" else:\n",
" done = False\n",
" #None\t\t\n",
" if not done:\n",
" if lVal == \"none\":\n",
" tVal = None\n",
" else:\n",
" tVal = val\n",
" else:\n",
" tVal = val\n",
"\n",
" return tVal\n",
"\n",
"def getAllFiles(dirPath):\n",
" \"\"\"\n",
" get all files recursively\n",
"\n",
" Parameters\n",
" dirPath : directory path\n",
" \"\"\"\n",
" filePaths = []\n",
" for (thisDir, subDirs, fileNames) in os.walk(dirPath):\n",
" for fileName in fileNames:\n",
" filePaths.append(os.path.join(thisDir, fileName))\n",
" filePaths.sort()\n",
" return filePaths\n",
"\n",
"def getFileContent(fpath, verbose=False):\n",
" \"\"\"\n",
" get file contents in directory\n",
"\n",
" Parameters\n",
" fpath ; directory path\n",
" verbose : verbosity flag\n",
" \"\"\"\n",
" # dcument list\n",
" docComplete = []\n",
" filePaths = getAllFiles(fpath)\n",
"\n",
" # read files\n",
" for filePath in filePaths:\n",
" if verbose:\n",
" print(\"next file \" + filePath)\n",
" with open(filePath, 'r') as contentFile:\n",
" content = contentFile.read()\n",
" docComplete.append(content)\n",
" return (docComplete, filePaths)\n",
"\n",
"def getOneFileContent(fpath):\n",
" \"\"\"\n",
" get one file contents\n",
"\n",
" Parameters\n",
" fpath : file path\n",
" \"\"\"\n",
" with open(fpath, 'r') as contentFile:\n",
" docStr = contentFile.read()\n",
" return docStr\n",
"\n",
"def getFileLines(dirPath, delim=\",\"):\n",
" \"\"\"\n",
" get lines from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" delim : delemeter\n",
" \"\"\"\n",
" lines = list()\n",
" for li in fileRecGen(dirPath, delim):\n",
" lines.append(li)\n",
" return lines\n",
"\n",
"def getFileSampleLines(dirPath, percen, delim=\",\"):\n",
" \"\"\"\n",
" get sampled lines from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" percen : sampling percentage\n",
" delim : delemeter\n",
" \"\"\"\n",
" lines = list()\n",
" for li in fileRecGen(dirPath, delim):\n",
" if randint(0, 100) < percen:\n",
" lines.append(li)\n",
" return lines\n",
"\n",
"def getFileColumnAsString(dirPath, index, delim=\",\"):\n",
" \"\"\"\n",
" get string column from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" index : index\n",
" delim : delemeter\n",
" \"\"\"\n",
" fields = list()\n",
" for rec in fileRecGen(dirPath, delim):\n",
" fields.append(rec[index])\n",
" #print(fields)\t\n",
" return fields\n",
"\n",
"def getFileColumnsAsString(dirPath, indexes, delim=\",\"):\n",
" \"\"\"\n",
" get multiple string columns from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" indexes : indexes of columns\n",
" delim : delemeter\n",
" \"\"\"\n",
" nindex = len(indexes)\n",
" columns = list(map(lambda i : list(), range(nindex)))\n",
" for rec in fileRecGen(dirPath, delim):\n",
" for i in range(nindex):\n",
" columns[i].append(rec[indexes[i]])\n",
" return columns\n",
"\n",
"def getFileColumnAsFloat(dirPath, index, delim=\",\"):\n",
" \"\"\"\n",
" get float fileds from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" index : index\n",
" delim : delemeter\n",
" \"\"\"\n",
" #print(\"{} {}\".format(dirPath, index))\n",
" fields = getFileColumnAsString(dirPath, index, delim)\n",
" return list(map(lambda v:float(v), fields))\n",
"\n",
"def getFileColumnAsInt(dirPath, index, delim=\",\"):\n",
" \"\"\"\n",
" get float fileds from a file\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" index : index\n",
" delim : delemeter\n",
" \"\"\"\n",
" fields = getFileColumnAsString(dirPath, index, delim)\n",
" return list(map(lambda v:int(v), fields))\n",
"\n",
"def getFileAsIntMatrix(dirPath, columns, delim=\",\"):\n",
" \"\"\"\n",
" extracts int matrix from csv file given column indices with each row being concatenation of \n",
" extracted column values row size = num of columns\n",
"\n",
" Parameters\n",
" dirPath : file path\n",
" columns : indexes of columns\n",
" delim : delemeter\n",
" \"\"\"\n",
" mat = list()\n",
" for rec in fileSelFieldsRecGen(dirPath, columns, delim):\n",
" mat.append(asIntList(rec))\n",
" return mat\n",
"\n",
"def getFileAsFloatMatrix(dirPath, columns, delim=\",\"):\n",
" \"\"\"\n",
" extracts float matrix from csv file given column indices with each row being concatenation of \n",
" extracted column values row size = num of columns\n",
" Parameters\n",
" dirPath : file path\n",
" columns : indexes of columns\n",
" delim : delemeter\n",
" \"\"\"\n",
" mat = list()\n",
" for rec in fileSelFieldsRecGen(dirPath, columns, delim):\n",
" mat.append(asFloatList(rec))\n",
" return mat\n",
"\n",
"def getFileAsFloatColumn(dirPath):\n",
" \"\"\"\n",
" grt float list from a file with one float per row\n",
" Parameters\n",
" dirPath : file path\n",
" \"\"\"\n",
" flist = list()\n",
" for rec in fileRecGen(dirPath, None):\n",
" flist.append(float(rec))\n",
" return flist\n",
"\n",
"def getFileAsFiltFloatMatrix(dirPath, filt, columns, delim=\",\"):\n",
" \"\"\"\n",
" extracts float matrix from csv file given row filter and column indices with each row being \n",
" concatenation of extracted column values row size = num of columns\n",
" Parameters\n",
" dirPath : file path\n",
" columns : indexes of columns\n",
" filt : row filter lambda\n",
" delim : delemeter\n",
" \"\"\"\n",
" mat = list()\n",
" for rec in fileFiltSelFieldsRecGen(dirPath, filt, columns, delim):\n",
" mat.append(asFloatList(rec))\n",
" return mat\n",
"\n",
"def getFileAsTypedRecords(dirPath, types, delim=\",\"):\n",
" \"\"\"\n",
" extracts typed records from csv file with each row being concatenation of \n",
" extracted column values \n",
" Parameters\n",
" dirPath : file path\n",
" types : data types\n",
" delim : delemeter\n",
" \"\"\"\n",
" (dtypes, cvalues) = extractTypesFromString(types)\n",
" tdata = list()\n",
" for rec in fileRecGen(dirPath, delim):\n",
" trec = list()\n",
" for index, value in enumerate(rec):\n",
" value = __convToTyped(index, value, dtypes)\n",
" trec.append(value)\n",
" tdata.append(trec)\n",
" return tdata\n",
"\n",
"\n",
"def getFileColsAsTypedRecords(dirPath, columns, types, delim=\",\"):\n",
" \"\"\"\n",
" extracts typed records from csv file given column indices with each row being concatenation of \n",
" extracted column values \n",
" Parameters\n",
" Parameters\n",
" dirPath : file path\n",
" columns : column indexes\n",
" types : data types\n",
" delim : delemeter\n",
" \"\"\"\n",
" (dtypes, cvalues) = extractTypesFromString(types)\n",
" tdata = list()\n",
" for rec in fileSelFieldsRecGen(dirPath, columns, delim):\n",
" trec = list()\n",
" for indx, value in enumerate(rec):\n",
" tindx = columns[indx]\n",
" value = __convToTyped(tindx, value, dtypes)\n",
" trec.append(value)\n",
" tdata.append(trec)\n",
" return tdata\n",
"\n",
"def getFileColumnsMinMax(dirPath, columns, dtype, delim=\",\"):\n",
" \"\"\"\n",
" extracts numeric matrix from csv file given column indices. For each column return min and max\n",
" Parameters\n",
" dirPath : file path\n",
" columns : column indexes\n",
" dtype : data type\n",
" delim : delemeter\n",
" \"\"\"\n",
" dtypes = list(map(lambda c : str(c) + \":\" + dtype, columns))\n",
" dtypes = \",\".join(dtypes)\n",
" #print(dtypes)\n",
"\n",
" tdata = getFileColsAsTypedRecords(dirPath, columns, dtypes, delim)\n",
" minMax = list()\n",
" ncola = len(tdata[0])\n",
" ncole = len(columns)\n",
" assertEqual(ncola, ncole, \"actual no of columns different from expected\")\n",
"\n",
" for ci in range(ncole):\t\n",
" vmin = sys.float_info.max\n",
" vmax = sys.float_info.min\n",
" for r in tdata:\n",
" cv = r[ci]\n",
" vmin = cv if cv < vmin else vmin\n",
" vmax = cv if cv > vmax else vmax\n",
" mm = (vmin, vmax, vmax - vmin)\n",
" minMax.append(mm)\n",
"\n",
" return minMax\n",
"\n",
"\n",
"def getRecAsTypedRecord(rec, types, delim=None):\n",
" \"\"\"\n",
" converts record to typed records \n",
" Parameters\n",
" rec : delemeter separate string or list of string\n",
" types : field data types\n",
" delim : delemeter\n",
" \"\"\"\t\n",
" if delim is not None:\n",
" rec = rec.split(delim)\n",
" (dtypes, cvalues) = extractTypesFromString(types)\n",
" #print(types)\n",
" #print(dtypes)\n",
" trec = list()\n",
" for ind, value in enumerate(rec):\n",
" tvalue = __convToTyped(ind, value, dtypes)\n",
" trec.append(tvalue)\n",
" return trec\n",
"\n",
"def __convToTyped(index, value, dtypes):\n",
" \"\"\"\n",
" convert to typed value \n",
" Parameters\n",
" index : index in type list\n",
" value : data value\n",
" dtypes : data type list\n",
" \"\"\"\n",
" #print(index, value)\n",
" dtype = dtypes[index]\n",
" tvalue = value\n",
" if dtype == \"int\":\n",
" tvalue = int(value)\n",
" elif dtype == \"float\":\n",
" tvalue = float(value)\n",
" return tvalue\n",
"\n",
"\n",
"\n",
"def extractTypesFromString(types):\n",
" \"\"\"\n",
" extracts column data types and set values for categorical variables \n",
" Parameters\n",
" types : encoded type information\n",
" \"\"\"\n",
" ftypes = types.split(\",\")\n",
" dtypes = dict()\n",
" cvalues = dict()\n",
" for ftype in ftypes:\n",
" items = ftype.split(\":\") \n",
" cindex = int(items[0])\n",
" dtype = items[1]\n",
" dtypes[cindex] = dtype\n",
" if len(items) == 3:\n",
" sitems = items[2].split()\n",
" cvalues[cindex] = sitems\n",
" return (dtypes, cvalues)\n",
"\n",
"def getMultipleFileAsInttMatrix(dirPathWithCol, delim=\",\"):\n",
" \"\"\"\n",
" extracts int matrix from from csv files given column index for each file. \n",
" num of columns = number of rows in each file and num of rows = number of files\n",
" Parameters\n",
" dirPathWithCol: list of file path and collumn index pair\n",
" delim : delemeter\n",
" \"\"\"\n",
" mat = list()\n",
" minLen = -1\n",
" for path, col in dirPathWithCol:\n",
" colVals = getFileColumnAsInt(path, col, delim)\n",
" if minLen < 0 or len(colVals) < minLen:\n",
" minLen = len(colVals)\n",
" mat.append(colVals)\n",
"\n",
" #make all same length\n",
" mat = list(map(lambda li:li[:minLen], mat))\n",
" return mat\n",
"\n",
"def getMultipleFileAsFloatMatrix(dirPathWithCol, delim=\",\"):\n",
" \"\"\"\n",
" extracts float matrix from from csv files given column index for each file. \n",
" num of columns = number of rows in each file and num of rows = number of files\n",
" Parameters\n",
" dirPathWithCol: list of file path and collumn index pair\n",
" delim : delemeter\n",
" \"\"\"\n",
" mat = list()\n",
" minLen = -1\n",
" for path, col in dirPathWithCol:\n",
" colVals = getFileColumnAsFloat(path, col, delim)\n",
" if minLen < 0 or len(colVals) < minLen:\n",
" minLen = len(colVals)\n",
" mat.append(colVals)\n",
"\n",
" #make all same length\n",
" mat = list(map(lambda li:li[:minLen], mat))\n",
" return mat\n",
"\n",
"def writeStrListToFile(ldata, filePath, delem=\",\"):\n",
" \"\"\"\n",
" writes list of dlem separated string or list of list of string to afile\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" filePath : file path\n",
" delim : delemeter\n",
" \"\"\"\n",
" with open(filePath, \"w\") as fh:\n",
" for r in ldata:\n",
" if type(r) == list:\n",
" r = delem.join(r)\n",
" fh.write(r + \"\\n\")\n",
"\n",
"def writeFloatListToFile(ldata, prec, filePath):\n",
" \"\"\"\n",
" writes float list to file, one value per line\n",
"\n",
" Parameters\n",
" ldata : list data\n",
" prec : precision\n",
" filePath : file path\n",
" \"\"\"\n",
" with open(filePath, \"w\") as fh:\n",
" for d in ldata:\n",
" fh.write(formatFloat(prec, d) + \"\\n\")\n",
"\n",
"\n",
"def takeFirst(elems):\n",
" \"\"\"\n",
" return fisrt item\n",
" Parameters\n",
" elems : list of data \n",
" \"\"\"\n",
" return elems[0]\n",
"\n",
"def takeSecond(elems):\n",
" \"\"\"\n",
" return 2nd element\n",
" Parameters\n",
" elems : list of data \n",
" \"\"\"\n",
" return elems[1]\n",
"\n",
"def takeThird(elems):\n",
" \"\"\"\n",
" returns 3rd element\n",
" Parameters\n",
" elems : list of data \n",
" \"\"\"\n",
" return elems[2]\n",
"\n",
"def addToKeyedCounter(dCounter, key, count=1):\n",
" \"\"\"\n",
" add to to keyed counter\n",
" Parameters\n",
" dCounter : dictionary of counters\n",
" key : dictionary key\n",
" count : count to add\n",
" \"\"\"\n",
" curCount = dCounter.get(key, 0)\n",
" dCounter[key] = curCount + count\n",
"\n",
"def incrKeyedCounter(dCounter, key):\n",
" \"\"\"\n",
" increment keyed counter\n",
" Parameters\n",
" dCounter : dictionary of counters\n",
" key : dictionary key\n",
" \"\"\"\n",
" addToKeyedCounter(dCounter, key, 1)\n",
"\n",
"def appendKeyedList(dList, key, elem):\n",
" \"\"\"\n",
" keyed list\n",
" Parameters\n",
" dList : dictionary of lists\n",
" key : dictionary key\n",
" elem : value to append\n",
" \"\"\"\n",
" curList = dList.get(key, [])\n",
" curList.append(elem)\n",
" dList[key] = curList\n",
"\n",
"def isNumber(st):\n",
" \"\"\"\n",
" Returns True is string is a number\n",
" Parameters\n",
" st : string value\n",
" \"\"\"\n",
" return st.replace('.','',1).isdigit()\n",
"\n",
"def removeNan(values):\n",
" \"\"\"\n",
" removes nan from list\n",
" Parameters\n",
" values : list data\n",
" \"\"\"\n",
" return list(filter(lambda v: not math.isnan(v), values))\n",
"\n",
"def fileRecGen(filePath, delim = \",\"):\n",
" \"\"\"\n",
" file record generator\n",
" Parameters\n",
" filePath ; file path\n",
" delim : delemeter\n",
" \"\"\"\n",
" with open(filePath, \"r\") as fp:\n",
" for line in fp:\t\n",
" line = line[:-1]\n",
" if delim is not None:\n",
" line = line.split(delim)\n",
" yield line\n",
"\n",
"def fileSelFieldsRecGen(dirPath, columns, delim=\",\"):\n",
" \"\"\"\n",
" file record generator given column indices \n",
" Parameters\n",
" filePath ; file path\n",
" columns : column indexes as int array or coma separated string\n",
" delim : delemeter\n",
" \"\"\"\n",
" if type(columns) == str:\n",
" columns = strToIntArray(columns, delim)\n",
" for rec in fileRecGen(dirPath, delim):\n",
" extracted = extractList(rec, columns)\n",
" yield extracted\n",
"\n",
"def fileFiltRecGen(filePath, filt, delim = \",\"):\n",
" \"\"\"\n",
" file record generator with row filter applied\n",
" Parameters\n",
" filePath ; file path\n",
" filt : row filter\n",
" delim : delemeter\n",
" \"\"\"\n",
" with open(filePath, \"r\") as fp:\n",
" for line in fp:\t\n",
" line = line[:-1]\n",
" if delim is not None:\n",
" line = line.split(delim)\n",
" if filt(line):\n",
" yield line\n",
"\n",
"def fileFiltSelFieldsRecGen(filePath, filt, columns, delim = \",\"):\n",
" \"\"\"\n",
" file record generator with row and column filter applied\n",
" Parameters\n",
" filePath ; file path\n",
" filt : row filter\n",
" columns : column indexes as int array or coma separated string\n",
" delim : delemeter\n",
" \"\"\"\n",
" columns = strToIntArray(columns, delim)\n",
" with open(filePath, \"r\") as fp:\n",
" for line in fp:\t\n",
" line = line[:-1]\n",
" if delim is not None:\n",
" line = line.split(delim)\n",
" if filt(line):\n",
" selected = extractList(line, columns)\n",
" yield selected\n",
"\n",
"def fileTypedRecGen(filePath, ftypes, delim = \",\"):\n",
" \"\"\"\n",
" file typed record generator\n",
" Parameters\n",
" filePath ; file path\n",
" ftypes : list of field types\n",
" delim : delemeter\n",
" \"\"\"\n",
" with open(filePath, \"r\") as fp:\n",
" for line in fp:\t\n",
" line = line[:-1]\n",
" line = line.split(delim)\n",
" for i in range(0, len(ftypes), 2):\n",
" ci = ftypes[i]\n",
" dtype = ftypes[i+1]\n",
" assertLesser(ci, len(line), \"index out of bound\")\n",
" if dtype == \"int\":\n",
" line[ci] = int(line[ci])\n",
" elif dtype == \"float\":\n",
" line[ci] = float(line[ci])\n",
" else:\n",
" exitWithMsg(\"invalid data type\")\n",
" yield line\n",
"\n",
"def fileMutatedFieldsRecGen(dirPath, mutator, delim=\",\"):\n",
" \"\"\"\n",
" file record generator with some columns mutated \n",
" Parameters\n",
" dirPath ; file path\n",
" mutator : row field mutator\n",
" delim : delemeter\n",
" \"\"\"\n",
" for rec in fileRecGen(dirPath, delim):\n",
" mutated = mutator(rec)\n",
" yield mutated\n",
"\n",
"def tableSelFieldsFilter(tdata, columns):\n",
" \"\"\"\n",
" gets tabular data for selected columns \n",
" Parameters\n",
" tdata : tabular data\n",
" columns : column indexes\n",
" \"\"\"\n",
" if areAllFieldsIncluded(tdata[0], columns):\n",
" ntdata = tdata\n",
" else:\n",
" ntdata = list()\n",
" for rec in tdata:\n",
" #print(rec)\n",
" #print(columns)\n",
" nrec = extractList(rec, columns)\n",
" ntdata.append(nrec)\n",
" return ntdata\n",
"\n",
"\n",
"def areAllFieldsIncluded(ldata, columns):\n",
" \"\"\"\n",
" return True id all indexes are in the columns\n",
" Parameters\n",
" ldata : list data\n",
" columns : column indexes\n",
" \"\"\"\n",
" return list(range(len(ldata))) == columns\n",
"\n",
"def asIntList(items):\n",
" \"\"\"\n",
" returns int list\n",
" Parameters\n",
" items : list data\n",
" \"\"\"\n",
" return [int(i) for i in items]\n",
"\n",
"def asFloatList(items):\n",
" \"\"\"\n",
" returns float list\n",
" Parameters\n",
" items : list data\n",
" \"\"\"\n",
" return [float(i) for i in items]\n",
"\n",
"def pastTime(interval, unit):\n",
" \"\"\"\n",
" current and past time\n",
" Parameters\n",
" interval : time interval\n",
" unit: time unit\n",
" \"\"\"\n",
" curTime = int(time.time())\n",
" if unit == \"d\":\n",
" pastTime = curTime - interval * secInDay\n",
" elif unit == \"h\":\n",
" pastTime = curTime - interval * secInHour\n",
" elif unit == \"m\":\n",
" pastTime = curTime - interval * secInMinute\n",
" else:\n",
" raise ValueError(\"invalid time unit \" + unit)\n",
" return (curTime, pastTime)\n",
"\n",
"def minuteAlign(ts):\n",
" \"\"\"\n",
" minute aligned time\t\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" return int((ts / secInMinute)) * secInMinute\n",
"\n",
"def multMinuteAlign(ts, min):\n",
" \"\"\"\n",
" multi minute aligned time\t\n",
" Parameters\n",
" ts : time stamp in sec\n",
" min : minute value\n",
" \"\"\"\n",
" intv = secInMinute * min\n",
" return int((ts / intv)) * intv\n",
"\n",
"def hourAlign(ts):\n",
" \"\"\"\n",
" hour aligned time\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" return int((ts / secInHour)) * secInHour\n",
"\n",
"def hourOfDayAlign(ts, hour):\n",
" \"\"\"\n",
" hour of day aligned time\n",
" Parameters\n",
" ts : time stamp in sec\n",
" hour : hour of day\n",
" \"\"\"\n",
" day = int(ts / secInDay)\n",
" return (24 * day + hour) * secInHour\n",
"\n",
"def dayAlign(ts):\n",
" \"\"\"\n",
" day aligned time\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" return int(ts / secInDay) * secInDay\n",
"\n",
"def timeAlign(ts, unit):\n",
" \"\"\"\n",
" boundary alignment of time\n",
" Parameters\n",
" ts : time stamp in sec\n",
" unit : unit of time\n",
" \"\"\"\n",
" alignedTs = 0\n",
" if unit == \"s\":\n",
" alignedTs = ts\n",
" elif unit == \"m\":\n",
" alignedTs = minuteAlign(ts)\n",
" elif unit == \"h\":\n",
" alignedTs = hourAlign(ts)\n",
" elif unit == \"d\":\n",
" alignedTs = dayAlign(ts)\n",
" else:\n",
" raise ValueError(\"invalid time unit\")\n",
" return alignedTs\n",
"\n",
"def monthOfYear(ts):\n",
" \"\"\"\n",
" month of year\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" rem = ts % secInYear\n",
" dow = int(rem / secInMonth)\n",
" return dow\n",
"\n",
"def dayOfWeek(ts):\n",
" \"\"\"\n",
" day of week\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" rem = ts % secInWeek\n",
" dow = int(rem / secInDay)\n",
" return dow\n",
"\n",
"def hourOfDay(ts):\n",
" \"\"\"\n",
" hour of day\n",
" Parameters\n",
" ts : time stamp in sec\n",
" \"\"\"\n",
" rem = ts % secInDay\n",
" hod = int(rem / secInHour)\n",
" return hod\n",
"\n",
"def processCmdLineArgs(expectedTypes, usage):\n",
" \"\"\"\n",
" process command line args and returns args as typed values\n",
" Parameters\n",
" expectedTypes : expected data types of arguments\n",
" usage : usage message string\n",
" \"\"\"\n",
" args = []\n",
" numComLineArgs = len(sys.argv)\n",
" numExpected = len(expectedTypes)\n",
" if (numComLineArgs - 1 == len(expectedTypes)):\n",
" try:\n",
" for i in range(0, numExpected):\n",
" if (expectedTypes[i] == typeInt):\n",
" args.append(int(sys.argv[i+1]))\n",
" elif (expectedTypes[i] == typeFloat):\n",
" args.append(float(sys.argv[i+1]))\n",
" elif (expectedTypes[i] == typeString):\n",
" args.append(sys.argv[i+1])\n",
" except ValueError:\n",
" print (\"expected number of command line arguments found but there is type mis match\")\n",
" sys.exit(1)\n",
" else:\n",
" print (\"expected number of command line arguments not found\")\n",
" print (usage)\n",
" sys.exit(1)\n",
" return args\n",
"\n",
"def mutateString(val, numMutate, ctype):\n",
" \"\"\"\n",
" mutate string multiple times\n",
" Parameters\n",
" val : string value\n",
" numMutate : num of mutations\n",
" ctype : type of character to mutate with\n",
" \"\"\"\n",
" mutations = set()\n",
" count = 0\n",
" while count < numMutate:\n",
" j = randint(0, len(val)-1)\n",
" if j not in mutations:\n",
" if ctype == \"alpha\":\n",
" ch = selectRandomFromList(alphaTokens)\n",
" elif ctype == \"num\":\n",
" ch = selectRandomFromList(numTokens)\n",
" elif ctype == \"any\":\n",
" ch = selectRandomFromList(tokens)\n",
" val = val[:j] + ch + val[j+1:]\n",
" mutations.add(j)\n",
" count += 1\n",
" return val\n",
"\n",
"def mutateList(values, numMutate, vmin, vmax):\n",
" \"\"\"\n",
" mutate list multiple times\n",
" Parameters\n",
" values : list value\n",
" numMutate : num of mutations\n",
" vmin : minimum of value range\n",
" vmax : maximum of value range\n",
" \"\"\"\n",
" mutations = set()\n",
" count = 0\n",
" while count < numMutate:\n",
" j = randint(0, len(values)-1)\n",
" if j not in mutations:\n",
" values[j] = np.random.uniform(vmin, vmax)\n",
" count += 1\n",
" return values\n",
"\n",
"\n",
"def swap(values, first, second):\n",
" \"\"\"\n",
" swap two elements\n",
" Parameters\n",
" values : list value\n",
" first : first swap position\n",
" second : second swap position\n",
" \"\"\"\n",
" t = values[first]\n",
" values[first] = values[second]\n",
" values[second] = t\n",
"\n",
"def swapBetweenLists(values1, values2):\n",
" \"\"\"\n",
" swap two elements between 2 lists\n",
" Parameters\n",
" values1 : first list of values\n",
" values2 : second list of values\n",
" \"\"\"\n",
" p1 = randint(0, len(values1)-1)\n",
" p2 = randint(0, len(values2)-1)\n",
" tmp = values1[p1]\n",
" values1[p1] = values2[p2]\n",
" values2[p2] = tmp\n",
"\n",
"def safeAppend(values, value):\n",
" \"\"\"\n",
" append only if not None\n",
" Parameters\n",
" values : list value\n",
" value : value to append\n",
" \"\"\"\n",
" if value is not None:\n",
" values.append(value)\n",
"\n",
"def getAllIndex(ldata, fldata):\n",
" \"\"\"\n",
" get ALL indexes of list elements\n",
" Parameters\n",
" ldata : list data to find index in\n",
" fldata : list data for values for index look up\n",
" \"\"\"\n",
" return list(map(lambda e : fldata.index(e), ldata))\n",
"\n",
"def findIntersection(lOne, lTwo):\n",
" \"\"\"\n",
" find intersection elements between 2 lists\n",
" Parameters\n",
" lOne : first list of data\n",
" lTwo : second list of data\n",
" \"\"\"\n",
" sOne = set(lOne)\n",
" sTwo = set(lTwo)\n",
" sInt = sOne.intersection(sTwo)\n",
" return list(sInt)\n",
"\n",
"def isIntvOverlapped(rOne, rTwo):\n",
" \"\"\"\n",
" checks overlap between 2 intervals\n",
" Parameters\n",
" rOne : first interval boundaries\n",
" rTwo : second interval boundaries\n",
" \"\"\"\n",
" clear = rOne[1] <= rTwo[0] or rOne[0] >= rTwo[1] \n",
" return not clear\n",
"\n",
"def isIntvLess(rOne, rTwo):\n",
" \"\"\"\n",
" checks if first iterval is less than second\n",
" Parameters\n",
" rOne : first interval boundaries\n",
" rTwo : second interval boundaries\n",
" \"\"\"\n",
" less = rOne[1] <= rTwo[0] \n",
" return less\n",
"\n",
"def findRank(e, values):\n",
" \"\"\"\n",
" find rank of value in a list\n",
" Parameters\n",
" e : value to compare with\n",
" values : list data\n",
" \"\"\"\n",
" count = 1\n",
" for ve in values:\n",
" if ve < e:\n",
" count += 1\n",
" return count\n",
"\n",
"def findRanks(toBeRanked, values):\n",
" \"\"\"\n",
" find ranks of values in one list in another list\n",
" Parameters\n",
" toBeRanked : list of values for which ranks are found\n",
" values : list in which rank is found : \n",
" \"\"\"\n",
" return list(map(lambda e: findRank(e, values), toBeRanked))\n",
"\n",
"def formatFloat(prec, value, label = None):\n",
" \"\"\"\n",
" formats a float with optional label\n",
" Parameters\n",
" prec : precision\n",
" value : data value\n",
" label : label for data\n",
" \"\"\"\n",
" st = (label + \" \") if label else \"\"\n",
" formatter = \"{:.\" + str(prec) + \"f}\" \n",
" return st + formatter.format(value)\n",
"\n",
"def formatAny(value, label = None):\n",
" \"\"\"\n",
" formats any obkect with optional label\n",
" Parameters\n",
" value : data value\n",
" label : label for data\n",
" \"\"\"\n",
" st = (label + \" \") if label else \"\"\n",
" return st + str(value)\n",
"\n",
"def printList(values):\n",
" \"\"\"\n",
" pretty print list\n",
" Parameters\n",
" values : list of values\n",
" \"\"\"\n",
" for v in values:\n",
" print(v)\n",
"\n",
"def printMap(values, klab, vlab, precision, offset=16):\n",
" \"\"\"\n",
" pretty print hash map\n",
" Parameters\n",
" values : dictionary of values\n",
" klab : label for key\n",
" vlab : label for value\n",
" precision : precision\n",
" offset : left justify offset\n",
" \"\"\"\n",
" print(klab.ljust(offset, \" \") + vlab)\n",
" for k in values.keys():\n",
" v = values[k]\n",
" ks = toStr(k, precision).ljust(offset, \" \")\n",
" vs = toStr(v, precision)\n",
" print(ks + vs)\n",
"\n",
"def printPairList(values, lab1, lab2, precision, offset=16):\n",
" \"\"\"\n",
" pretty print list of pairs\n",
" Parameters\n",
" values : dictionary of values\n",
" lab1 : first label\n",
" lab2 : second label\n",
" precision : precision\n",
" offset : left justify offset\n",
" \"\"\"\n",
" print(lab1.ljust(offset, \" \") + lab2)\n",
" for (v1, v2) in values:\n",
" sv1 = toStr(v1, precision).ljust(offset, \" \")\n",
" sv2 = toStr(v2, precision)\n",
" print(sv1 + sv2)\n",
"\n",
"def createMap(*values):\n",
" \"\"\"\n",
" create disctionary with results\n",
" Parameters\n",
" values : sequence of key value pairs\n",
" \"\"\"\n",
" result = dict()\n",
" for i in range(0, len(values), 2):\n",
" result[values[i]] = values[i+1]\n",
" return result\n",
"\n",
"def getColMinMax(table, col):\n",
" \"\"\"\n",
" return min, max values of a column\n",
" Parameters\n",
" table : tabular data\n",
" col : column index\n",
" \"\"\"\n",
" vmin = None\n",
" vmax = None\n",
" for rec in table:\n",
" value = rec[col]\n",
" if vmin is None:\n",
" vmin = value\n",
" vmax = value\n",
" else:\n",
" if value < vmin:\n",
" vmin = value\n",
" elif value > vmax:\n",
" vmax = value\n",
" return (vmin, vmax, vmax - vmin)\n",
"\n",
"def createLogger(name, logFilePath, logLevName):\n",
" \"\"\"\n",
" creates logger\n",
" Parameters\n",
" name : logger name\n",
" logFilePath : log file path\n",
" logLevName : log level\n",
" \"\"\"\n",
" logger = logging.getLogger(name)\n",
" fHandler = logging.handlers.RotatingFileHandler(logFilePath, maxBytes=1048576, backupCount=4)\n",
" logLev = logLevName.lower()\n",
" if logLev == \"debug\":\n",
" logLevel = logging.DEBUG\n",
" elif logLev == \"info\":\n",
" logLevel = logging.INFO\n",
" elif logLev == \"warning\":\n",
" logLevel = logging.WARNING\n",
" elif logLev == \"error\":\n",
" logLevel = logging.ERROR\n",
" elif logLev == \"critical\":\n",
" logLevel = logging.CRITICAL\n",
" else:\n",
" raise ValueError(\"invalid log level name \" + logLevelName)\n",
" fHandler.setLevel(logLevel)\n",
" fFormat = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n",
" fHandler.setFormatter(fFormat)\n",
" logger.addHandler(fHandler)\n",
" logger.setLevel(logLevel)\n",
" return logger\n",
"\n",
"@contextmanager\n",
"def suppressStdout():\n",
" \"\"\"\n",
" suppress stdout\n",
" Parameters\n",
" \"\"\"\n",
" with open(os.devnull, \"w\") as devnull:\n",
" oldStdout = sys.stdout\n",
" sys.stdout = devnull\n",
" try: \n",
" yield\n",
" finally:\n",
" sys.stdout = oldStdout\n",
"\n",
"def exitWithMsg(msg):\n",
" \"\"\"\n",
" print message and exit\n",
" Parameters\n",
" msg : message\n",
" \"\"\"\n",
" print(msg + \" -- quitting\")\n",
" sys.exit(0)\n",
"\n",
"def drawLine(data, yscale=None):\n",
" \"\"\"\n",
" line plot\n",
" Parameters\n",
" data : list data\n",
" yscale : y axis scale\n",
" \"\"\"\n",
" plt.plot(data)\n",
" if yscale:\n",
" step = int(yscale / 10)\n",
" step = int(step / 10) * 10\n",
" plt.yticks(range(0, yscale, step))\n",
" plt.show()\n",
"\n",
"def drawPlot(x, y, xlabel, ylabel):\n",
" \"\"\"\n",
" line plot\n",
" Parameters\n",
" x : x values\n",
" y : y values\n",
" xlabel : x axis label\n",
" ylabel : y axis label\n",
" \"\"\"\n",
" plt.plot(x,y)\n",
" plt.xlabel(xlabel)\n",
" plt.ylabel(ylabel)\n",
" plt.show()\n",
"\n",
"def drawPairPlot(x, y1, y2, xlabel,ylabel, y1label, y2label):\n",
" \"\"\"\n",
" line plot of 2 lines\n",
" Parameters\n",
" x : x values\n",
" y1 : first y values\n",
" y2 : second y values\n",
" xlabel : x labbel\n",
" ylabel : y label\n",
" y1label : first plot label\n",
" y2label : second plot label\n",
" \"\"\"\n",
" plt.plot(x, y1, label = y1label)\n",
" plt.plot(x, y2, label = y2label)\n",
" plt.xlabel(xlabel)\n",
" plt.ylabel(ylabel)\n",
" plt.legend()\n",
" plt.show()\n",
"\n",
"def drawHist(ldata, myTitle, myXlabel, myYlabel, nbins=10):\n",
" \"\"\"\n",
" draw histogram\n",
" Parameters\n",
" ldata : list data\n",
" myTitle : title\n",
" myXlabel : x label\n",
" myYlabel : y label \n",
" nbins : num of bins\n",
" \"\"\"\n",
" plt.hist(ldata, bins=nbins, density=True)\n",
" plt.title(myTitle)\n",
" plt.xlabel(myXlabel)\n",
" plt.ylabel(myYlabel)\n",
" plt.show()\n",
"\n",
"def saveObject(obj, filePath):\n",
" \"\"\"\n",
" saves an object\n",
" Parameters\n",
" obj : object\n",
" filePath : file path for saved object\n",
" \"\"\"\n",
" with open(filePath, \"wb\") as outfile:\n",
" pickle.dump(obj,outfile)\n",
"\n",
"def restoreObject(filePath):\n",
" \"\"\"\n",
" restores an object\n",
" Parameters\n",
" filePath : file path to restore object from\n",
" \"\"\"\n",
" with open(filePath, \"rb\") as infile:\n",
" obj = pickle.load(infile)\n",
" return obj\n",
"\n",
"def isNumeric(data):\n",
" \"\"\"\n",
" true if all elements int or float\n",
" Parameters\n",
" data : numeric data list\n",
" \"\"\"\n",
" if type(data) == list or type(data) == np.ndarray:\n",
" col = pd.Series(data)\n",
" else:\n",
" col = data\n",
" return col.dtype == np.int32 or col.dtype == np.int64 or col.dtype == np.float32 or col.dtype == np.float64\n",
"\n",
"def isInteger(data):\n",
" \"\"\"\n",
" true if all elements int \n",
" Parameters\n",
" data : numeric data list\n",
" \"\"\"\n",
" if type(data) == list or type(data) == np.ndarray:\n",
" col = pd.Series(data)\n",
" else:\n",
" col = data\n",
" return col.dtype == np.int32 or col.dtype == np.int64\n",
"\n",
"def isFloat(data):\n",
" \"\"\"\n",
" true if all elements float\n",
" Parameters\n",
" data : numeric data list\n",
" \"\"\"\n",
" if type(data) == list or type(data) == np.ndarray:\n",
" col = pd.Series(data)\n",
" else:\n",
" col = data\n",
" return col.dtype == np.float32 or col.dtype == np.float64\n",
"\n",
"def isBinary(data):\n",
" \"\"\"\n",
" true if all elements either 0 or 1\n",
" Parameters\n",
" data : binary data\n",
" \"\"\"\n",
" re = next((d for d in data if not (type(d) == int and (d == 0 or d == 1))), None)\n",
" return (re is None)\n",
"\n",
"def isCategorical(data):\n",
" \"\"\"\n",
" true if all elements int or string\n",
" Parameters\n",
" data : data value\n",
" \"\"\"\n",
" re = next((d for d in data if not (type(d) == int or type(d) == str)), None)\n",
" return (re is None)\n",
"\n",
"def assertEqual(value, veq, msg):\n",
" \"\"\"\n",
" assert equal to\n",
" Parameters\n",
" value : value\n",
" veq : value to be equated with\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value == veq , msg\n",
"\n",
"def assertGreater(value, vmin, msg):\n",
" \"\"\"\n",
" assert greater than \n",
" Parameters\n",
" value : value\n",
" vmin : minimum value\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value > vmin , msg\n",
"\n",
"def assertGreaterEqual(value, vmin, msg):\n",
" \"\"\"\n",
" assert greater than \n",
" Parameters\n",
" value : value\n",
" vmin : minimum value\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value >= vmin , msg\n",
"\n",
"def assertLesser(value, vmax, msg):\n",
" \"\"\"\n",
" assert less than\n",
" Parameters\n",
" value : value\n",
" vmax : maximum value\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value < vmax , msg\n",
"\n",
"def assertLesserEqual(value, vmax, msg):\n",
" \"\"\"\n",
" assert less than\n",
" Parameters\n",
" value : value\n",
" vmax : maximum value\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value <= vmax , msg\n",
"\n",
"def assertWithinRange(value, vmin, vmax, msg):\n",
" \"\"\"\n",
" assert within range\n",
" Parameters\n",
" value : value\n",
" vmin : minimum value\n",
" vmax : maximum value\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value >= vmin and value <= vmax, msg\n",
"\n",
"def assertInList(value, values, msg):\n",
" \"\"\"\n",
" assert contains in a list\n",
" Parameters\n",
" value ; balue to check for inclusion\n",
" values : list data\n",
" msg : error msg\n",
" \"\"\"\n",
" assert value in values, msg\n",
"\n",
"def maxListDist(l1, l2):\n",
" \"\"\"\n",
" maximum list element difference between 2 lists\n",
" Parameters\n",
" l1 : first list data\n",
" l2 : second list data\n",
" \"\"\"\n",
" dist = max(list(map(lambda v : abs(v[0] - v[1]), zip(l1, l2))))\t\n",
" return dist\n",
"\n",
"def fileLineCount(fPath):\n",
" \"\"\" \n",
" number of lines ina file \n",
" Parameters\n",
" fPath : file path\n",
" \"\"\"\n",
" with open(fPath) as f:\n",
" for i, li in enumerate(f):\n",
" pass\n",
" return (i + 1)\n",
"\n",
"def getAlphaNumCharCount(sdata):\n",
" \"\"\" \n",
" number of alphabetic and numeric charcters in a string \n",
" Parameters\n",
" sdata : string data\n",
" \"\"\"\n",
" acount = 0\n",
" ncount = 0\n",
" scount = 0\n",
" ocount = 0\n",
" assertEqual(type(sdata), str, \"input must be string\")\n",
" for c in sdata:\n",
" if c.isnumeric():\n",
" ncount += 1\n",
" elif c.isalpha():\n",
" acount += 1\n",
" elif c.isspace():\n",
" scount += 1\n",
" else:\n",
" ocount += 1\n",
" r = (acount, ncount, ocount)\n",
" return r\n",
"\n",
"class StepFunction:\n",
" \"\"\"\n",
" step function\n",
" Parameters\n",
" \"\"\"\n",
" def __init__(self, *values):\n",
" \"\"\"\n",
" initilizer\n",
"\n",
" Parameters\n",
" values : list of tuples, wich each tuple containing 2 x values and corresponding y value\n",
" \"\"\"\n",
" self.points = values\n",
"\n",
" def find(self, x):\n",
" \"\"\"\n",
" finds step function value\n",
"\n",
" Parameters\n",
" x : x value\n",
" \"\"\"\n",
" found = False\n",
" y = 0\n",
" for p in self.points:\n",
" if (x >= p[0] and x < p[1]):\n",
" y = p[2]\n",
" found = True\n",
" break\n",
"\n",
" if not found:\n",
" l = len(self.points)\n",
" if (x < self.points[0][0]):\n",
" y = self.points[0][2]\n",
" elif (x > self.points[l-1][1]):\n",
" y = self.points[l-1][2]\n",
" return y\n",
"\n",
"\n",
"class DummyVarGenerator:\n",
" \"\"\"\n",
" dummy variable generator for categorical variable\n",
" \"\"\"\n",
" def __init__(self, rowSize, catValues, trueVal, falseVal, delim=None):\n",
" \"\"\"\n",
" initilizer\n",
"\n",
" Parameters\n",
" rowSize : row size\n",
" catValues : dictionary with field index as key and list of categorical values as value\n",
" trueVal : true value, typically \"1\"\n",
" falseval : false value , typically \"0\"\n",
" delim : field delemeter\n",
" \"\"\"\n",
" self.rowSize = rowSize\n",
" self.catValues = catValues\n",
" numCatVar = len(catValues)\n",
" colCount = 0\n",
" for v in self.catValues.values():\n",
" colCount += len(v)\n",
" self.newRowSize = rowSize - numCatVar + colCount\n",
" #print (\"new row size {}\".format(self.newRowSize))\n",
" self.trueVal = trueVal\n",
" self.falseVal = falseVal\n",
" self.delim = delim\n",
"\n",
" def processRow(self, row):\n",
" \"\"\"\n",
" encodes categorical variables, returning as delemeter separate dstring or list\n",
"\n",
" Parameters\n",
" row : row either delemeter separated string or list\n",
" \"\"\"\n",
" if self.delim is not None:\n",
" rowArr = row.split(self.delim)\n",
" msg = \"row does not have expected number of columns found \" + str(len(rowArr)) + \" expected \" + str(self.rowSize)\n",
" assert len(rowArr) == self.rowSize, msg\n",
" else:\n",
" rowArr = row\n",
"\n",
" newRowArr = []\n",
" for i in range(len(rowArr)):\n",
" curVal = rowArr[i]\n",
" if (i in self.catValues):\n",
" values = self.catValues[i]\n",
" for val in values:\n",
" if val == curVal:\n",
" newVal = self.trueVal\n",
" else:\n",
" newVal = self.falseVal\n",
" newRowArr.append(newVal)\n",
" else:\n",
" newRowArr.append(curVal)\n",
" assert len(newRowArr) == self.newRowSize, \"invalid new row size \" + str(len(newRowArr)) + \" expected \" + str(self.newRowSize)\n",
" encRow = self.delim.join(newRowArr) if self.delim is not None else newRowArr\n",
" return encRow\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|