data.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. /* The C clustering library.
  2. * Copyright (C) 2002 Michiel Jan Laurens de Hoon.
  3. *
  4. * This library was written at the Laboratory of DNA Information Analysis,
  5. * Human Genome Center, Institute of Medical Science, University of Tokyo,
  6. * 4-6-1 Shirokanedai, Minato-ku, Tokyo 108-8639, Japan.
  7. * Contact: mdehoon 'AT' gsc.riken.jp
  8. *
  9. * Permission to use, copy, modify, and distribute this software and its
  10. * documentation with or without modifications and for any purpose and
  11. * without fee is hereby granted, provided that any copyright notices
  12. * appear in all copies and that both those copyright notices and this
  13. * permission notice appear in supporting documentation, and that the
  14. * names of the contributors or copyright holders not be used in
  15. * advertising or publicity pertaining to distribution of the software
  16. * without specific prior permission.
  17. *
  18. * THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL
  19. * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE
  21. * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
  22. * OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  23. * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  24. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
  25. * OR PERFORMANCE OF THIS SOFTWARE.
  26. *
  27. */
  28. /* This file contains C code needed for Cluster 3.0, particularly file reading
  29. * and data handling. It is platform-independent; platform-dependent code is
  30. * located in windows/gui.c (Microsoft Windows), in mac/Controller.m (Mac OS X),
  31. * and in x11/gui.c (X11 using Motif).
  32. *
  33. * Michiel de Hoon, (mdehoon 'AT' gsc.riken.jp).
  34. * University of Tokyo, Human Genome Center.
  35. * 2003.01.10.
  36. */
  37. /*============================================================================*/
  38. /* Header files */
  39. /*============================================================================*/
  40. /* Standard C header files */
  41. #include <stdio.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #include <math.h>
  45. /* Local header files */
  46. #include "data.h"
  47. #include "cluster.h" /* The C clustering library */
  48. /*============================================================================*/
  49. /* Data declaration */
  50. /*============================================================================*/
  51. static int _rows = 0;
  52. static int _columns = 0;
  53. static double* _geneweight = NULL;
  54. static double* _arrayweight = NULL;
  55. static double* _geneorder = NULL; /* Saves gene order in the data file */
  56. static double* _arrayorder = NULL; /* Saves array order in the data file */
  57. static int* _geneindex = NULL; /* Set by clustering methods for file output */
  58. static int* _arrayindex = NULL; /* Set by clustering methods for file output */
  59. static char* _uniqID = NULL; /* Stores UNIQID identifier in the data file */
  60. static char** _geneuniqID = NULL;
  61. static char** _genename = NULL;
  62. static char** _arrayname = NULL;
  63. static double** _data = NULL;
  64. static int** _mask = NULL;
  65. /*============================================================================*/
  66. /* Utility routines */
  67. /*============================================================================*/
  68. static char* GetLine(FILE* inputfile)
  69. /* The function GetLine reads one line from the inputfile, and returns it as a
  70. * null-terminated string. If inputfile is at EOF, a null pointer is returned.
  71. * The calling routine should free the char* returned by GetLine.
  72. */
  73. { int c;
  74. int n = 0;
  75. int size = 1023;
  76. char* line = malloc((size+1)*sizeof(char));
  77. while ((c = getc(inputfile))!=EOF && c!='\r' && c!='\n')
  78. { if (n == size)
  79. { size *= 2;
  80. line = realloc(line,(size+1)*sizeof(char));
  81. }
  82. line[n] = (char)c;
  83. n++;
  84. }
  85. if (c=='\r')
  86. { c = getc(inputfile);
  87. if (c!='\n' && c!=EOF) ungetc(c,inputfile);
  88. }
  89. if (n==0 && c==EOF)
  90. { free(line);
  91. return 0;
  92. }
  93. line[n] = '\0';
  94. line = realloc(line,(n+1)*sizeof(char));
  95. return line;
  96. }
  97. static char* tokenize(char* s)
  98. {
  99. char* p = s;
  100. while (1)
  101. {
  102. if (*p=='\0') return NULL;
  103. if (*p=='\t')
  104. {
  105. *p = '\0';
  106. return p+1;
  107. }
  108. p++;
  109. }
  110. /* Never get here */
  111. return NULL;
  112. }
  113. static char* MakeID (const char* name, int i)
  114. { int n;
  115. char* ID;
  116. int ndigits = 1;
  117. int remainder = i;
  118. while (remainder/=10) ndigits++; /* Count how many digits there are in i */
  119. n = strlen(name) + ndigits + 2;
  120. /* One more for the X, and one more for the \0 termination character */
  121. ID = malloc(n*sizeof(char));
  122. sprintf (ID, "%s%dX",name,i);
  123. return ID;
  124. }
  125. static void SetClusterIndex (char which, int k, int* clusterid)
  126. { int i;
  127. int cluster;
  128. int counter = 0;
  129. int* index = NULL;
  130. if (which=='g')
  131. { index = malloc(_rows*sizeof(int));
  132. for (i=0; i<_rows; i++) index[i] = i;
  133. sort (_rows, _geneorder, index);
  134. for (cluster = 0; cluster < k; cluster++)
  135. { for (i = 0; i < _rows; i++)
  136. { const int j = index[i];
  137. if (clusterid[j]==cluster)
  138. { _geneindex[counter] = j;
  139. counter++;
  140. }
  141. }
  142. }
  143. }
  144. if (which=='a')
  145. { index = malloc(_columns*sizeof(int));
  146. for (i=0; i<_columns; i++) index[i] = i;
  147. sort (_columns, _arrayorder, index);
  148. for (cluster = 0; cluster < k; cluster++)
  149. { for (i = 0; i < _columns; i++)
  150. { const int j = index[i];
  151. if (clusterid[j]==cluster)
  152. { _arrayindex[counter] = j;
  153. counter++;
  154. }
  155. }
  156. }
  157. }
  158. free(index);
  159. return;
  160. }
  161. static void
  162. TreeSort(const char which, const int nNodes, const double* order,
  163. const double* nodeorder, const int* nodecounts, Node* tree)
  164. { const int nElements = nNodes + 1;
  165. int i;
  166. double* neworder = calloc(nElements,sizeof(double)); /* initialized to 0.0 */
  167. int* clusterids = malloc(nElements*sizeof(int));
  168. for (i = 0; i < nElements; i++) clusterids[i] = i;
  169. for (i = 0; i < nNodes; i++)
  170. { const int i1 = tree[i].left;
  171. const int i2 = tree[i].right;
  172. const double order1 = (i1<0) ? nodeorder[-i1-1] : order[i1];
  173. const double order2 = (i2<0) ? nodeorder[-i2-1] : order[i2];
  174. const int count1 = (i1<0) ? nodecounts[-i1-1] : 1;
  175. const int count2 = (i2<0) ? nodecounts[-i2-1] : 1;
  176. /* If order1 and order2 are equal, their order is determined by
  177. * the order in which they were clustered */
  178. if (i1<i2)
  179. { const double increase = (order1<order2) ? count1 : count2;
  180. int j;
  181. for (j = 0; j < nElements; j++)
  182. { const int clusterid = clusterids[j];
  183. if (clusterid==i1 && order1>=order2) neworder[j] += increase;
  184. if (clusterid==i2 && order1<order2) neworder[j] += increase;
  185. if (clusterid==i1 || clusterid==i2) clusterids[j] = -i-1;
  186. }
  187. }
  188. else
  189. { const double increase = (order1<=order2) ? count1 : count2;
  190. int j;
  191. for (j = 0; j < nElements; j++)
  192. { const int clusterid = clusterids[j];
  193. if (clusterid==i1 && order1>order2) neworder[j] += increase;
  194. if (clusterid==i2 && order1<=order2) neworder[j] += increase;
  195. if (clusterid==i1 || clusterid==i2) clusterids[j] = -i-1;
  196. }
  197. }
  198. }
  199. free(clusterids);
  200. if (which=='g')
  201. { for (i=0; i<_rows; i++) _geneindex[i] = i;
  202. sort(_rows, neworder, _geneindex);
  203. }
  204. if (which=='a')
  205. { for (i=0; i<_columns; i++) _arrayindex[i] = i;
  206. sort(_columns, neworder, _arrayindex);
  207. }
  208. free(neworder);
  209. return;
  210. }
  211. static void
  212. PerformGeneSOM(FILE* file, int XDim, int YDim, int iterations, double tau,
  213. char metric)
  214. { int i,j,k;
  215. int* clusterid;
  216. int* index;
  217. int (*Group)[2] = malloc(_rows*sizeof(int[2]));
  218. double*** Nodes = malloc(XDim*YDim*_columns*sizeof(double**));
  219. for (i = 0; i < XDim; i++)
  220. { Nodes[i] = malloc(YDim*_columns*sizeof(double*));
  221. for (j = 0; j < YDim; j++) Nodes[i][j] = malloc(_columns*sizeof(double));
  222. }
  223. somcluster(_rows, _columns, _data, _mask, _arrayweight, 0,
  224. XDim, YDim, tau, iterations, metric, Nodes, Group);
  225. clusterid = malloc(_rows*sizeof(int));
  226. for (i=0; i<_rows; i++) clusterid[i] = Group[i][0] * YDim + Group[i][1];
  227. free(Group);
  228. index = malloc(_columns*sizeof(int));
  229. for (k=0; k<_columns; k++) index[k] = k;
  230. sort (_columns, _arrayorder, index);
  231. fputs ("NODE", file);
  232. for (i=0; i<_columns; i++) fprintf (file, "\t%s", _arrayname[index[i]]);
  233. putc ('\n', file);
  234. for (i=0; i<XDim; i++)
  235. { for (j=0; j<YDim; j++)
  236. { fprintf (file, "NODE(%d,%d)", i, j);
  237. for (k=0; k<_columns; k++) fprintf (file, "\t%f", Nodes[i][j][index[k]]);
  238. putc ('\n', file);
  239. }
  240. }
  241. free(index);
  242. for (i=0;i<XDim;i++)
  243. { for (j=0; j<YDim; j++) free(Nodes[i][j]);
  244. free(Nodes[i]);
  245. }
  246. free(Nodes);
  247. SetClusterIndex ('g', XDim * YDim, clusterid);
  248. free(clusterid);
  249. }
  250. static void
  251. PerformArraySOM(FILE* file, int XDim, int YDim, int iterations, double tau,
  252. char metric)
  253. { int i,j,k;
  254. int* clusterid;
  255. int (*Group)[2] = malloc(_columns*sizeof(int[2]));
  256. double*** Nodes = malloc(XDim*YDim*_rows*sizeof(double**));
  257. for (i = 0; i < XDim; i++)
  258. { Nodes[i] = malloc(YDim*_rows*sizeof(double*));
  259. for (j = 0; j < YDim; j++) Nodes[i][j] = malloc(_rows*sizeof(double));
  260. }
  261. somcluster(_rows, _columns, _data, _mask, _geneweight, 1,
  262. XDim, YDim, tau, iterations, metric, Nodes, Group);
  263. clusterid = malloc(_columns*sizeof(int));
  264. for (i=0; i<_columns; i++)
  265. clusterid[i] = Group[i][0] * YDim + Group[i][1];
  266. free(Group);
  267. fprintf (file, "%s\t", _uniqID);
  268. for (i=0; i<XDim; i++)
  269. for (j=0; j<YDim; j++) fprintf(file, "\tNODE(%d,%d)", i, j);
  270. putc ('\n', file);
  271. for (k=0;k<_rows;k++)
  272. { int index = _geneindex[k];
  273. fprintf (file, "%s\t", _geneuniqID[index]);
  274. if (_genename[index]) fputs (_genename[index], file);
  275. else fputs (_geneuniqID[index], file);
  276. for (i=0; i<XDim; i++)
  277. for (j=0; j<YDim; j++) fprintf (file, "\t%f", Nodes[i][j][index]);
  278. putc ('\n', file);
  279. }
  280. for (i=0;i<XDim;i++)
  281. { for (j=0; j<YDim; j++) free(Nodes[i][j]);
  282. free(Nodes[i]);
  283. }
  284. free(Nodes);
  285. SetClusterIndex ('a', XDim * YDim, clusterid);
  286. free(clusterid);
  287. }
  288. /*============================================================================*/
  289. /* Data handling routines */
  290. /*============================================================================*/
  291. void Free(void)
  292. { int row, column;
  293. for (row = 0; row < _rows; row++)
  294. { free (_data[row]);
  295. free (_mask[row]);
  296. free (_geneuniqID[row]);
  297. free (_genename[row]);
  298. }
  299. free (_data);
  300. free (_mask);
  301. free (_geneuniqID);
  302. free (_genename);
  303. for (column = 0; column < _columns; column++)
  304. free (_arrayname[column]);
  305. free (_arrayname);
  306. free (_geneorder);
  307. free (_arrayorder);
  308. free (_geneindex);
  309. free (_arrayindex);
  310. free (_geneweight);
  311. free (_arrayweight);
  312. free (_uniqID);
  313. _genename = NULL;
  314. _geneuniqID = NULL;
  315. _geneweight = NULL;
  316. _geneorder = NULL;
  317. _geneindex = NULL;
  318. _arrayname = NULL;
  319. _arrayweight = NULL;
  320. _arrayorder = NULL;
  321. _arrayindex = NULL;
  322. _data = NULL;
  323. _mask = NULL;
  324. _uniqID = NULL;
  325. _rows = 0;
  326. _columns = 0;
  327. }
  328. int GetRows(void)
  329. { return _rows;
  330. }
  331. int GetColumns(void)
  332. { return _columns;
  333. }
  334. char* Load (FILE* file)
  335. /* Load in data from tab-delimited text file.
  336. * If an error occurs, an error message is returned.
  337. * All error messages are allocated with malloc, even if not strictly
  338. * necessary. The reason is that any error message then can (and should) be
  339. * safely freed. */
  340. { int row, column; /* Counters for data matrix */
  341. int fileRow, fileColumn; /* Counters for rows and columns in the file */
  342. int n;
  343. int nFileColumns;
  344. char* line;
  345. char* s;
  346. int geneNameColumn = -1;
  347. int geneWeightColumn = -1;
  348. int geneOrderColumn = -1;
  349. int arrayWeightRow = -1;
  350. int arrayOrderRow = -1;
  351. /* Deallocate previously allocated space */
  352. Free();
  353. /* Parse header line (first line) to find out what the columns are */
  354. line=GetLine(file);
  355. if(!line)
  356. { const char text[] = "Error: Attempt to read empty file";
  357. const int m = strlen(text) + 1;
  358. char* error = malloc(m*sizeof(char));
  359. strcpy(error,text);
  360. return error;
  361. }
  362. while(line[0]=='\0') /* Ignore completely empty lines */
  363. { free(line);
  364. line = GetLine(file);
  365. if(!line)
  366. { const char text[] = "Error: Failed to find first line in file";
  367. const int m = strlen(text) + 1;
  368. char* error = malloc(m*sizeof(char));
  369. strcpy(error,text);
  370. return error;
  371. }
  372. }
  373. s = tokenize(line); /* Skip the first column UNIQID */
  374. fileColumn = 1;
  375. _columns = 0;
  376. while (s)
  377. { char* token = s;
  378. s = tokenize(s);
  379. if (!strcmp(token,"NAME")) geneNameColumn = fileColumn;
  380. else if (!strcmp(token,"GWEIGHT")) geneWeightColumn = fileColumn;
  381. else if (!strcmp(token,"GORDER")) geneOrderColumn = fileColumn;
  382. else _columns++;
  383. fileColumn++;
  384. }
  385. free(line);
  386. nFileColumns = fileColumn;
  387. if (nFileColumns < 2)
  388. { const char text[] = "Error: less than two columns found in the file";
  389. const int m = strlen(text) + 1;
  390. char* error = malloc(m*sizeof(char));
  391. strcpy(error,text);
  392. _columns = 0;
  393. return error;
  394. }
  395. /* Check if the other rows in the file have the same number of columns */
  396. fileRow = 1;
  397. while ((line = GetLine(file)))
  398. { if (line[0]=='\0') free(line); /* Ignore completely empty lines */
  399. else
  400. /* Parse the first column to find out what the rows contain */
  401. { fileColumn = 1; /* One more columns than tabs */
  402. for (s=line; (*s)!='\0'; s++) if(*s=='\t') fileColumn++;
  403. s = tokenize(line);
  404. if(!strcmp(line,"EWEIGHT")) arrayWeightRow=fileRow;
  405. else if (!strcmp(line,"EORDER")) arrayOrderRow=fileRow;
  406. else if (line[0]=='\0') s = NULL; /* no gene name found */
  407. else _rows++;
  408. free(line);
  409. fileRow++;
  410. if (s==NULL)
  411. { int n = 1024;
  412. char* text = malloc(n*sizeof(char));
  413. sprintf (text, "Error reading line %d: Gene name is missing", fileRow);
  414. n = strlen(text) + 1;
  415. text = realloc(text,n*sizeof(char));
  416. _rows = 0;
  417. _columns = 0;
  418. return text;
  419. }
  420. if (fileColumn < nFileColumns)
  421. { int n = 1024;
  422. char* text = malloc(n*sizeof(char));
  423. sprintf (text,
  424. "Error reading line %d: only %d columns available (%d needed)",
  425. fileRow, fileColumn, nFileColumns);
  426. n = strlen(text) + 1;
  427. text = realloc(text,n*sizeof(char));
  428. _rows = 0;
  429. _columns = 0;
  430. return text;
  431. }
  432. if (fileColumn > nFileColumns)
  433. { int n = 1024;
  434. char* text = malloc(n*sizeof(char));
  435. sprintf (text,
  436. "Error reading line %d: %d columns given (%d needed)",
  437. fileRow, fileColumn, nFileColumns);
  438. n = strlen(text) + 1;
  439. text = realloc(text,n*sizeof(char));
  440. _rows = 0;
  441. _columns = 0;
  442. return text;
  443. }
  444. }
  445. }
  446. /* Read the first line into a string */
  447. fseek (file, 0, SEEK_SET);
  448. line = GetLine(file);
  449. /* Save which word the user used instead of UniqID */
  450. if(!line)
  451. { char text[] = "Error finding UniqID keyword";
  452. const int m = strlen(text) + 1;
  453. char* error = malloc(m*sizeof(char));
  454. strcpy(error,text);
  455. _rows = 0;
  456. _columns = 0;
  457. return error;
  458. }
  459. s = tokenize(line);
  460. n = strlen(line);
  461. _uniqID = malloc((n+1)*sizeof(char));
  462. strcpy(_uniqID, line);
  463. /* Allocate space for array names (experiment names) and save them */
  464. _arrayname = malloc(_columns*sizeof(char*));
  465. column = 0;
  466. fileColumn = 1;
  467. while (column < _columns)
  468. { char* token = s;
  469. s = tokenize(s);
  470. n = strlen(token);
  471. if (fileColumn!=0 &&
  472. fileColumn!=geneNameColumn &&
  473. fileColumn!=geneWeightColumn &&
  474. fileColumn!=geneOrderColumn)
  475. { _arrayname[column] = malloc((n+1)*sizeof(char));
  476. strcpy(_arrayname[column],token);
  477. column++;
  478. }
  479. fileColumn++;
  480. }
  481. free(line);
  482. /* Allocate space for array weights */
  483. _arrayweight = malloc(_columns*sizeof(double));
  484. _arrayorder = malloc(_columns*sizeof(double));
  485. _arrayindex = malloc(_columns*sizeof(int));
  486. for (column = 0; column < _columns; column++)
  487. { _arrayweight[column] = 1.;
  488. _arrayorder[column] = column;
  489. }
  490. /* Allocate space for data */
  491. _data = malloc(_rows*sizeof(double*));
  492. _mask = malloc(_rows*sizeof(int*));
  493. for (row = 0; row < _rows; row++)
  494. { _data[row] = malloc(_columns*sizeof(double));
  495. _mask[row] = malloc(_columns*sizeof(int));
  496. }
  497. /* Allocate space for gene quantities */
  498. _geneweight = malloc(_rows*sizeof(double));
  499. _geneorder = malloc(_rows*sizeof(double));
  500. _geneindex = malloc(_rows*sizeof(int));
  501. _geneuniqID = malloc(_rows*sizeof(char*));
  502. _genename = malloc(_rows*sizeof(char*));
  503. /* Unless a NAME column exists, fill the gene names with NULL */
  504. if (geneNameColumn == -1)
  505. for (row = 0; row < _rows; row++) _genename[row] = NULL;
  506. /* Unless a GWEIGHT column exists,
  507. * fill the gene weights with the default value */
  508. if (geneWeightColumn == -1)
  509. for (row = 0; row < _rows; row++) _geneweight[row] = 1.;
  510. /* Unless a GORDER column exist, set the gene order to the default value */
  511. if (geneOrderColumn == -1)
  512. for (row = 0; row < _rows; row++) _geneorder[row] = row;
  513. /* Read in gene data */
  514. row = 0;
  515. fseek (file, 0, SEEK_SET);
  516. free(GetLine(file)); /* Skip header line */
  517. fileRow = 1;
  518. while ((line=GetLine(file)))
  519. { if (strlen(line) > 1) /* Ignore completely empty lines */
  520. { if (fileRow==arrayWeightRow)
  521. { column = 0;
  522. fileColumn = 1;
  523. /* Skipping UNIQID column */
  524. s = tokenize(line);
  525. while (column < _columns)
  526. { char* error = NULL;
  527. char* token = s;
  528. s = tokenize(s);
  529. if (fileColumn!=geneNameColumn &&
  530. fileColumn!=geneWeightColumn &&
  531. fileColumn!=geneOrderColumn)
  532. {
  533. _arrayweight[column] = 0; /* Default value */
  534. if(token[0]!='\0')
  535. { const double number = strtod(token, &error);
  536. if (!(*error)) _arrayweight[column] = number;
  537. }
  538. column++;
  539. }
  540. fileColumn++;
  541. }
  542. }
  543. else if (fileRow==arrayOrderRow)
  544. { column = 0;
  545. fileColumn = 1;
  546. /* Skipping UNIQID column */
  547. s = tokenize(line);
  548. while (column < _columns)
  549. { char* error = NULL;
  550. char* token = s;
  551. s = tokenize(s);
  552. if (fileColumn!=geneNameColumn &&
  553. fileColumn!=geneWeightColumn &&
  554. fileColumn!=geneOrderColumn)
  555. {
  556. _arrayorder[column] = 0; /* Default value */
  557. if(token[0]!='\0')
  558. { const double number = strtod(token, &error);
  559. if (!(*error)) _arrayorder[column] = number;
  560. }
  561. column++;
  562. }
  563. fileColumn++;
  564. }
  565. }
  566. else
  567. { column = 0;
  568. fileColumn = 0;
  569. s = line;
  570. while (s)
  571. { char* token = s;
  572. s = tokenize(s);
  573. if (fileColumn==0)
  574. { const int n = strlen(token) + 1;
  575. _geneuniqID[row] = malloc(n*sizeof(char));
  576. strcpy (_geneuniqID[row],token);
  577. }
  578. else if (fileColumn==geneNameColumn)
  579. { const int n = strlen(token) + 1;
  580. _genename[row] = malloc(n*sizeof(char));
  581. strcpy (_genename[row],token);
  582. }
  583. else if (fileColumn==geneWeightColumn)
  584. { char* error = NULL;
  585. double number = strtod(token, &error);
  586. if (!(*error)) _geneweight[row] = number;
  587. else _geneweight[row] = 0.;
  588. }
  589. else if (fileColumn==geneOrderColumn)
  590. { char* error = NULL;
  591. double number = strtod(token, &error);
  592. if (!(*error)) _geneorder[row] = number;
  593. else _geneorder[row] = 0.;
  594. }
  595. else
  596. { char* error = NULL;
  597. _data[row][column] = 0;
  598. _mask[row][column] = 0;
  599. if (token[0]!='\0') /* Otherwise it is a missing value */
  600. { double number = strtod(token, &error);
  601. if (!(*error))
  602. { _data[row][column] = number;
  603. _mask[row][column] = 1;
  604. }
  605. }
  606. column++;
  607. }
  608. fileColumn++;
  609. }
  610. row++;
  611. }
  612. fileRow++;
  613. }
  614. free(line);
  615. }
  616. sort (_rows, _geneorder, _geneindex);
  617. sort (_columns, _arrayorder, _arrayindex);
  618. return 0;
  619. }
  620. void Save(FILE* outputfile, int geneID, int arrayID)
  621. { int row, column;
  622. if (geneID) fputs ("GID\t", outputfile);
  623. fputs (_uniqID, outputfile);
  624. fputs ("\tNAME\tGWEIGHT", outputfile);
  625. /* Now add headers for data columns */
  626. for (column = 0; column < _columns; column++)
  627. { putc('\t', outputfile);
  628. fputs(_arrayname[_arrayindex[column]], outputfile);
  629. }
  630. putc ('\n', outputfile);
  631. if (arrayID)
  632. { fputs ("AID", outputfile);
  633. if (geneID) putc ('\t',outputfile);
  634. fputs ("\t\t", outputfile);
  635. for (column = 0; column < _columns; column++)
  636. { char* ID = MakeID("ARRY",_arrayindex[column]);
  637. putc ('\t', outputfile);
  638. fputs (ID, outputfile);
  639. free (ID);
  640. }
  641. putc ('\n', outputfile);
  642. }
  643. fputs ("EWEIGHT", outputfile);
  644. if (geneID) putc ('\t', outputfile);
  645. fputs ("\t\t", outputfile);
  646. for (column = 0; column < _columns; column++)
  647. fprintf (outputfile, "\t%f", _arrayweight[_arrayindex[column]]);
  648. putc ('\n', outputfile);
  649. for (row = 0; row < _rows; row++)
  650. { int index = _geneindex[row];
  651. if (geneID)
  652. { char* ID = MakeID("GENE",index);
  653. fputs (ID, outputfile);
  654. free (ID);
  655. putc ('\t', outputfile);
  656. }
  657. fputs (_geneuniqID[index], outputfile);
  658. putc ('\t', outputfile);
  659. if (_genename[index]) fputs (_genename[index], outputfile);
  660. else fputs (_geneuniqID[index], outputfile);
  661. fprintf (outputfile, "\t%f", _geneweight[index]);
  662. for (column = 0; column < _columns; column++)
  663. { int columnindex = _arrayindex[column];
  664. putc ('\t', outputfile);
  665. if (_mask[index][columnindex])
  666. fprintf (outputfile, "%f", _data[index][columnindex]);
  667. }
  668. putc ('\n', outputfile);
  669. }
  670. return;
  671. }
  672. void SelectSubset(int useRows, const int use[])
  673. { /* Allocate temporary space */
  674. char** tempID = malloc(_rows*sizeof(char*));
  675. char** tempName = malloc(_rows*sizeof(char*));
  676. double* tempOrder = malloc(_rows*sizeof(double));
  677. double* tempWeight = malloc(_rows*sizeof(double));
  678. double** tempData = malloc(_rows*sizeof(double*));
  679. int** tempMask = malloc(_rows*sizeof(int*));
  680. int counter = 0;
  681. int row, column;
  682. for (row = 0; row < _rows; row++)
  683. { int n = strlen(_geneuniqID[row]) + 1;
  684. tempData[row] = malloc(_columns*sizeof(double));
  685. tempMask[row] = malloc(_columns*sizeof(int));
  686. for (column = 0; column < _columns; column++)
  687. { tempData[row][column] = _data[row][column];
  688. tempMask[row][column] = _mask[row][column];
  689. }
  690. tempID[row] = malloc(n*sizeof(char));
  691. strcpy (tempID[row],_geneuniqID[row]);
  692. if (_genename[row])
  693. { n = strlen(_genename[row]) + 1;
  694. tempName[row] = malloc(n*sizeof(char));
  695. strcpy (tempName[row],_genename[row]);
  696. }
  697. else tempName[row] = NULL;
  698. tempOrder[row] = _geneorder[row];
  699. tempWeight[row] = _geneweight[row];
  700. }
  701. /* Deallocate space previously used */
  702. for (row = 0; row < _rows; row++)
  703. { free(_data[row]);
  704. free(_mask[row]);
  705. free(_geneuniqID[row]);
  706. free(_genename[row]);
  707. }
  708. free(_data);
  709. free(_mask);
  710. free(_geneuniqID);
  711. free(_genename);
  712. free(_geneorder);
  713. free(_geneindex);
  714. free(_geneweight);
  715. /* Allocate space that will be used now */
  716. _geneuniqID = malloc(useRows*sizeof(char*));
  717. _genename = malloc(useRows*sizeof(char*));
  718. _geneorder = malloc(useRows*sizeof(double));
  719. _geneweight = malloc(useRows*sizeof(double));
  720. _geneindex = malloc(useRows*sizeof(int));
  721. _data = malloc(useRows*sizeof(double*));
  722. _mask = malloc(useRows*sizeof(int*));
  723. for (row = 0; row < useRows; row++)
  724. { _data[row] = malloc(_columns*sizeof(double));
  725. _mask[row] = malloc(_columns*sizeof(int));
  726. }
  727. for (row = 0; row < _rows; row++)
  728. { if (use[row])
  729. { int n = strlen(tempID[row]) + 1;
  730. for (column = 0; column < _columns; column++)
  731. { _data[counter][column] = tempData[row][column];
  732. _mask[counter][column] = tempMask[row][column];
  733. }
  734. _geneuniqID[counter] = malloc(n*sizeof(char));
  735. strcpy (_geneuniqID[counter],tempID[row]);
  736. if (tempName[row])
  737. { n = strlen(tempName[row]) + 1;
  738. _genename[counter] = malloc(n*sizeof(char));
  739. strcpy (_genename[counter],tempName[row]);
  740. }
  741. else _genename[counter] = 0;
  742. _geneorder[counter] = tempOrder[row];
  743. _geneweight[counter] = tempWeight[row];
  744. counter++;
  745. }
  746. }
  747. /* Deallocate temporary data */
  748. for (row = 0; row < _rows; row++)
  749. { free(tempData[row]);
  750. free(tempMask[row]);
  751. free(tempName[row]);
  752. free(tempID[row]);
  753. }
  754. free(tempData);
  755. free(tempMask);
  756. free(tempID);
  757. free(tempName);
  758. free(tempOrder);
  759. free(tempWeight);
  760. _rows = counter;
  761. sort (_rows, _geneorder, _geneindex);
  762. return;
  763. }
  764. void LogTransform(void)
  765. { int row, column;
  766. for (row = 0; row < _rows; row++)
  767. { /* Log transformation */
  768. for (column = 0; column < _columns; column++)
  769. { if (_mask[row][column] && _data[row][column] > 0)
  770. _data[row][column] = log(_data[row][column])/log(2.);
  771. else _mask[row][column]=0;
  772. }
  773. }
  774. return;
  775. }
  776. void AdjustGenes (int MeanCenter, int MedianCenter, int Normalize)
  777. { int row, column;
  778. for (row = 0; row < _rows; row++)
  779. { /* Center genes */
  780. if (MeanCenter || MedianCenter)
  781. { int counter = 0;
  782. double* temp = malloc(_columns*sizeof(double));
  783. for (column = 0; column < _columns; column++)
  784. { if (_mask[row][column])
  785. { temp[counter] = _data[row][column];
  786. counter++;
  787. }
  788. }
  789. if (counter > 0)
  790. { if (MeanCenter)
  791. { double rowmean = mean(counter, temp);
  792. for (column = 0; column < _columns; column++)
  793. if (_mask[row][column]) _data[row][column] -= rowmean;
  794. }
  795. else if (MedianCenter)
  796. { double rowmedian = median(counter, temp);
  797. for (column = 0; column < _columns; column++)
  798. if (_mask[row][column]) _data[row][column] -= rowmedian;
  799. }
  800. }
  801. free(temp);
  802. }
  803. /* Normalize genes */
  804. if (Normalize)
  805. { double ssqu = 0;
  806. for (column = 0; column < _columns; column++)
  807. { if (_mask[row][column])
  808. { double term = _data[row][column];
  809. ssqu += term*term;
  810. }
  811. }
  812. if (ssqu > 0) /* Avoid dividing by zero */
  813. { double std = sqrt(ssqu);
  814. for (column = 0; column < _columns; column++)
  815. if (_mask[row][column]) _data[row][column] /= std;
  816. }
  817. }
  818. }
  819. }
  820. void AdjustArrays (int MeanCenter, int MedianCenter, int Normalize)
  821. { int row, column;
  822. /* Center Arrays */
  823. if (MeanCenter || MedianCenter)
  824. { double* temp = malloc(_rows*sizeof(double));
  825. for (column = 0; column < _columns; column++)
  826. { int counter = 0;
  827. for (row = 0; row < _rows; row++)
  828. { if (_mask[row][column])
  829. { temp[counter] = _data[row][column];
  830. counter++;
  831. }
  832. }
  833. if (counter > 0)
  834. { if (MeanCenter)
  835. { double columnmean = mean(counter,temp);
  836. for (row = 0; row < _rows; row++)
  837. if (_mask[row][column])
  838. _data[row][column] -= columnmean;
  839. }
  840. else if (MedianCenter)
  841. { double columnmedian = median(counter,temp);
  842. for (row = 0; row < _rows; row++)
  843. if (_mask[row][column])
  844. _data[row][column] -= columnmedian;
  845. }
  846. }
  847. }
  848. free(temp);
  849. }
  850. /* Normalize arrays */
  851. if (Normalize)
  852. { for (column = 0; column < _columns; column++)
  853. { double ssqu = 0;
  854. for (row = 0; row < _rows; row++)
  855. if (_mask[row][column])
  856. { double term = _data[row][column];
  857. ssqu += term * term;
  858. }
  859. if (ssqu > 0) /* Avoid dividing by zero */
  860. { double std = sqrt(ssqu);
  861. for (row = 0; row < _rows; row++)
  862. if (_mask[row][column]) _data[row][column] /= std;
  863. }
  864. }
  865. }
  866. return;
  867. }
  868. void PerformSOM(FILE* GeneFile, int GeneXDim, int GeneYDim, int GeneIters,
  869. double GeneTau, char GeneMetric, FILE* ArrayFile, int ArrayXDim,
  870. int ArrayYDim, int ArrayIters, double ArrayTau, char ArrayMetric)
  871. { if (GeneIters>0) PerformGeneSOM(GeneFile,
  872. GeneXDim,
  873. GeneYDim,
  874. GeneIters,
  875. GeneTau,
  876. GeneMetric);
  877. else sort (_rows, _geneorder, _geneindex);
  878. if (ArrayIters>0) PerformArraySOM(ArrayFile,
  879. ArrayXDim,
  880. ArrayYDim,
  881. ArrayIters,
  882. ArrayTau,
  883. ArrayMetric);
  884. else sort (_columns, _arrayorder, _arrayindex);
  885. return;
  886. }
  887. int FilterRow (int Row, int bStd, int bPercent, int bAbsVal, int bMaxMin,
  888. double absVal, double percent, double std, int numberAbs, double maxmin)
  889. { int Count = 0;
  890. int CountAbs = 0;
  891. double Sum = 0;
  892. double Sum2 = 0;
  893. double Min = 10000000;
  894. double Max = -10000000;
  895. /* Compute some row stats */
  896. int Column;
  897. for (Column = 0; Column < _columns; Column++)
  898. { if (_mask[Row][Column])
  899. { double value = _data[Row][Column];
  900. Sum += value;
  901. Sum2 += value*value;
  902. Count ++;
  903. Min = min(value,Min);
  904. Max = max(value,Max);
  905. if (fabs(value) >= absVal) CountAbs++;
  906. }
  907. }
  908. /* Filter based on percent values present;
  909. * remove rows with too many missing values.
  910. */
  911. if (bPercent)
  912. { int number = (int) ceil(percent*_columns/100);
  913. if (Count < number) return 0;
  914. }
  915. /* Remove rows with low SD */
  916. if (bStd)
  917. { if (Count > 1)
  918. { double Ave = Sum / (double) Count;
  919. double Var = (Sum2 - 2 * Ave * Sum + Count * Ave * Ave)/ (Count-1);
  920. if (sqrt(Var) < std) return 0;
  921. }
  922. else return 0;
  923. }
  924. /* Remove rows with too few extreme values */
  925. if (bAbsVal && CountAbs < numberAbs) return 0;
  926. /* Remove rows with too small Max-Min */
  927. if (bMaxMin && Max - Min < maxmin) return 0;
  928. return 1;
  929. }
  930. const char*
  931. CalculateWeights(double GeneCutoff, double GeneExponent, char GeneDist,
  932. double ArrayCutoff, double ArrayExponent, char ArrayDist)
  933. { double* geneweight = NULL;
  934. double* arrayweight = NULL;
  935. if (GeneCutoff && GeneExponent && GeneDist)
  936. { geneweight = calculate_weights(_rows, _columns, _data, _mask,
  937. _arrayweight, 0, GeneDist,
  938. GeneCutoff, GeneExponent);
  939. if (!geneweight)
  940. return "Insufficient memory to calculate the row weights";
  941. }
  942. if (ArrayCutoff && ArrayExponent && ArrayDist)
  943. { arrayweight = calculate_weights(_rows, _columns, _data, _mask,
  944. _geneweight, 1, ArrayDist,
  945. ArrayCutoff, ArrayExponent);
  946. if (!arrayweight)
  947. { if (geneweight) free(geneweight);
  948. return "Insufficient memory to calculate the column weights";
  949. }
  950. }
  951. if (geneweight)
  952. { free(_geneweight);
  953. _geneweight = geneweight;
  954. }
  955. if (arrayweight)
  956. { free(_arrayweight);
  957. _arrayweight = arrayweight;
  958. }
  959. return NULL;
  960. }
  961. int HierarchicalCluster(FILE* file, char metric, int transpose, char method)
  962. { int i;
  963. double* nodeorder;
  964. int* nodecounts;
  965. char** nodeID;
  966. const int nNodes = (transpose ? _columns : _rows) - 1;
  967. const double* order = (transpose==0) ? _geneorder : _arrayorder;
  968. double* weight = (transpose==0) ? _arrayweight : _geneweight;
  969. const char* keyword = (transpose==0) ? "GENE" : "ARRY";
  970. /* Perform hierarchical clustering. */
  971. Node * tree = treecluster(_rows, _columns, _data, _mask, weight, transpose,
  972. metric, method, NULL);
  973. if (!tree) return 0;
  974. if (metric=='e' || metric=='b')
  975. /* Scale all distances such that they are between 0 and 1 */
  976. { double scale = 0.0;
  977. for (i = 0; i < nNodes; i++)
  978. if (tree[i].distance > scale) scale = tree[i].distance;
  979. if (scale) for (i = 0; i < nNodes; i++) tree[i].distance /= scale;
  980. }
  981. /* Now we join nodes */
  982. nodeorder = malloc(nNodes*sizeof(double));
  983. nodecounts = malloc(nNodes*sizeof(int));
  984. nodeID = malloc(nNodes*sizeof(char*));
  985. for (i = 0; i < nNodes; i++)
  986. { int min1 = tree[i].left;
  987. int min2 = tree[i].right;
  988. /* min1 and min2 are the elements that are to be joined */
  989. double order1;
  990. double order2;
  991. int counts1;
  992. int counts2;
  993. char* ID1;
  994. char* ID2;
  995. nodeID[i] = MakeID ("NODE",i+1);
  996. if (min1 < 0)
  997. { int index1 = -min1-1;
  998. order1 = nodeorder[index1];
  999. counts1 = nodecounts[index1];
  1000. ID1 = nodeID[index1];
  1001. tree[i].distance = max(tree[i].distance, tree[index1].distance);
  1002. }
  1003. else
  1004. { order1 = order[min1];
  1005. counts1 = 1;
  1006. ID1 = MakeID (keyword, min1);
  1007. }
  1008. if (min2 < 0)
  1009. { int index2 = -min2-1;
  1010. order2 = nodeorder[index2];
  1011. counts2 = nodecounts[index2];
  1012. ID2 = nodeID[index2];
  1013. tree[i].distance = max(tree[i].distance, tree[index2].distance);
  1014. }
  1015. else
  1016. { order2 = order[min2];
  1017. counts2 = 1;
  1018. ID2 = MakeID (keyword, min2);
  1019. }
  1020. fprintf (file, "%s\t%s\t%s\t", nodeID[i], ID1, ID2);
  1021. fprintf (file, "%f\n", 1.0-tree[i].distance);
  1022. if (min1>=0) free(ID1);
  1023. if (min2>=0) free(ID2);
  1024. nodecounts[i] = counts1 + counts2;
  1025. nodeorder[i] = (counts1*order1 + counts2*order2) / (counts1 + counts2);
  1026. }
  1027. /* Now set up order based on the tree structure */
  1028. TreeSort((transpose==0) ? 'g' : 'a', nNodes, order, nodeorder, nodecounts,
  1029. tree);
  1030. free(nodecounts);
  1031. free(nodeorder);
  1032. for (i = 0; i < nNodes; i++) free(nodeID[i]);
  1033. free(nodeID);
  1034. free(tree);
  1035. return 1;
  1036. }
  1037. int GeneKCluster(int k, int nTrials, char method, char dist, int* NodeMap)
  1038. { int ifound = 0;
  1039. double error;
  1040. kcluster (k, _rows, _columns, _data, _mask,
  1041. _arrayweight, 0, nTrials, method, dist, NodeMap, &error, &ifound);
  1042. SetClusterIndex('g', k, NodeMap);
  1043. return ifound;
  1044. }
  1045. int ArrayKCluster(int k, int nTrials, char method, char dist, int* NodeMap)
  1046. { int ifound = 0;
  1047. double error;
  1048. kcluster (k, _rows, _columns, _data, _mask,
  1049. _geneweight, 1, nTrials, method, dist, NodeMap, &error, &ifound);
  1050. SetClusterIndex ('a', k, NodeMap);
  1051. return ifound;
  1052. }
  1053. void
  1054. SaveGeneKCluster(FILE* file, int k, const int* NodeMap)
  1055. { int i, cluster;
  1056. int* geneindex = malloc(_rows*sizeof(int));
  1057. fprintf (file, "%s\tGROUP\n", _uniqID);
  1058. for (i=0; i<_rows; i++) geneindex[i] = i;
  1059. sort (_rows,_geneorder,geneindex);
  1060. for (cluster = 0; cluster < k; cluster++)
  1061. { for (i = 0; i < _rows; i++)
  1062. { const int j = geneindex[i];
  1063. if (NodeMap[j]==cluster)
  1064. fprintf (file, "%s\t%d\n", _geneuniqID[j], NodeMap[j]);
  1065. }
  1066. }
  1067. free(geneindex);
  1068. }
  1069. void
  1070. SaveArrayKCluster(FILE* file, int k, const int* NodeMap)
  1071. { int i, cluster;
  1072. int* arrayindex = malloc(_columns*sizeof(int));
  1073. fputs ("ARRAY\tGROUP\n", file);
  1074. for (i=0; i<_columns; i++) arrayindex[i] = i;
  1075. sort (_columns,_arrayorder,arrayindex);
  1076. for (cluster = 0; cluster < k; cluster++)
  1077. { for (i = 0; i < _columns; i++)
  1078. { const int j = arrayindex[i];
  1079. if (NodeMap[j]==cluster)
  1080. fprintf (file, "%s\t%d\n", _arrayname[j], NodeMap[j]);
  1081. }
  1082. }
  1083. free(arrayindex);
  1084. }
  1085. const char* PerformGenePCA(FILE* coordinatefile, FILE* pcfile)
  1086. {
  1087. int i, j;
  1088. const int nmin = min(_rows,_columns);
  1089. double** u = malloc(_rows*sizeof(double*));
  1090. double** v = malloc(nmin*sizeof(double*));
  1091. double* w = malloc(nmin*sizeof(double));
  1092. double* m = malloc(_columns*sizeof(double));
  1093. for (i = 0; i < _rows; i++)
  1094. { u[i] = malloc(_columns*sizeof(double));
  1095. if (!u[i]) break;
  1096. }
  1097. if (i < _rows) /* then we encountered the break */
  1098. { while(i-- > 0) free(u[i]);
  1099. free(u);
  1100. u = NULL;
  1101. }
  1102. for (i = 0; i < nmin; i++)
  1103. { v[i] = malloc(nmin*sizeof(double));
  1104. if (!v[i]) break;
  1105. }
  1106. if (i < nmin) /* then we encountered the break */
  1107. { while(i-- > 0) free(v[i]);
  1108. free(v);
  1109. v = NULL;
  1110. }
  1111. if (!u || !v || !w ||!m)
  1112. { if (u) free(u);
  1113. if (v) free(v);
  1114. if (w) free(w);
  1115. if (m) free(m);
  1116. return "Memory allocation error in PerformGenePCA";
  1117. }
  1118. for (j = 0; j < _columns; j++)
  1119. { double value;
  1120. m[j] = 0.0;
  1121. for (i = 0; i < _rows; i++)
  1122. { value = _data[i][j];
  1123. u[i][j] = value;
  1124. m[j] += value;
  1125. }
  1126. m[j] /= _rows;
  1127. for (i = 0; i < _rows; i++) u[i][j] -= m[j];
  1128. }
  1129. pca(_rows, _columns, u, v, w);
  1130. fprintf(coordinatefile, "%s\tNAME\tGWEIGHT", _uniqID);
  1131. for (j=0; j < nmin; j++)
  1132. fprintf(coordinatefile, "\t%f", w[j]);
  1133. putc ('\n', coordinatefile);
  1134. fprintf(pcfile, "EIGVALUE");
  1135. for (j=0; j < _columns; j++)
  1136. fprintf(pcfile, "\t%s", _arrayname[j]);
  1137. putc ('\n', pcfile);
  1138. fprintf(pcfile, "MEAN");
  1139. for (j=0; j < _columns; j++)
  1140. fprintf(pcfile, "\t%f", m[j]);
  1141. putc ('\n', pcfile);
  1142. if (_rows>_columns)
  1143. { for (i=0; i<_rows; i++)
  1144. { fprintf (coordinatefile, "%s\t",_geneuniqID[i]);
  1145. if (_genename[i]) fputs (_genename[i], coordinatefile);
  1146. else fputs (_geneuniqID[i], coordinatefile);
  1147. fprintf (coordinatefile, "\t%f", _geneweight[i]);
  1148. for (j=0; j<_columns; j++)
  1149. fprintf (coordinatefile, "\t%f", u[i][j]);
  1150. putc ('\n', coordinatefile);
  1151. }
  1152. for (i = 0; i < nmin; i++)
  1153. { fprintf(pcfile, "%f", w[i]);
  1154. for (j=0; j < _columns; j++)
  1155. fprintf(pcfile, "\t%f", v[i][j]);
  1156. putc ('\n', pcfile);
  1157. }
  1158. }
  1159. else
  1160. { for (i=0; i<_rows; i++)
  1161. { fprintf (coordinatefile, "%s\t",_geneuniqID[i]);
  1162. if (_genename[i]) fputs (_genename[i], coordinatefile);
  1163. else fputs (_geneuniqID[i], coordinatefile);
  1164. fprintf (coordinatefile, "\t%f", _geneweight[i]);
  1165. for (j=0; j<nmin; j++)
  1166. fprintf (coordinatefile, "\t%f", v[i][j]);
  1167. putc ('\n', coordinatefile);
  1168. }
  1169. for (i = 0; i < _rows; i++)
  1170. { fprintf(pcfile, "%f", w[i]);
  1171. for (j=0; j < _columns; j++)
  1172. fprintf(pcfile, "\t%f", u[i][j]);
  1173. putc('\n', pcfile);
  1174. }
  1175. }
  1176. for (i = 0; i < _rows; i++) free(u[i]);
  1177. for (i = 0; i < nmin; i++) free(v[i]);
  1178. free(u);
  1179. free(v);
  1180. free(w);
  1181. free(m);
  1182. return NULL;
  1183. }
  1184. const char* PerformArrayPCA(FILE* coordinatefile, FILE* pcfile)
  1185. {
  1186. int i, j;
  1187. const int nmin = min(_rows,_columns);
  1188. double** u = malloc(_columns*sizeof(double*));
  1189. double** v = malloc(nmin*sizeof(double*));
  1190. double* w = malloc(nmin*sizeof(double));
  1191. double* m = malloc(_rows*sizeof(double));
  1192. for (i = 0; i < _columns; i++)
  1193. { u[i] = malloc(_rows*sizeof(double));
  1194. if (!u[i]) break;
  1195. }
  1196. if (i < _columns) /* then we encountered the break */
  1197. { while(i-- > 0) free(u[i]);
  1198. free(u);
  1199. u = NULL;
  1200. }
  1201. for (i = 0; i < nmin; i++)
  1202. { v[i] = malloc(nmin*sizeof(double));
  1203. if (!v[i]) break;
  1204. }
  1205. if (i < nmin) /* then we encountered the break */
  1206. { while(i-- > 0) free(v[i]);
  1207. free(v);
  1208. v = NULL;
  1209. }
  1210. if (!u || !v || !w ||!m)
  1211. { if (u) free(u);
  1212. if (v) free(v);
  1213. if (w) free(w);
  1214. if (m) free(m);
  1215. return "Memory allocation error in PerformGenePCA";
  1216. }
  1217. for (j = 0; j < _rows; j++)
  1218. { double value;
  1219. m[j] = 0.0;
  1220. for (i = 0; i < _columns; i++)
  1221. { value = _data[j][i];
  1222. u[i][j] = value;
  1223. m[j] += value;
  1224. }
  1225. m[j] /= _columns;
  1226. for (i = 0; i < _columns; i++) u[i][j] -= m[j];
  1227. }
  1228. pca(_columns, _rows, u, v, w);
  1229. fprintf(coordinatefile, "EIGVALUE");
  1230. for (j=0; j < _columns; j++)
  1231. fprintf (coordinatefile, "\t%s", _arrayname[j]);
  1232. putc ('\n', coordinatefile);
  1233. fprintf(coordinatefile, "EWEIGHT");
  1234. for (j=0; j < _columns; j++)
  1235. fprintf (coordinatefile, "\t%f", _arrayweight[j]);
  1236. putc ('\n', coordinatefile);
  1237. fprintf(pcfile, "%s\tNAME\tMEAN", _uniqID);
  1238. for (j=0; j < nmin; j++)
  1239. fprintf(pcfile, "\t%f", w[j]);
  1240. putc ('\n', pcfile);
  1241. if (_rows>_columns)
  1242. { for (i = 0; i < nmin; i++)
  1243. { fprintf(coordinatefile, "%f", w[i]);
  1244. for (j=0; j<_columns; j++)
  1245. fprintf (coordinatefile, "\t%f", v[j][i]);
  1246. putc ('\n', coordinatefile);
  1247. }
  1248. for (i = 0; i < _rows; i++)
  1249. { fprintf(pcfile, "%s\t",_geneuniqID[i]);
  1250. if (_genename[i]) fputs (_genename[i], pcfile);
  1251. else fputs (_geneuniqID[i], pcfile);
  1252. fprintf(pcfile, "\t%f", m[i]);
  1253. for (j=0; j<_columns; j++)
  1254. fprintf(pcfile, "\t%f", u[j][i]);
  1255. putc ('\n', pcfile);
  1256. }
  1257. }
  1258. else /* _rows < _columns */
  1259. { for (i=0; i<_rows; i++)
  1260. { fprintf(coordinatefile, "%f", w[i]);
  1261. for (j=0; j<_columns; j++)
  1262. fprintf (coordinatefile, "\t%f", u[j][i]);
  1263. putc ('\n', coordinatefile);
  1264. }
  1265. for (i = 0; i < _rows; i++)
  1266. { fprintf(pcfile, "%s\t",_geneuniqID[i]);
  1267. if (_genename[i]) fputs (_genename[i], pcfile);
  1268. else fputs (_geneuniqID[i], pcfile);
  1269. fprintf(pcfile, "\t%f", m[i]);
  1270. for (j=0; j<nmin; j++)
  1271. fprintf(pcfile, "\t%f", v[j][i]);
  1272. putc ('\n', pcfile);
  1273. }
  1274. }
  1275. for (i = 0; i < _columns; i++) free(u[i]);
  1276. for (i = 0; i < nmin; i++) free(v[i]);
  1277. free(u);
  1278. free(v);
  1279. free(w);
  1280. free(m);
  1281. return NULL;
  1282. }