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
|
/*
Project: Adun
Copyright (C) 2006 Michael Johnston & Jordi Villa-Freixa
Author: Michael Johnston
Created: 2005-06-02 15:34:11 +0200 by michael johnston
This application is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This application is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#include "AdunKernel/AdunDataMatrix.h"
static NSArray* allowedDataTypes;
static NSDictionary* dataTypeToClassMap;
static NSDictionary* classToDataTypeMap;
#ifndef GNUSTEP
static NSArray* integerEncodings;
#endif
@class AdMutableDataMatrix;
#ifndef GNUSTEP
//OSX - Definitons of NSIntNumber and NSDoubleNumber so they
//can be used with Cocoa. The only use of these classes is
//as keys in the classToDataTypeMap and values in dataTypeToClassMap.
@interface NSIntNumber: NSNumber
{
}
@end
@implementation NSIntNumber: NSNumber
@end
@interface NSDoubleNumber: NSNumber
{
}
@end
@implementation NSDoubleNumber
@end
#else
@class NSDoubleNumber;
@class NSIntNumber;
#endif
@implementation NSArray (AdKernelAdditions)
- (NSArray*) subarrayFromElementSelection: (NSIndexSet*) indexSet
{
int index, i;
unsigned int* buffer;
NSMutableArray* subarray = [NSMutableArray new];
NSArray* arrayCopy;
//Check for range problems
index = [indexSet lastIndex];
if(index != NSNotFound)
{
if(index >= (int)[self count])
[NSException raise: NSRangeException
format: @"Index %d is out of range (%d)",
index,
[self count]];
//FIXME: Switch to using buffer for efficency
buffer = (unsigned int*)malloc([indexSet count]*sizeof(unsigned int));
[indexSet getIndexes: buffer
maxCount: [indexSet count]
inIndexRange: NULL];
for(i=0; i<(int)[indexSet count]; i++)
[subarray addObject:
[self objectAtIndex: buffer[i]]];
free(buffer);
}
arrayCopy = [subarray copy];
[subarray release];
return [arrayCopy autorelease];
}
@end
/*
Category containing method for converting added elements
to the correct types for each column
*/
@interface AdDataMatrix (PrivateElementConversions)
/**
Returns the allowed class \e object is descended from
or nil if there is none.
*/
- (Class) allowedSuperClassForObject: (id) object;
/**
Converts object to the correct representation for column. If
no dataType has been set for columnIndex an exception is raised.
If the conversion if not possible raise an exception.
*/
- (id) representationOfObject: (id) object forColumn: (unsigned int) columnIndex;
/**
Sets the data type for each column to be the type defined by
the class of the corresponding element in array.
If any of the element classes have no corresponding type
an NSInvalidArgumentException is raised.
If the number of elements in array are not equal to the number
of columns an NSInvalidArgumentException is raised.
In the case of an exception being raised no data types are set.
*/
- (void) setDataTypesToTypesInArray: (NSArray*) array;
@end
@implementation AdDataMatrix (PrivateElementConversions)
/*
All NSNumber subclasses and NSString respond
to stringValue, intValue and doubleValue */
- (id) convertObject: (id) object toClassForDataType: (NSString*) type
{
if([type isEqual: @"string"])
return [object stringValue];
else if([type isEqual: @"int"])
return [NSNumber numberWithInt: [object intValue]];
else if([type isEqual: @"double"])
return [NSNumber numberWithDouble: [object doubleValue]];
NSWarnLog(@"Cant convert to class for data type %@", type);
return nil;
}
- (Class) allowedSuperClassForObject: (id) object
{
NSEnumerator* allowedClassesEnum;
Class class;
#ifdef GNUSTEP
allowedClassesEnum = [[dataTypeToClassMap allValues] objectEnumerator];
while((class = [allowedClassesEnum nextObject]))
if([object isKindOfClass: class])
return class;
#else
//OSX code - The above wont work since the dataTypeToClassMap
//contains NSIntNumber and NSDoubleNumber for allowed superclasses and
//these dont exist in Cocoa. Further its difficult to determine
//what the Cocoa analogs are. Instead we find if the encoded number
//is of int or double type and then return NSIntNumber and NSDoubleNumber
//depending. Thus the rest of the class is essentially "decieved" into
//behaving as it does on GNUstep as this is the only place where the
//distinction matters (The class is only used to determine the data type
//e.g. int string or double).
NSString* objectiveCType;
if([object isKindOfClass: [NSNumber class]])
{
objectiveCType = [NSString stringWithCString: [object objCType]
encoding: NSUTF8StringEncoding];
if([integerEncodings containsObject: objectiveCType])
return [NSIntNumber class];
else
return [NSDoubleNumber class];
}
else if([object isKindOfClass: [NSString class]])
return [NSString class];
#endif
return nil;
}
- (id) representationOfObject: (id) object forColumn: (unsigned int) columnIndex
{
NSString *dataType;
dataType = [columnDataTypes objectAtIndex: columnIndex];
//check if the class of value is of the correct type
//(or a descendant of that type). If not we convert it.
if(![object isKindOfClass: [dataTypeToClassMap objectForKey: dataType]])
{
object = [self convertObject: object toClassForDataType: dataType];
if(object == nil)
[NSException raise: NSInvalidArgumentException
format: @"Cannot convert object of class %@", [object class]];
}
return object;
}
- (void) setDataTypesToTypesInArray: (NSArray*) array
{
NSMutableArray* typeArray = [NSMutableArray new];
NSEnumerator* arrayEnum;
NSString *dataType;
id element;
Class class;
if([array count] != numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Array has incorrect number of entries"];
arrayEnum = [array objectEnumerator];
while((element = [arrayEnum nextObject]))
{
//First check if the elements class is a subclass of any
//of the allowed objects.
//Otherwise check if the class is in classToDataTypeMap
//Note: On OSX the first condition is always true for
//NSNumber/NSString based objects.
if((class = [self allowedSuperClassForObject: element]) != nil)
{
dataType = [classToDataTypeMap objectForKey:
NSStringFromClass(class)];
}
else
{
dataType = [classToDataTypeMap objectForKey:
NSStringFromClass([element class])];
if(dataType == nil)
[NSException raise: NSInvalidArgumentException
format: @"AdDataMatrix - Cannot insert objects of class %@",
[element class]];
}
[typeArray addObject: dataType];
}
[columnDataTypes addObjectsFromArray: typeArray];
[typeArray release];
}
@end
/*
The AdDataMatrix class implementation
*/
@implementation AdDataMatrix
/*
* Class Methods
*/
+ (void) initialize
{
static BOOL done = NO;
if(!done)
{
allowedDataTypes = [NSArray arrayWithObjects:
@"string",
@"double",
@"int", nil];
[allowedDataTypes retain];
//the classes each data type will be stored in
dataTypeToClassMap = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString class], @"string",
[NSDoubleNumber class], @"double",
[NSIntNumber class], @"int", nil];
[dataTypeToClassMap retain];
//Dictionary mapping Foundation classes to data types.
//Subclasses of the allowed classes are not included here.
classToDataTypeMap = [NSDictionary dictionaryWithObjectsAndKeys:
@"string", @"NSString",
@"double", @"NSDoubleNumber",
@"double", @"NSFloatNumber",
@"int", @"NSShortNumber",
@"int", @"NSUShortNumber",
@"int", @"NSIntNumber",
@"int", @"NSUIntNumber",
@"int", @"NSLongNumber",
@"int", @"NSULongNumber",
@"int", @"NSLongLongNumber",
@"int", @"NSULongLongNumber",
nil];
[classToDataTypeMap retain];
#if NeXT_RUNTIME == 1
//On OSX we need to check an NSNumbers objcType to
//determine if its an int or double. If this method
//works the entire class may be changed to use it.
integerEncodings = [NSArray arrayWithObjects:
@"i", @"s", @"l", @"q", @"I", @"S", @"L", @"Q", nil];
[integerEncodings retain];
#endif
done = YES;
}
}
+ (id) matrixFromGSLVector: (gsl_vector*) aVector
{
return [[[AdDataMatrix alloc]
initWithGSLVector: aVector
columnHeaders: nil
name: nil] autorelease];
}
+ (id) matrixFromGSLMatrix: (gsl_matrix*) aMatrix
{
return [[[AdDataMatrix alloc]
initWithGSLMatrix: aMatrix
columnHeaders: nil
name: nil] autorelease];
}
+ (id) matrixFromADMatrix: (AdMatrix*) aMatrix
{
return [[[AdDataMatrix alloc]
initWithADMatrix: aMatrix
columnHeaders: nil
name: nil] autorelease];
}
+ (id) matrixFromStringRepresentation: (NSString*) aString
{
return [[[AdDataMatrix alloc]
initWithStringRepresentation: aString]
autorelease];
}
//Initialisation
- (NSArray*) _trimAndRemoveEmptyStrings: (NSArray*) array
{
NSArray *editedArray;
NSMutableArray *trimmedArray;
NSString *element;
NSEnumerator* arrayEnum;
//Trim the strings
trimmedArray = [NSMutableArray array];
arrayEnum = [array objectEnumerator];
while((element = [arrayEnum nextObject]))
{
[trimmedArray addObject:
[element stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]];
}
//In case the last element in the row was followed by a ","
//This will have created an empty last object
if([[trimmedArray lastObject] isEqual: @""])
{
editedArray = [trimmedArray subarrayWithRange:
NSMakeRange(0, [trimmedArray count] - 1)];
}
else
editedArray = trimmedArray;
return editedArray;
}
- (id) initWithStringRepresentation: (NSString*) aString
{
return [self initWithStringRepresentation: aString name: nil];
}
- (id) initWithStringRepresentation: (NSString*) aString name: (NSString*) nameString
{
NSArray *row, *headers;
NSMutableArray *rows, *array;
NSString* string;
NSEnumerator* arrayEnum;
rows = [NSMutableArray array];
array = [[[aString componentsSeparatedByString: @"\n"]
mutableCopy] autorelease];
headers = [[array objectAtIndex: 0]
componentsSeparatedByString: @","];
headers = [self _trimAndRemoveEmptyStrings: headers];
[array removeObjectAtIndex: 0];
arrayEnum = [array objectEnumerator];
while((string = [arrayEnum nextObject]))
{
row = [self _trimAndRemoveEmptyStrings:
[string componentsSeparatedByString: @","]];
//If the row is empty dont add it
//This will happen with incorrect string representations
//but also if the last line containing numbers ended in "\n"
if([row count] != 0)
[rows addObject: row];
}
return [self initWithRows: rows
columnHeaders: headers
name: nameString];
}
- (id) initWithGSLVector: (gsl_vector*) aVector
columnHeaders: (NSArray*) anArray
name: (NSString*) aString
{
int i, j;
NSMutableArray* array;
array = [NSMutableArray new];
for(i=0; i<(int)aVector->size; i++)
for(j=0; j<1; j++)
[array addObject:
[NSArray arrayWithObject:
[NSNumber numberWithDouble: gsl_vector_get(aVector, i)]]];
[self initWithRows: array
columnHeaders: anArray
name: aString];
[array release];
return self;
}
- (id) initWithGSLMatrix: (gsl_matrix*) aMatrix
columnHeaders: (NSArray*) anArray
name: (NSString*) aString
{
int i, j;
NSMutableArray* array, *row;
array = [NSMutableArray new];
for(i=0; i<(int)aMatrix->size1; i++)
{
row = [NSMutableArray array];
for(j=0; j<(int)aMatrix->size2; j++)
{
[row addObject: [NSNumber
numberWithDouble: gsl_matrix_get(aMatrix, i, j)]];
}
[array addObject: row];
}
[self initWithRows: array
columnHeaders: anArray
name: aString];
[array release];
return self;
}
- (id) initWithADMatrix: (AdMatrix*) aMatrix
columnHeaders: (NSArray*) anArray
name: (NSString*) aString
{
int i, j;
NSMutableArray* array, *row;
array = [NSMutableArray new];
for(i=0; i<aMatrix->no_rows; i++)
{
row = [NSMutableArray array];
for(j=0; j<aMatrix->no_columns; j++)
{
[row addObject: [NSNumber
numberWithDouble: aMatrix->matrix[i][j]]];
}
[array addObject: row];
}
[self initWithRows: array
columnHeaders: anArray
name: aString];
[array release];
return self;
}
- (id) initWithDataMatrix: (AdDataMatrix*) dataMatrix
columnHeaders: (NSArray*) anArray
name: (NSString*) aString
{
NSMutableArray* rows;
NSEnumerator *rowEnum;
id row;
rows = [NSMutableArray new];
rowEnum = [dataMatrix rowEnumerator];
while((row = [rowEnum nextObject]))
[rows addObject: row];
if(anArray == nil && dataMatrix != nil)
anArray = [dataMatrix columnHeaders];
if(aString == nil && dataMatrix != nil)
aString = [dataMatrix name];
[self initWithRows: rows
columnHeaders: anArray
name: aString];
[rows release];
return self;
}
- (id) initWithRows: (NSArray*) rows
columnHeaders: (NSArray*) anArray
name: (NSString*) aString
{
int i;
NSEnumerator *rowEnum;
NSArray *row, *firstRow;
NSMutableArray* convertedRow;
id element;
if((self = [super init]))
{
numberOfColumns = 0;
numberOfRows = 0;
matrix = [NSMutableArray new];
columnHeaders = [NSMutableArray new];
columnDataTypes = [NSMutableArray new];
if(rows != nil && ([rows count] > 0))
{
numberOfRows = [rows count];
firstRow = [rows objectAtIndex: 0];
if(![firstRow isKindOfClass: [NSArray class]])
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"The first element in rows is not an array"];
}
else
numberOfColumns = [[rows objectAtIndex: 0] count];
//Set the column data types.
[self setDataTypesToTypesInArray: firstRow];
//Go through all the rows and converting the
//elements and adding them to the matrix
rowEnum = [rows objectEnumerator];
while((row = [rowEnum nextObject]))
{
//Check all rows have the same number of elements
if([row count] == numberOfColumns)
{
convertedRow = [NSMutableArray array];
for(i=0; i<(int)[row count]; i++)
{
element = [self representationOfObject:
[row objectAtIndex: i]
forColumn: i];
[convertedRow addObject: element];
}
[matrix addObject: convertedRow];
}
else
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"The supplied rows must all have the same length"];
}
}
}
//Use the user supplied name if any.
if(aString == nil)
name = [@"None" retain];
else
name = [aString copy];
//Check headers
if(anArray != nil)
{
//If no rows exist numberOfColumns wont have been set yet.
if(rows == nil || ([rows count] == 0))
numberOfColumns = [anArray count];
if([anArray count] != numberOfColumns)
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"Number of headers %@ does not match number of columns %d",
[anArray count], numberOfColumns];
}
else
columnHeaders = [anArray mutableCopy];
}
else
{
for(i=0; i<(int)numberOfColumns; i++)
[columnHeaders addObject:
[NSString stringWithFormat: @"Column %d", i]];
}
}
return self;
}
- (id) initWithRows: (NSArray*) rows
name: (NSString*) aString
{
return [self initWithRows: rows
columnHeaders: nil
name: aString];
}
- (id) initWithRows: (NSArray*) rows
columnHeaders: (NSArray*) anArray
{
return [self initWithRows: rows
columnHeaders: anArray
name: nil];
}
- (id) initWithRows: (NSArray*) rows
{
return [self initWithRows: rows
columnHeaders: nil
name: nil];
}
- (id) init
{
return [self initWithRows: nil];
}
- (void) dealloc
{
[matrix release];
[columnDataTypes release];
[columnHeaders release];
[name release];
[super dealloc];
}
- (NSString*) stringRepresentation
{
NSMutableString* string = [NSMutableString string];
NSEnumerator* headerEnum, *rowEnum, *valueEnum;
id header, row, value;
headerEnum = [columnHeaders objectEnumerator];
while((header = [headerEnum nextObject]))
[string appendFormat: @"%@, ", header];
[string appendString: @"\n"];
rowEnum = [self rowEnumerator];
while((row = [rowEnum nextObject]))
{
valueEnum = [row objectEnumerator];
while((value = [valueEnum nextObject]))
[string appendFormat: @"%@, ", value];
[string appendString: @"\n"];
}
return [[string copy] autorelease];
}
- (NSString*) description
{
int i;
unsigned int width;
NSMutableString* string = [NSMutableString string];
NSEnumerator* headerEnum;
id header;
width = 0;
headerEnum = [columnHeaders objectEnumerator];
while((header = [headerEnum nextObject]))
if(width < [header length])
width = [header length];
[string appendFormat: @"%@ - ", name];
[string appendFormat: @"Dimensions - %d x %d\n\n",
numberOfRows, numberOfColumns];
[string appendString: @"Column Headers:\n\t"];
headerEnum = [columnHeaders objectEnumerator];
i = 0;
while((header = [headerEnum nextObject]))
{
i++;
[string appendFormat: @"%-*@", width + 4, header];
if(i%5 == 0)
[string appendString: @"\n\t"];
}
[string appendString: @"\n"];
return string;
}
/*
* Accessing Elements
*/
- (id) elementAtRow: (unsigned int) rowIndex
column: (unsigned int) columnIndex;
{
return [[matrix objectAtIndex: rowIndex] objectAtIndex: columnIndex];
}
- (id) elementAtRow: (unsigned int) row
ofColumnWithHeader: (NSString*) columnHeader
{
int columnIndex;
if((columnIndex = [columnHeaders indexOfObject: columnHeader]) == NSNotFound)
[NSException raise: NSInvalidArgumentException
format: @"Column header %@ does not exist", columnHeader];
return [self elementAtRow: row
column: columnIndex];
}
- (NSArray*) matrixRows
{
NSWarnLog(@"This method is deprecated - use row: or rowEnumerator instead");
return matrix;
}
- (NSArray*) column: (unsigned int) columnIndex
{
NSMutableArray* columnCopy = [NSMutableArray array];
[self addColumn: columnIndex toArray: columnCopy];
return [[columnCopy copy] autorelease];
}
- (NSArray*) columnWithHeader: (NSString*) columnHeader
{
int columnIndex;
if((columnIndex = [columnHeaders indexOfObject: columnHeader]) == NSNotFound)
[NSException raise: NSInvalidArgumentException
format: @"Column header %@ does not exist", columnHeader];
return [self column: columnIndex];
}
- (NSArray*) row: (unsigned int) rowIndex
{
if(rowIndex >= numberOfRows)
[NSException raise: NSInvalidArgumentException
format: @" Row %d does not exist", rowIndex];
return [NSArray arrayWithArray:
[matrix objectAtIndex: rowIndex]];
}
- (void) addRow: (unsigned int) rowIndex toArray: (NSMutableArray*) anArray
{
if(rowIndex >= numberOfRows)
[NSException raise: NSInvalidArgumentException
format: @" Row %d does not exist", rowIndex];
[anArray addObjectsFromArray:
[matrix objectAtIndex: rowIndex]];
}
- (void) addColumn: (unsigned int) columnIndex toArray: (NSMutableArray*) anArray
{
int i;
id object;
if(columnIndex >= numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @" Column %d does not exist", columnIndex];
for(i = 0; i<(int)numberOfRows; i++)
{
object = [[matrix objectAtIndex: i] objectAtIndex: columnIndex];
[anArray addObject: object];
}
}
- (void) addColumnWithHeader: (NSString*) columnHeader
toArray: (NSMutableArray*) anArray
{
int columnIndex;
if((columnIndex = [columnHeaders indexOfObject: columnHeader]) == NSNotFound)
[NSException raise: NSInvalidArgumentException
format: @"Column header %@ does not exist", columnHeader];
[self addColumn: columnIndex toArray: anArray];
}
- (NSEnumerator*) rowEnumerator
{
return [matrix objectEnumerator];
}
/*
* C Representations
*/
- (AdMatrix*) cRepresentation
{
int i,j;
AdMatrix* cMatrix;
cMatrix = [[AdMemoryManager appMemoryManager]
allocateMatrixWithRows: numberOfRows
withColumns: numberOfColumns];
for(i=0;i<(int)numberOfRows; i++)
for(j=0; j<(int)numberOfColumns; j++)
cMatrix->matrix[i][j] = [[self elementAtRow: i
column: j] doubleValue];
return cMatrix;
}
- (void) cRepresentationUsingBuffer: (AdMatrix*) aMatrix
{
int i,j;
if(aMatrix->no_rows != (int)numberOfRows)
[NSException raise: NSInvalidArgumentException
format: @"Provided buffer has incorrect number of rows - required %d, provided %d",
aMatrix->no_rows,
numberOfRows];
if(aMatrix->no_columns != (int)numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Provided buffer has incorrect number of columns - required %d, provided %d",
aMatrix->no_columns,
numberOfColumns];
for(i=0;i<(int)numberOfRows; i++)
for(j=0; j<(int)numberOfColumns; j++)
aMatrix->matrix[i][j] = [[self elementAtRow: i
column: j] doubleValue];
}
/*
* Setters and Getters
*/
- (unsigned int) numberOfRows
{
return numberOfRows;
}
- (unsigned int) numberOfColumns
{
return numberOfColumns;
}
- (NSArray*) columnHeaders
{
return [[columnHeaders copy] autorelease];
}
- (unsigned int) indexOfColumnWithHeader: (NSString*) header
{
return [columnHeaders indexOfObject: header];
}
- (NSArray*) columnDataTypes
{
return [[columnDataTypes copy] autorelease];
}
- (NSString*) dataTypeForColumn: (unsigned int) columnIndex
{
if(columnIndex >= numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Column %d does not exist", columnIndex];
return [columnDataTypes objectAtIndex: columnIndex];
}
- (NSString*) dataTypeForColumnWithHeader: (NSString*) columnHeader
{
int columnIndex;
if((columnIndex = [columnHeaders indexOfObject: columnHeader]) == NSNotFound)
[NSException raise: NSInvalidArgumentException
format: @"Column header %@ does not exist", columnHeader];
return [columnDataTypes objectAtIndex: columnIndex];
}
- (NSString*) name
{
return name;
}
/*
* Printing the Matrix
*/
- (void) printMatrix
{
unsigned int i;
for(i=0; i<numberOfRows; i++)
NSLog(@"%@\n", [[matrix objectAtIndex: i] componentsJoinedByString: @" "]);
}
- (BOOL) writeMatrixToFile: (NSString*) filename
{
int i;
FILE* file_p;
file_p = fopen([filename cString], "w");
if(file_p == NULL)
return NO;
if(columnHeaders != nil)
GSPrintf(file_p, @"%@\n",
[columnHeaders componentsJoinedByString: @" "]);
for(i=0;i<(int)numberOfRows; i++)
GSPrintf(file_p, @"%@\n",
[[matrix objectAtIndex: i]
componentsJoinedByString: @" "]);
fclose(file_p);
return YES;
}
/*
* Searching the matrix
*/
/**
Returns an NSIndexSet containing the indexes of rows containing \e element
*/
- (NSIndexSet*) indexesOfRowsContainingElement: (id) element
{
int i;
NSArray* row;
NSIndexSet* setCopy;
NSMutableIndexSet* indexSet = [NSMutableIndexSet new];
for(i=0; i<(int)numberOfRows; i++)
{
row = [matrix objectAtIndex: i];
if([row containsObject: element])
[indexSet addIndex: i];
}
setCopy = [[indexSet copy] autorelease];
[indexSet release];
return setCopy;
}
/**
Returns an NSIndexSet containing the indexes of rows that match \e array.
A match is found if the array contains the same number of objects as the
row and objects at a given index in each array satisfy the isEqual: test.
*/
- (NSIndexSet*) indexesOfRowsMatchingArray: (NSArray*) anArray
{
int i;
NSArray* row;
NSIndexSet* setCopy;
NSMutableIndexSet* indexSet = [NSMutableIndexSet new];
//Only search if anArray is the correct size
if([anArray count] == numberOfColumns)
{
for(i=0; i<(int)numberOfRows; i++)
{
row = [matrix objectAtIndex: i];
if([row isEqualToArray: anArray])
[indexSet addIndex: i];
}
}
setCopy = [[indexSet copy] autorelease];
[indexSet release];
return setCopy;
}
/*
* Deriving new matrices
*/
/**
Returns a new AdDataMatrix instance containing only the rows
specified by the indexes in \e indexSet.
The submatrix has the same headers and name as the receiver.
If any index in \e indexSet exceeds the range of rows in the reciever
an NSRangeException is raised.
*/
- (AdDataMatrix*) submatrixFromRowSelection: (NSIndexSet*) indexSet
{
int index, i;
unsigned int* buffer;
NSMutableArray* rows = [NSMutableArray new];
AdDataMatrix* submatrix;
//Check for range problems
index = [indexSet lastIndex];
if(index != NSNotFound)
{
if(index >= (int)numberOfRows)
[NSException raise: NSRangeException
format: @"Index %d is out of row range (%d)",
index,
numberOfRows - 1];
//Dont use subarrayFromElementSelection: since that
//will return an array containing the actual NSMutableArrays
//used by the object.
buffer = (unsigned int*)malloc([indexSet count]*sizeof(unsigned int));
[indexSet getIndexes: buffer
maxCount: [indexSet count]
inIndexRange: NULL];
for(i=0; i<(int)[indexSet count]; i++)
[rows addObject:
[self row: buffer[i]]];
free(buffer);
}
submatrix = [[AdDataMatrix alloc]
initWithRows: rows
columnHeaders: [self columnHeaders]
name: [self name]];
[rows release];
return [submatrix autorelease];
}
/**
Returns a new AdDataMatrix instance containing only the columns
specified by the indexes in \e indexSet.
The column headers are also copied and the returned matrix has the same
name as the receiver.
If any index in \e indexSet is exceeds the range of columns in the receiver
an NSRangeException is raised.
*/
- (AdDataMatrix*) submatrixFromColumnSelection: (NSIndexSet*) indexSet
{
int index;
id row;
NSArray* array;
NSMutableArray* rows = [NSMutableArray new];
NSEnumerator* rowEnumerator;
AdDataMatrix* submatrix;
//Check for range problems
index = [indexSet lastIndex];
if(index != NSNotFound)
{
if(index >= (int)numberOfColumns)
[NSException raise: NSRangeException
format: @"Index %d is out of column range (%d)",
index,
numberOfColumns - 1];
rowEnumerator = [self rowEnumerator];
while((row = [rowEnumerator nextObject]))
{
array = [row subarrayFromElementSelection: indexSet];
[rows addObject: array];
}
}
array = [[self columnHeaders]
subarrayFromElementSelection: indexSet];
submatrix = [[AdDataMatrix alloc]
initWithRows: rows
columnHeaders: array
name: [self name]];
[rows release];
return [submatrix autorelease];
}
/**
Returns a new AdDataMatrix instance containing only the rows in \e range
The submatrix has the same headers and name as the receiver.
If \e range exceeds the range of rows in the matrix an NSRangeException
is raised.
*/
- (AdDataMatrix*) submatrixWithRowRange: (NSRange) range
{
return [self submatrixFromRowSelection:
[NSIndexSet indexSetWithIndexesInRange: range]];
}
/**
Returns a new AdDataMatrix instance containing data from the columns in \e range
The column headers are also copied and the returned matrix has the same
name as the receiver.
If \e range exceeds the range of columns in the matrix an NSRangeException
is raised.
*/
- (AdDataMatrix*) submatrixWithColumnRange: (NSRange) range
{
return [self submatrixFromColumnSelection:
[NSIndexSet indexSetWithIndexesInRange: range]];
}
/*
* NSCoding Methods
*/
//decoder for pre 0.7 version objects
- (id) _initWithCoderPre0_7: (NSCoder*) decoder
{
int i,j;
int matrixElements;
int count;
unsigned int length;
double *matrixStore;
NSMutableArray* matrixRow;
NSNumber *element;
NSLog(@"Decoding pre0.7 data matrix");
if([decoder allowsKeyedCoding])
{
matrix = [NSMutableArray new];
numberOfRows = [decoder decodeIntForKey: @"Rows"];
numberOfColumns = [decoder decodeIntForKey: @"Columns"];
matrixStore = (double*)[decoder decodeBytesForKey: @"Matrix"
returnedLength: &length];
matrixElements = length/sizeof(double);
for(i=0, count=0; i<(int)numberOfRows; i++)
{
matrixRow = [NSMutableArray arrayWithCapacity: 1];
for(j=0; j<(int)numberOfColumns; j++)
{
element = [NSNumber numberWithDouble: matrixStore[count]];
[matrixRow addObject: element];
count++;
}
[matrix addObject: matrixRow];
}
columnHeaders = [decoder decodeObjectForKey: @"ColumnHeaders"];
[columnHeaders retain];
name = [decoder decodeObjectForKey: @"Name"];
[name retain];
}
else
{
//We only retain keyed decoding support.
//Non keyed coding/decoding is only used for DO and
//every object sent by DO will be of the new version.
//i.e. it will either be of 0.7+ version or decoded from
//the database using keyed coding and updated to the 0.7 version.
NSWarnLog(@"Non keyed decoding of pre 0.7 version AdDataMatrices not supported");
}
/*** update to new version ****/
NSLog(@"Decoding pre0.7 data matrix");
//check column headers actually exists
if(columnHeaders == nil)
{
columnHeaders = [NSMutableArray new];
for(i=0; i< (int)numberOfColumns; i++)
[columnHeaders addObject:
[NSString stringWithFormat: @"Column %d", i]];
}
//all columns in pre 0.7 versions are doubles when unarchived.
columnDataTypes = [NSMutableArray new];
for(i=0; i< (int)numberOfColumns; i++)
[columnDataTypes addObject: @"double"];
NSLog(@"Decoding pre0.7 data matrix");
return self;
}
//Decoding - We Encode and decode strings as Unicode
- (NSArray*) _decodeNumericColumnOfType: (NSString*) dataType
numberOfElements: (int) numberOfElements
fromData: (NSData*) data
start: (int) start
end: (int*) end
byteSwapFlag: (int) byteSwapFlag
{
int i, step, intNumber;
double doubleNumber;
NSRange range;
void *buffer;
NSMutableArray* column = [NSMutableArray array];
step = intNumber = 0;
doubleNumber = 0.0;
if([dataType isEqual: @"int"])
step = sizeof(int);
else if([dataType isEqual: @"double"])
step = sizeof(double);
else
[NSException raise: NSInvalidArgumentException
format: @"Encountered unknown numeric data type %@ when coding.",
dataType];
*end = start + numberOfElements*step;
buffer = malloc(step);
for(i=start; i< *end; i=i+step)
{
range = NSMakeRange(i, step);
[data getBytes: buffer range: range];
if([dataType isEqual: @"int"])
{
if(byteSwapFlag == AdNoSwap)
intNumber = *(int*)buffer;
else if(byteSwapFlag == AdSwapBytesToBig)
intNumber = NSSwapLittleIntToHost(*(int*)buffer);
else if(byteSwapFlag == AdSwapBytesToLittle)
intNumber = NSSwapBigIntToHost(*(int*)buffer);
[column addObject:
[NSNumber numberWithInt: intNumber]];
}
else if([dataType isEqual: @"double"])
{
if(byteSwapFlag == AdNoSwap)
doubleNumber = *(double*)buffer;
else if(byteSwapFlag == AdSwapBytesToBig)
{
doubleNumber = NSSwapLittleDoubleToHost(*(NSSwappedDouble*)buffer);
}
else if(byteSwapFlag == AdSwapBytesToLittle)
doubleNumber = NSSwapBigDoubleToHost(*(NSSwappedDouble*)buffer);
[column addObject:
[NSNumber numberWithDouble: doubleNumber]];
}
}
free(buffer);
return column;
}
- (NSArray*) _decodeStringColumnWithNumberOfElements: (int) numberOfElements
fromData: (NSData*) data
start: (int) start
end: (int*) end
byteSwapFlag: (int) byteSwapFlag
{
int i, step, length;
NSRange range;
int* lengthBuffer;
id element;
NSData* elementData;
NSMutableArray* column = [NSMutableArray array];
//first extract the string lengths
step = sizeof(int);
*end = start + numberOfElements*step;
lengthBuffer = malloc(numberOfElements*step);
for(i=0; i< numberOfElements; i++)
{
range = NSMakeRange(start + i*step, step);
[data getBytes: (lengthBuffer + i) range: range];
}
//now extract the strings
for(i=0; i< numberOfElements; i++)
{
length = 0;
if(byteSwapFlag == AdNoSwap)
length = lengthBuffer[i];
if(byteSwapFlag == AdSwapBytesToBig)
length = NSSwapLittleIntToHost(lengthBuffer[i]);
else if(byteSwapFlag == AdSwapBytesToLittle)
length = NSSwapBigIntToHost(lengthBuffer[i]);
start = *end;
*end += length;
range = NSMakeRange(start, length);
//We dont have to swap chars since they
//are only one byte long.
elementData = [data subdataWithRange: range];
element = [[NSString alloc]
initWithData: elementData
encoding: NSUTF8StringEncoding];
[element autorelease];
[column addObject: element];
}
free(lengthBuffer);
return column;
}
//recreates the matrix from the archived data
- (void) _extractMatrixFromNumericData: (NSData*) numericData
stringData: (NSData*) stringData
byteSwapFlag: (int) byteSwapFlag
{
int numericStart, numericEnd, i;
int stringStart, stringEnd;
NSEnumerator* columnDataTypesEnum;
NSString *columnDataType;
NSArray* column;
//create the matrix
matrix = [NSMutableArray new];
for(i=0; i<(int)numberOfRows; i++)
[matrix addObject: [NSMutableArray array]];
numericStart = stringStart = 0;
columnDataTypesEnum = [columnDataTypes objectEnumerator];
while((columnDataType = [columnDataTypesEnum nextObject]))
{
if([columnDataType isEqual: @"string"])
{
column = [self _decodeStringColumnWithNumberOfElements: numberOfRows
fromData: stringData
start: stringStart
end: &stringEnd
byteSwapFlag: byteSwapFlag];
stringStart = stringEnd;
}
else
{
column = [self _decodeNumericColumnOfType: columnDataType
numberOfElements: numberOfRows
fromData: numericData
start: numericStart
end: &numericEnd
byteSwapFlag: byteSwapFlag];
numericStart = numericEnd;
}
for(i=0; i<(int)numberOfRows; i++)
[[matrix objectAtIndex: i]
addObject: [column objectAtIndex: i]];
}
}
/*
* Endianness -
* AdDataMatrix handles endianness issues in the following manner.
*
* Endianness is not taken into account during encoding.
* i.e. encoding is done using the endianness of the encoding machine
* However the endianness of the machine is encoded.
*
* On decoding the endianness of the decoding machine and the
* endianness of the archive are compared.
*
* If they are the same byteSwapFlag is set to AdNoSwap.
*
* If the host is big-endian and the archive little-endian
* byteSwapFlag is set to AdSwapBytesToBig
*
* If the host is little-endian and the archive big-endian
* byteSwapFlag is set to AdSwapBytesToLittle
*/
- (id) initWithCoder: (NSCoder*) decoder
{
unsigned int length, encodedByteOrder;
void *bytes;
NSData* numericData, *stringData;
AdByteSwapFlag byteSwapFlag;
if([decoder allowsKeyedCoding])
{
//check archive version
if([decoder decodeObjectForKey: @"ClassVersion"] == nil)
return [self _initWithCoderPre0_7: decoder];
encodedByteOrder = [decoder decodeIntForKey: @"EncodedByteOrder"];
NSDebugLLog(@"AdDataMatrix",
@"Encoded byte order %d. Host byte order %d", encodedByteOrder, NSHostByteOrder());
if(encodedByteOrder != NSHostByteOrder())
{
//This machine is a different endianess to
//the one the object was encoded on.
//We have to swap the bits.
if(encodedByteOrder == NS_LittleEndian)
byteSwapFlag = AdSwapBytesToBig;
else if(encodedByteOrder == NS_BigEndian)
byteSwapFlag = AdSwapBytesToLittle;
else
{
/*
* The encoded byte order is unknown
* Two possible causes :
* 1) This is an old archive and the byte order wasnt encoded
* 2) The byte order of the encoding machine was not known.
* In either case we issue a warning and default to no swapping.
*/
NSWarnLog(@"Encoded byte order unknown - defaulting to no swapping");
byteSwapFlag = AdNoSwap;
}
}
else
byteSwapFlag = AdNoSwap;
NSDebugLLog(@"AdDataMatrix", @"Byte swap flag %d", byteSwapFlag);
numberOfRows = [decoder decodeIntForKey: @"Rows"];
numberOfColumns = [decoder decodeIntForKey: @"Columns"];
columnDataTypes = [decoder decodeObjectForKey: @"ColumnDataTypes"];
[columnDataTypes retain];
columnHeaders = [decoder decodeObjectForKey: @"ColumnHeaders"];
[columnHeaders retain];
name = [decoder decodeObjectForKey: @"Name"];
[name retain];
NSDebugLLog(@"AdDataMatrix", @"Name: %@. Rows %d. Columns %d. Column Names %@",
name, numberOfRows, numberOfColumns, columnHeaders);
bytes = (void*)[decoder decodeBytesForKey: @"NumericColumns"
returnedLength: &length];
numericData = [NSData dataWithBytesNoCopy: bytes
length: length
freeWhenDone: NO];
NSDebugLLog(@"AdDataMatrix", @"Numeric Data - %d bytes", length);
bytes = (void*)[decoder decodeBytesForKey: @"StringColumns"
returnedLength: &length];
stringData = [NSData dataWithBytesNoCopy: bytes
length: length
freeWhenDone: NO];
NSDebugLLog(@"AdDataMatrix", @"String Data - %d bytes", length);
[self _extractMatrixFromNumericData: numericData
stringData: stringData
byteSwapFlag: byteSwapFlag];
}
else
{
numberOfRows = [[decoder decodeObject] intValue];
numberOfColumns = [[decoder decodeObject] intValue];
columnHeaders = [[decoder decodeObject] retain];
name = [[decoder decodeObject] retain];
columnDataTypes = [[decoder decodeObject] retain];
encodedByteOrder = [[decoder decodeObject] intValue];
if(encodedByteOrder != NSHostByteOrder())
{
if(encodedByteOrder == NS_LittleEndian)
byteSwapFlag = AdSwapBytesToBig;
else
byteSwapFlag = AdSwapBytesToLittle;
}
else
byteSwapFlag = AdNoSwap;
bytes = (void*)[decoder decodeBytesWithReturnedLength: &length];
numericData = [NSData dataWithBytesNoCopy: bytes
length: length
freeWhenDone: NO];
bytes = (void*)[decoder decodeBytesWithReturnedLength: &length];
stringData = [NSData dataWithBytesNoCopy: bytes
length: length
freeWhenDone: NO];
[self _extractMatrixFromNumericData: numericData
stringData: stringData
byteSwapFlag: byteSwapFlag];
}
return self;
}
//Encoding
- (void) _addNumericColumn: (NSArray*) column
ofType: (NSString*) dataType
toData: (NSMutableData*) data
{
int intValue;
double doubleValue;
NSEnumerator *columnEnum;
id element;
if([dataType isEqual: @"double"])
{
columnEnum = [column objectEnumerator];
while((element = [columnEnum nextObject]))
{
doubleValue = [element doubleValue];
[data appendBytes: (const void*)&doubleValue
length: sizeof(double)];
}
}
else if([dataType isEqual: @"int"])
{
columnEnum = [column objectEnumerator];
while((element = [columnEnum nextObject]))
{
intValue = [element intValue];
[data appendBytes: (const void*)&intValue
length: sizeof(int)];
}
}
else
[NSException raise: NSInvalidArgumentException
format: @"Encountered unknown numeric data type %@ when coding.",
dataType];
}
- (NSData*) _encodeNumericColumnsAsData
{
int i;
NSMutableData* data;
NSArray* column;
data = [NSMutableData dataWithLength:0];
//Only encode if theres something to encode
if([columnDataTypes count] != 0)
for(i=0; i<(int)numberOfColumns; i++)
{
column = [self column: i];
if(![[columnDataTypes objectAtIndex: i] isEqual: @"string"])
[self _addNumericColumn: column
ofType: [columnDataTypes objectAtIndex: i]
toData: data];
}
return data;
}
- (NSData*) _encodeStringColumnsAsData
{
int i, j;
id element;
NSMutableData* data;
int* lengthBuffer;
NSArray* column;
lengthBuffer = malloc(numberOfRows*sizeof(int));
data = [NSMutableData dataWithLength:0];
//Only encode if theres something to encode
if([columnDataTypes count] != 0)
{
for(i=0; i<(int)numberOfColumns; i++)
{
column = [self column: i];
if([[columnDataTypes objectAtIndex: i] isEqual: @"string"])
{
//Go through once and add an array with the lengths of all
//the strings
for(j=0; j<(int)[column count]; j++)
{
element = [column objectAtIndex: j];
lengthBuffer[j] = [element lengthOfBytesUsingEncoding:
NSUTF8StringEncoding];
//lengthBuffer[j] += 1;
}
[data appendBytes: lengthBuffer
length: numberOfRows*sizeof(int)];
//Now add the strings
for(j=0; j<(int)[column count]; j++)
{
element = [column objectAtIndex: j];
[data appendData:
[element dataUsingEncoding: NSUTF8StringEncoding]];
}
}
}
}
free(lengthBuffer);
return data;
}
- (void) encodeWithCoder: (NSCoder*) encoder
{
NSData* data;
if([encoder allowsKeyedCoding])
{
[encoder encodeInt: numberOfRows forKey: @"Rows"];
[encoder encodeInt: numberOfColumns forKey: @"Columns"];
[encoder encodeObject: columnHeaders forKey: @"ColumnHeaders"];
[encoder encodeObject: name forKey: @"Name"];
[encoder encodeObject: columnDataTypes forKey: @"ColumnDataTypes"];
[encoder encodeInt: NSHostByteOrder() forKey: @"EncodedByteOrder"];
NSDebugLLog(@"AdDataMatrix", @"Encoding: %@. Rows %d. Columns %d. Column Names %@",
name, numberOfRows, numberOfColumns, columnHeaders);
data = [self _encodeNumericColumnsAsData];
NSDebugLLog(@"AdDataMatrix",
@"Encoding %d bytes of numeric data", [data length]);
[encoder encodeBytes: [data bytes]
length: [data length]
forKey: @"NumericColumns"];
data = [self _encodeStringColumnsAsData];
NSDebugLLog(@"AdDataMatrix",
@"Encoding %d bytes of string data", [data length]);
[encoder encodeBytes: [data bytes]
length: [data length]
forKey: @"StringColumns"];
//Encode the lengths of all string columns
[encoder encodeObject: [NSNumber numberWithDouble: 0.7]
forKey: @"ClassVersion"];
}
else
{
[encoder encodeObject: [NSNumber numberWithInt: numberOfRows]];
[encoder encodeObject: [NSNumber numberWithInt: numberOfColumns]];
[encoder encodeObject: columnHeaders];
[encoder encodeObject: name];
[encoder encodeObject: columnDataTypes];
[encoder encodeObject: [NSNumber numberWithInt: NSHostByteOrder()]];
data = [self _encodeNumericColumnsAsData];
[encoder encodeBytes: (uint8_t*)[data bytes]
length: [data length]];
data = [self _encodeStringColumnsAsData];
[encoder encodeBytes: (uint8_t*)[data bytes]
length: [data length]];
}
}
#ifndef GNUSTEP
//See the AdModelObject implementation of this method
//for a description of why it is necessary.
//Note: Here we always return a copy of the object since
//if we dont certain methods will cause the program to crash
//e.g. cRepresentation.
- (id) replacementObjectForPortCoder: (NSPortCoder*) encoder
{
return self;
}
#endif
/*
* NSCopying & NSMutableCopying
*/
- (id) copyWithZone: (NSZone*) zone
{
//If we are not AdDataMatrix alloc explicitly
//since we must could be a mutable subclass
if(![self isMemberOfClass: [AdDataMatrix class]])
return [[AdDataMatrix allocWithZone: zone]
initWithDataMatrix: self
columnHeaders: [self columnHeaders]
name: [self name]];
if(zone == NULL || zone == NSDefaultMallocZone())
return [self retain];
else
return [[AdDataMatrix allocWithZone: zone]
initWithDataMatrix: self
columnHeaders: [self columnHeaders]
name: [self name]];
}
- (id) mutableCopyWithZone: (NSZone*) zone
{
return [[AdMutableDataMatrix allocWithZone: zone]
initWithDataMatrix: self
columnHeaders: [self columnHeaders]
name: [self name]];
}
@end
/*
Mutable subclass of AdDataMatrix
*/
@implementation AdMutableDataMatrix
+ (id) matrixFromStringRepresentation: (NSString*) aString
{
return [[[AdMutableDataMatrix alloc]
initWithStringRepresentation: aString]
autorelease];
}
+ (id) matrixFromGSLVector: (gsl_vector*) aVector
{
return [[[AdMutableDataMatrix alloc]
initWithGSLVector: aVector
columnHeaders: nil
name: nil] autorelease];
}
+ (id) matrixFromGSLMatrix: (gsl_matrix*) aMatrix
{
return [[[AdMutableDataMatrix alloc]
initWithGSLMatrix: aMatrix
columnHeaders: nil
name: nil] autorelease];
}
+ (id) matrixFromADMatrix: (AdMatrix*) aMatrix
{
return [[[AdMutableDataMatrix alloc]
initWithADMatrix: aMatrix
columnHeaders: nil
name: nil] autorelease];
}
/*
* Init and dealloc
*/
- (id) initWithNumberOfColumns: (unsigned int) number
columnHeaders: (NSArray*) headers
columnDataTypes: (NSArray*) dataTypes
{
int i;
id dataType;
NSEnumerator *dataTypesEnum;
//Calling [super init] creates
//an empty matrix.
if((self = [super init]))
{
numberOfColumns = number;
//check headers
if(headers == nil)
{
for(i=0; i<(int)numberOfColumns; i++)
[columnHeaders addObject:
[NSString stringWithFormat: @"Column %d", i]];
}
else if([headers count] != numberOfColumns)
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"Number of headers %d does not match number of columns %d",
[headers count], numberOfColumns];
}
else
[columnHeaders addObjectsFromArray: headers];
if(dataTypes != nil)
{
if([dataTypes count] != numberOfColumns)
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"Number of data types %d does not match number of columns %d",
[dataTypes count], numberOfColumns];
}
else
{
dataTypesEnum = [dataTypes objectEnumerator];
while((dataType = [dataTypesEnum nextObject]))
if(![allowedDataTypes containsObject: dataType])
{
[self release];
[NSException raise: NSInvalidArgumentException
format: @"%@ is an invalid column data type",
dataType];
}
[columnDataTypes addObjectsFromArray: dataTypes];
}
}
}
return self;
}
- (id) initWithColumnsForDataTypes: (NSArray*) dataTypes
withHeaders: (NSArray*) headers
{
int columns;
if(dataTypes == nil)
columns = 0;
else
columns = (int)[dataTypes count];
return [self initWithNumberOfColumns: columns
columnHeaders: headers
columnDataTypes: dataTypes];
}
- (id) init
{
return [self initWithNumberOfColumns: 0
columnHeaders: nil
columnDataTypes: nil];
}
- (void) dealloc
{
[super dealloc];
}
/*
* Setting Elements
*/
- (void) setElementAtRow: (unsigned int) rowIndex
column: (unsigned int) columnIndex
withValue: (id) value;
{
//check element exists
if(columnIndex >= numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Column %d does not exist", columnIndex];
if(rowIndex >= numberOfRows)
[NSException raise: NSInvalidArgumentException
format: @"Row %d does not exist", rowIndex];
value = [self representationOfObject: value
forColumn: columnIndex];
[[matrix objectAtIndex: rowIndex] replaceObjectAtIndex: columnIndex
withObject: value];
}
- (void) setElementAtRow: (unsigned int) row
ofColumnWithHeader: (NSString*) columnHeader
withValue: (id) value;
{
int columnIndex;
if((columnIndex = [columnHeaders indexOfObject: columnHeader]) == NSNotFound)
[NSException raise: NSInvalidArgumentException
format: @"Column header %@ does not exist", columnHeader];
[self setElementAtRow: row
column: columnIndex
withValue: value];
}
- (void) extendMatrixWithRow: (NSArray*) anArray
{
int i;
NSMutableArray* row;
id element;
//If numberOfColumns is 0 we initialise the matrix to
//have the same number of columns as the first row added.
if(numberOfColumns == 0)
{
numberOfColumns = [anArray count];
//create the headers
for(i=0; i<(int)numberOfColumns; i++)
[columnHeaders addObject:
[NSString stringWithFormat: @"Column %d", i]];
}
if([anArray count] == numberOfColumns)
{
//If this is the first row we must set the data types
//(unless the data types were set on initialisation for a AdMutableDataMatrix)
//Otherwise we convert anArrays elements to the correct classes.
if((numberOfRows == 0) && ([columnDataTypes count] == 0))
{
[self setDataTypesToTypesInArray: anArray];
row = [[NSMutableArray alloc] initWithArray: anArray];
}
else
{
row = [NSMutableArray new];
for(i=0; i<(int)[anArray count]; i++)
{
element = [self representationOfObject:
[anArray objectAtIndex: i]
forColumn: i];
[row addObject: element];
}
}
[matrix addObject: row];
[row release];
numberOfRows++;
}
else
{
[NSException raise: NSInvalidArgumentException
format: @"Incorrect number of elements in array (%d, %d)",
[anArray count], numberOfColumns];
}
}
- (void) extendMatrixWithColumn: (NSArray*) anArray
{
int i;
NSString* initialObjectClass, *dataType;
NSMutableArray* convertedArray;
id element;
Class class;
//if there are any previous columns check that this one is
//the right length
if(numberOfColumns != 0 && numberOfRows != 0)
if([anArray count] != numberOfRows)
[NSException raise: NSInvalidArgumentException
format: @"Incorrect number of elements in array (%d, %d)",
[anArray count], numberOfRows];
initialObjectClass = NSStringFromClass([[anArray objectAtIndex: 0] class]);
if((class = [self allowedSuperClassForObject: [anArray objectAtIndex: 0]]) != nil)
{
dataType = [classToDataTypeMap objectForKey:
NSStringFromClass(class)];
}
else
{
dataType = [classToDataTypeMap objectForKey: initialObjectClass];
if(dataType == nil)
[NSException raise: NSInvalidArgumentException
format: @"AdDataMatrix - Cannot insert objects of class %@",
initialObjectClass];
}
[columnDataTypes addObject: dataType];
//Convert the rest of the array to the correct type.
//We could add each element using extendMatrixWithRow:
//however we want to check if all the objects in anArray are
//convertible first.
convertedArray = [NSMutableArray array];
[convertedArray addObject: [anArray objectAtIndex: 0]];
for(i=1; i<(int)[anArray count]; i++)
{
element = [self representationOfObject: [anArray objectAtIndex: i]
forColumn: numberOfColumns];
[convertedArray addObject: element];
}
//If there are no rows we have to create
//one for each element we are going to add.
if(numberOfRows == 0)
for(i=0; i<(int)[convertedArray count]; i++)
{
[matrix addObject: [NSMutableArray array]];
numberOfRows++;
}
for(i=0; i<(int)numberOfRows; i++)
[[matrix objectAtIndex: i] addObject:
[convertedArray objectAtIndex: i]];
//Add new column header
[columnHeaders addObject:
[NSString stringWithFormat: @"Column %d", numberOfColumns]];
numberOfColumns++;
}
- (void) extendMatrixWithMatrix: (AdDataMatrix*) extendingMatrix
{
NSEnumerator* rowEnum;
id row;
rowEnum = [extendingMatrix rowEnumerator];
while((row = [rowEnum nextObject]))
[self extendMatrixWithRow: row];
}
/*
* Removing Elements
*/
- (void) removeRowsWithIndexes: (NSIndexSet*) indexSet
{
unsigned int* buffer;
if([indexSet lastIndex] == NSNotFound)
return;
if([indexSet lastIndex] >= numberOfRows)
[NSException raise: NSRangeException
format: @"Index %d is out of row range %d",
[indexSet lastIndex],
numberOfRows];
//maybe one day this will be implemented - only in Cocoa for now
//[matrix removeObjectsWithIndexes: indexSet];
buffer = (unsigned int*)malloc([indexSet count]*sizeof(unsigned int));
[indexSet getIndexes: buffer
maxCount: [indexSet count]
inIndexRange: NULL];
[matrix removeObjectsFromIndices: buffer numIndices: [indexSet count]];
free(buffer);
numberOfRows = [matrix count];
}
- (void) removeRowsInRange: (NSRange) aRange
{
if(NSMaxRange(aRange) > numberOfRows)
[NSException raise: NSRangeException
format: @"Range exceeds the number of rows in the receiver (%d, %d)",
NSMaxRange(aRange), numberOfRows];
[matrix removeObjectsInRange: aRange];
numberOfRows = [matrix count];
}
- (void) removeRow: (unsigned int) rowIndex
{
if(rowIndex >= numberOfRows)
[NSException raise: NSRangeException
format: @"Index %d is out of row range %d",
rowIndex,
numberOfRows];
[matrix removeObjectAtIndex: rowIndex];
numberOfRows = [matrix count];
}
- (void) setColumnHeaders: (NSArray*) anArray
{
id holder;
if([anArray count] != numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Incorrect number of elements in array (%d, %d)",
[anArray count], numberOfRows];
if(anArray != columnHeaders)
{
holder = columnHeaders;
columnHeaders = [anArray mutableCopy];
[holder release];
}
}
- (void) setHeaderOfColumn: (unsigned int) columnIndex to: (NSString*) string
{
if(columnIndex >= numberOfColumns)
[NSException raise: NSInvalidArgumentException
format: @"Column doesnt exist"];
[columnHeaders replaceObjectAtIndex: columnIndex
withObject: string];
}
- (void) setName: (NSString*) aString
{
name = [aString retain];
}
@end
//For older classes
@implementation ULMatrix
@end
|