Table.cpp 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. /* Table.cpp
  2. *
  3. * Copyright (C) 2002-2018 Paul Boersma
  4. *
  5. * This code is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This code is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. * See the GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this work. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <ctype.h>
  19. #include "Table.h"
  20. #include "NUM2.h"
  21. #include "Formula.h"
  22. #include "SSCP.h"
  23. #include "oo_DESTROY.h"
  24. #include "Table_def.h"
  25. #include "oo_COPY.h"
  26. #include "Table_def.h"
  27. #include "oo_EQUAL.h"
  28. #include "Table_def.h"
  29. #include "oo_CAN_WRITE_AS_ENCODING.h"
  30. #include "Table_def.h"
  31. #include "oo_WRITE_TEXT.h"
  32. #include "Table_def.h"
  33. #include "oo_WRITE_BINARY.h"
  34. #include "Table_def.h"
  35. #include "oo_READ_TEXT.h"
  36. #include "Table_def.h"
  37. #include "oo_READ_BINARY.h"
  38. #include "Table_def.h"
  39. #include "oo_DESCRIPTION.h"
  40. #include "Table_def.h"
  41. Thing_implement (TableRow, Daata, 0);
  42. Thing_implement (Table, Daata, 0);
  43. void structTable :: v_info () {
  44. our structDaata :: v_info ();
  45. MelderInfo_writeLine (U"Number of rows: ", our rows.size);
  46. MelderInfo_writeLine (U"Number of columns: ", our numberOfColumns);
  47. }
  48. conststring32 structTable :: v_getColStr (integer columnNumber) {
  49. if (columnNumber < 1 || columnNumber > our numberOfColumns)
  50. return nullptr;
  51. return our columnHeaders [columnNumber]. label ? our columnHeaders [columnNumber]. label.get() : U"";
  52. }
  53. double structTable :: v_getMatrix (integer rowNumber, integer columnNumber) {
  54. if (rowNumber < 1 || rowNumber > our rows.size)
  55. return undefined;
  56. if (columnNumber < 1 || columnNumber > our numberOfColumns)
  57. return undefined;
  58. conststring32 stringValue = our rows.at [rowNumber] -> cells [columnNumber]. string.get();
  59. return stringValue ? Melder_atof (stringValue) : undefined;
  60. }
  61. conststring32 structTable :: v_getMatrixStr (integer rowNumber, integer columnNumber) {
  62. if (rowNumber < 1 || rowNumber > our rows.size)
  63. return U"";
  64. if (columnNumber < 1 || columnNumber > our numberOfColumns)
  65. return U"";
  66. conststring32 stringValue = our rows.at [rowNumber] -> cells [columnNumber]. string.get();
  67. return stringValue ? stringValue : U"";
  68. }
  69. double structTable :: v_getColIndex (conststring32 columnLabel) {
  70. return Table_findColumnIndexFromColumnLabel (this, columnLabel);
  71. }
  72. static autoTableRow TableRow_create (integer numberOfColumns) {
  73. autoTableRow me = Thing_new (TableRow);
  74. my numberOfColumns = numberOfColumns;
  75. my cells = NUMvector <structTableCell> (1, numberOfColumns);
  76. return me;
  77. }
  78. void Table_initWithoutColumnNames (Table me, integer numberOfRows, integer numberOfColumns) {
  79. if (numberOfColumns < 1)
  80. Melder_throw (U"Cannot create table without columns.");
  81. my numberOfColumns = numberOfColumns;
  82. my columnHeaders = NUMvector <structTableColumnHeader> (1, numberOfColumns);
  83. for (integer irow = 1; irow <= numberOfRows; irow ++)
  84. Table_appendRow (me);
  85. }
  86. autoTable Table_createWithoutColumnNames (integer numberOfRows, integer numberOfColumns) {
  87. try {
  88. autoTable me = Thing_new (Table);
  89. Table_initWithoutColumnNames (me.get(), numberOfRows, numberOfColumns);
  90. return me;
  91. } catch (MelderError) {
  92. Melder_throw (U"Table not created.");
  93. }
  94. }
  95. conststring32 Table_messageColumn (Table me, integer column) {
  96. if (column >= 1 && column <= my numberOfColumns && my columnHeaders [column]. label && my columnHeaders [column]. label [0] != U'\0')
  97. return Melder_cat (U"\"", my columnHeaders [column]. label.get(), U"\"");
  98. else
  99. return Melder_integer (column);
  100. }
  101. void Table_initWithColumnNames (Table me, integer numberOfRows, conststring32 columnNames_string) {
  102. autostring32vector columnNames = STRVECtokenize (columnNames_string);
  103. Table_initWithoutColumnNames (me, numberOfRows, columnNames.size);
  104. for (integer icol = 1; icol <= columnNames.size; icol ++)
  105. Table_setColumnLabel (me, icol, columnNames [icol].get());
  106. }
  107. autoTable Table_createWithColumnNames (integer numberOfRows, conststring32 columnNames) {
  108. try {
  109. autoTable me = Thing_new (Table);
  110. Table_initWithColumnNames (me.get(), numberOfRows, columnNames);
  111. return me;
  112. } catch (MelderError) {
  113. Melder_throw (U"Table not created.");
  114. }
  115. }
  116. void Table_appendRow (Table me) {
  117. try {
  118. autoTableRow row = TableRow_create (my numberOfColumns);
  119. my rows. addItem_move (row.move());
  120. } catch (MelderError) {
  121. Melder_throw (me, U": row not appended.");
  122. }
  123. }
  124. void Table_appendColumn (Table me, conststring32 label) {
  125. try {
  126. Table_insertColumn (me, my numberOfColumns + 1, label);
  127. } catch (MelderError) {
  128. Melder_throw (me, U": column \"", label, U"\" not appended.");
  129. }
  130. }
  131. void Table_checkSpecifiedRowNumberWithinRange (Table me, integer rowNumber) {
  132. if (rowNumber < 1)
  133. Melder_throw (me, U": the specified row number is ", rowNumber, U", but should be at least 1.");
  134. if (rowNumber > my rows.size)
  135. Melder_throw (me, U": the specified row number (", rowNumber, U") exceeds my number of rows (", my rows.size, U").");
  136. }
  137. void Table_removeRow (Table me, integer rowNumber) {
  138. try {
  139. if (my rows.size == 1)
  140. Melder_throw (me, U": cannot remove my only row.");
  141. Table_checkSpecifiedRowNumberWithinRange (me, rowNumber);
  142. my rows. removeItem (rowNumber);
  143. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  144. my columnHeaders [icol]. numericized = false;
  145. } catch (MelderError) {
  146. Melder_throw (me, U": row ", rowNumber, U" not removed.");
  147. }
  148. }
  149. void Table_checkSpecifiedColumnNumberWithinRange (Table me, integer columnNumber) {
  150. if (columnNumber < 1)
  151. Melder_throw (me, U": the specified column number is ", columnNumber, U", but should be at least 1.");
  152. if (columnNumber > my numberOfColumns)
  153. Melder_throw (me, U": the specified column number is ", columnNumber, U", but should be at most my number of columns (", my numberOfColumns, U").");
  154. }
  155. void Table_removeColumn (Table me, integer columnNumber) {
  156. try {
  157. if (my numberOfColumns == 1)
  158. Melder_throw (me, U": cannot remove my only column.");
  159. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  160. /*
  161. Changes without error.
  162. */
  163. for (integer icol = columnNumber; icol < my numberOfColumns; icol ++)
  164. my columnHeaders [icol] = std::move (my columnHeaders [icol + 1]);
  165. my columnHeaders [my numberOfColumns]. destroy ();
  166. for (integer irow = 1; irow <= my rows.size; irow ++) {
  167. TableRow row = my rows.at [irow];
  168. for (integer icol = columnNumber; icol < row -> numberOfColumns; icol ++)
  169. row -> cells [icol] = std::move (row -> cells [icol + 1]);
  170. row -> cells [row -> numberOfColumns]. destroy ();
  171. row -> numberOfColumns --;
  172. }
  173. my numberOfColumns --;
  174. } catch (MelderError) {
  175. Melder_throw (me, U": column ", Table_messageColumn (me, columnNumber), U" not removed.");
  176. }
  177. }
  178. void Table_insertRow (Table me, integer rowNumber) {
  179. try {
  180. /*
  181. Check without changes.
  182. */
  183. if (rowNumber < 1)
  184. Melder_throw (me, U": the specified row number is ", rowNumber, U", but should be at least 1.");
  185. if (rowNumber > my rows.size + 1)
  186. Melder_throw (me, U": the specified row number is ", rowNumber, U", but should be at most my number of rows (", my rows.size, U") plus 1.");
  187. autoTableRow row = TableRow_create (my numberOfColumns);
  188. /*
  189. Safe change (on error, me is not changed).
  190. */
  191. my rows. addItemAtPosition_move (row.move(), rowNumber);
  192. /*
  193. Changes without error.
  194. */
  195. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  196. my columnHeaders [icol]. numericized = false;
  197. } catch (MelderError) {
  198. Melder_throw (me, U": row ", rowNumber, U" not inserted.");
  199. }
  200. }
  201. void Table_insertColumn (Table me, integer columnNumber, conststring32 label /* cattable */) {
  202. try {
  203. /*
  204. Check without changes.
  205. */
  206. if (columnNumber < 1)
  207. Melder_throw (me, U": the specified column number is ", columnNumber, U", but should be at least 1.");
  208. if (columnNumber > my numberOfColumns + 1)
  209. Melder_throw (me, U": the specified column number is ", columnNumber, U", but should be at most my number of columns (", my numberOfColumns, U") plus 1.");
  210. autostring32 newLabel = Melder_dup (label);
  211. autoTable thee = Table_createWithoutColumnNames (my rows.size, my numberOfColumns + 1);
  212. /*
  213. Changes without error.
  214. */
  215. /*
  216. Transfer column headers to larger structure.
  217. */
  218. for (integer icol = 1; icol < columnNumber; icol ++)
  219. thy columnHeaders [icol] = std::move (my columnHeaders [icol]);
  220. thy columnHeaders [columnNumber]. label = newLabel.move();
  221. thy columnHeaders [columnNumber]. numericized = false;
  222. for (integer icol = my numberOfColumns + 1; icol > columnNumber; icol --)
  223. thy columnHeaders [icol] = std::move (my columnHeaders [icol - 1]);
  224. /*
  225. Transfer rows to larger structure.
  226. */
  227. for (integer irow = 1; irow <= my rows.size; irow ++) {
  228. TableRow myRow = my rows.at [irow];
  229. TableRow thyRow = thy rows.at [irow];
  230. for (integer icol = 1; icol < columnNumber; icol ++)
  231. thyRow -> cells [icol] = std::move (myRow -> cells [icol]);
  232. Melder_assert (! thyRow -> cells [columnNumber]. string);
  233. Melder_assert (thyRow -> cells [columnNumber]. number == 0.0);
  234. for (integer icol = myRow -> numberOfColumns + 1; icol > columnNumber; icol --)
  235. thyRow -> cells [icol] = std::move (myRow -> cells [icol - 1]);
  236. }
  237. /*
  238. Transfer larger structure with column headers to me.
  239. */
  240. NUMvector_free <structTableColumnHeader> (my columnHeaders, 1); // make room...
  241. my columnHeaders = thy columnHeaders; // ...fill in and dangle...
  242. thy columnHeaders = nullptr; // ...undangle
  243. /*
  244. Transfer larger structure with rows to me.
  245. */
  246. my rows = thy rows.move();
  247. /*
  248. Update my state.
  249. */
  250. my numberOfColumns ++;
  251. } catch (MelderError) {
  252. Melder_throw (me, U": column not inserted.");
  253. }
  254. }
  255. void Table_setColumnLabel (Table me, integer columnNumber, conststring32 label /* cattable */) {
  256. try {
  257. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  258. my columnHeaders [columnNumber]. label = Melder_dup (label);
  259. } catch (MelderError) {
  260. Melder_throw (me, U": column label not set.");
  261. }
  262. }
  263. integer Table_findColumnIndexFromColumnLabel (Table me, conststring32 label) noexcept {
  264. for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
  265. if (my columnHeaders [icol]. label && str32equ (my columnHeaders [icol]. label.get(), label))
  266. return icol;
  267. }
  268. return 0;
  269. }
  270. integer Table_getColumnIndexFromColumnLabel (Table me, conststring32 columnLabel) {
  271. integer columnNumber = Table_findColumnIndexFromColumnLabel (me, columnLabel);
  272. if (columnNumber == 0)
  273. Melder_throw (me, U": there is no column named \"", columnLabel, U"\".");
  274. return columnNumber;
  275. }
  276. autoINTVEC Table_getColumnIndicesFromColumnLabelString (Table me, conststring32 columnLabels_string) {
  277. autostring32vector columnLabels = STRVECtokenize (columnLabels_string);
  278. if (columnLabels.size < 1)
  279. Melder_throw (me, U": you specified an empty list of columns.");
  280. autoINTVEC columns = INTVECraw (columnLabels.size);
  281. for (integer icol = 1; icol <= columnLabels.size; icol ++)
  282. columns [icol] = Table_getColumnIndexFromColumnLabel (me, columnLabels [icol].get());
  283. return columns;
  284. }
  285. integer Table_searchColumn (Table me, integer columnNumber, conststring32 value) noexcept {
  286. for (integer irow = 1; irow <= my rows.size; irow ++) {
  287. TableRow row = my rows.at [irow];
  288. if (row -> cells [columnNumber]. string && str32equ (row -> cells [columnNumber]. string.get(), value))
  289. return irow;
  290. }
  291. return 0;
  292. }
  293. void Table_setStringValue (Table me, integer rowNumber, integer columnNumber, conststring32 value /* cattable */) {
  294. try {
  295. /*
  296. Check without changes.
  297. */
  298. Table_checkSpecifiedRowNumberWithinRange (me, rowNumber);
  299. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  300. autostring32 newLabel = Melder_dup (value);
  301. /*
  302. Change without errors.
  303. */
  304. TableRow row = my rows.at [rowNumber];
  305. row -> cells [columnNumber]. string = newLabel.move();
  306. my columnHeaders [columnNumber]. numericized = false;
  307. } catch (MelderError) {
  308. Melder_throw (me, U": string value not set.");
  309. }
  310. }
  311. void Table_setNumericValue (Table me, integer rowNumber, integer columnNumber, double value) {
  312. try {
  313. /*
  314. Check without changes.
  315. */
  316. Table_checkSpecifiedRowNumberWithinRange (me, rowNumber);
  317. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  318. autostring32 newLabel = Melder_dup (Melder_double (value));
  319. /*
  320. Change without errors.
  321. */
  322. TableRow row = my rows.at [rowNumber];
  323. row -> cells [columnNumber]. string = newLabel.move();
  324. my columnHeaders [columnNumber]. numericized = false;
  325. } catch (MelderError) {
  326. Melder_throw (me, U": numeric value not set.");
  327. }
  328. }
  329. bool Table_isCellNumeric_ErrorFalse (Table me, integer rowNumber, integer columnNumber) {
  330. if (rowNumber < 1 || rowNumber > my rows.size) return false;
  331. if (columnNumber < 1 || columnNumber > my numberOfColumns) return false;
  332. TableRow row = my rows.at [rowNumber];
  333. conststring32 cell = row -> cells [columnNumber]. string.get();
  334. if (! cell)
  335. return true; // namely the value --undefined--
  336. /*
  337. Skip leading white space, in order to separately detect "?" and "--undefined--".
  338. */
  339. while (*cell == U' ' || *cell == U'\t' || *cell == U'\n' || *cell == U'\r') cell ++;
  340. if (cell [0] == U'\0')
  341. return true; // only white space: the value --undefined--
  342. if (cell [0] == U'?' || str32nequ (cell, U"--undefined--", 13)) {
  343. /*
  344. See whether there is anything else besides "?" or "--undefined--" and white space.
  345. */
  346. cell += ( cell [0] == U'?' ) ? 1 : 13;
  347. while (*cell == U' ' || *cell == U'\t' || *cell == U'\n' || *cell == U'\r') cell ++;
  348. return *cell == U'\0'; // only white space after the "?" or "--undefined--"
  349. }
  350. return Melder_isStringNumeric (cell);
  351. }
  352. bool Table_isColumnNumeric_ErrorFalse (Table me, integer columnNumber) {
  353. if (columnNumber < 1 || columnNumber > my numberOfColumns)
  354. return false;
  355. for (integer irow = 1; irow <= my rows.size; irow ++) {
  356. if (! Table_isCellNumeric_ErrorFalse (me, irow, columnNumber))
  357. return false;
  358. }
  359. return true;
  360. }
  361. static integer stringCompare_column;
  362. static int stringCompare_NoError (const void *first, const void *second) {
  363. TableRow me = * (TableRow *) first, thee = * (TableRow *) second;
  364. conststring32 firstString = my cells [stringCompare_column]. string.get();
  365. conststring32 secondString = thy cells [stringCompare_column]. string.get();
  366. return str32cmp (firstString ? firstString : U"", secondString ? secondString : U"");
  367. }
  368. static void sortRowsByStrings_Assert (Table me, integer columnNumber) {
  369. Melder_assert (columnNumber >= 1 && columnNumber <= my numberOfColumns);
  370. stringCompare_column = columnNumber;
  371. qsort (& my rows.at [1], (unsigned long) my rows.size, sizeof (TableRow), stringCompare_NoError);
  372. }
  373. static int indexCompare_NoError (const void *first, const void *second) {
  374. TableRow me = * (TableRow *) first, thee = * (TableRow *) second;
  375. if (my sortingIndex < thy sortingIndex) return -1;
  376. if (my sortingIndex > thy sortingIndex) return +1;
  377. return 0;
  378. }
  379. static void sortRowsByIndex_NoError (Table me) {
  380. qsort (& my rows.at [1], (unsigned long) my rows.size, sizeof (TableRow), indexCompare_NoError);
  381. }
  382. void Table_numericize_Assert (Table me, integer columnNumber) {
  383. Melder_assert (columnNumber >= 1 && columnNumber <= my numberOfColumns);
  384. if (my columnHeaders [columnNumber]. numericized) return;
  385. if (Table_isColumnNumeric_ErrorFalse (me, columnNumber)) {
  386. for (integer irow = 1; irow <= my rows.size; irow ++) {
  387. TableRow row = my rows.at [irow];
  388. const conststring32 string = row -> cells [columnNumber]. string.get();
  389. row -> cells [columnNumber]. number =
  390. ! string || string [0] == U'\0' || (string [0] == U'?' && string [1] == U'\0') ? undefined :
  391. Melder_atof (string);
  392. }
  393. } else {
  394. integer iunique = 0;
  395. conststring32 previousString = nullptr;
  396. for (integer irow = 1; irow <= my rows.size; irow ++) {
  397. TableRow row = my rows.at [irow];
  398. row -> sortingIndex = irow;
  399. }
  400. sortRowsByStrings_Assert (me, columnNumber);
  401. for (integer irow = 1; irow <= my rows.size; irow ++) {
  402. TableRow row = my rows.at [irow];
  403. conststring32 string = row -> cells [columnNumber]. string.get();
  404. if (! string)
  405. string = U"";
  406. if (! previousString || ! str32equ (string, previousString))
  407. iunique ++;
  408. row -> cells [columnNumber]. number = iunique;
  409. previousString = string;
  410. }
  411. sortRowsByIndex_NoError (me);
  412. }
  413. my columnHeaders [columnNumber]. numericized = true;
  414. }
  415. static void Table_numericize_checkDefined (Table me, integer columnNumber) {
  416. Table_numericize_Assert (me, columnNumber);
  417. for (integer irow = 1; irow <= my rows.size; irow ++) {
  418. TableRow row = my rows.at [irow];
  419. if (isundef (row -> cells [columnNumber]. number)) {
  420. Melder_throw (me, U": the cell in row ", irow,
  421. U" of column \"", my columnHeaders [columnNumber]. label ? my columnHeaders [columnNumber]. label.get() : Melder_integer (columnNumber),
  422. U"\" is undefined."
  423. );
  424. }
  425. }
  426. }
  427. conststring32 Table_getStringValue_Assert (Table me, integer rowNumber, integer columnNumber) {
  428. Melder_assert (rowNumber >= 1 && rowNumber <= my rows.size);
  429. Melder_assert (columnNumber >= 1 && columnNumber <= my numberOfColumns);
  430. TableRow row = my rows.at [rowNumber];
  431. return row -> cells [columnNumber]. string ? row -> cells [columnNumber]. string.get() : U"";
  432. }
  433. double Table_getNumericValue_Assert (Table me, integer rowNumber, integer columnNumber) {
  434. Melder_assert (rowNumber >= 1 && rowNumber <= my rows.size);
  435. Melder_assert (columnNumber >= 1 && columnNumber <= my numberOfColumns);
  436. TableRow row = my rows.at [rowNumber];
  437. Table_numericize_Assert (me, columnNumber);
  438. return row -> cells [columnNumber]. number;
  439. }
  440. double Table_getMean (Table me, integer columnNumber) {
  441. try {
  442. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  443. Table_numericize_checkDefined (me, columnNumber);
  444. if (my rows.size < 1)
  445. return undefined;
  446. longdouble sum = 0.0;
  447. for (integer irow = 1; irow <= my rows.size; irow ++) {
  448. TableRow row = my rows.at [irow];
  449. sum += row -> cells [columnNumber]. number;
  450. }
  451. return (double) sum / my rows.size;
  452. } catch (MelderError) {
  453. Melder_throw (me, U": cannot compute mean of column ", columnNumber, U".");
  454. }
  455. }
  456. double Table_getMaximum (Table me, integer columnNumber) {
  457. try {
  458. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  459. Table_numericize_checkDefined (me, columnNumber);
  460. if (my rows.size < 1)
  461. return undefined;
  462. TableRow firstRow = my rows.at [1];
  463. double maximum = firstRow -> cells [columnNumber]. number;
  464. for (integer irow = 2; irow <= my rows.size; irow ++) {
  465. TableRow row = my rows.at [irow];
  466. if (row -> cells [columnNumber]. number > maximum)
  467. maximum = row -> cells [columnNumber]. number;
  468. }
  469. return maximum;
  470. } catch (MelderError) {
  471. Melder_throw (me, U": cannot compute maximum of column ", columnNumber, U".");
  472. }
  473. }
  474. double Table_getMinimum (Table me, integer columnNumber) {
  475. try {
  476. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  477. Table_numericize_checkDefined (me, columnNumber);
  478. if (my rows.size < 1)
  479. return undefined;
  480. TableRow firstRow = my rows.at [1];
  481. double minimum = firstRow -> cells [columnNumber]. number;
  482. for (integer irow = 2; irow <= my rows.size; irow ++) {
  483. TableRow row = my rows.at [irow];
  484. if (row -> cells [columnNumber]. number < minimum)
  485. minimum = row -> cells [columnNumber]. number;
  486. }
  487. return minimum;
  488. } catch (MelderError) {
  489. Melder_throw (me, U": cannot compute minimum of column ", columnNumber, U".");
  490. }
  491. }
  492. double Table_getGroupMean (Table me, integer columnNumber, integer groupColumnNumber, conststring32 group) {
  493. try {
  494. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  495. Table_numericize_checkDefined (me, columnNumber);
  496. integer n = 0;
  497. longdouble sum = 0.0;
  498. for (integer irow = 1; irow <= my rows.size; irow ++) {
  499. TableRow row = my rows.at [irow];
  500. if (Melder_equ (row -> cells [groupColumnNumber]. string.get(), group)) {
  501. n += 1;
  502. sum += row -> cells [columnNumber]. number;
  503. }
  504. }
  505. if (n < 1)
  506. return undefined;
  507. double mean = (double) sum / n;
  508. return mean;
  509. } catch (MelderError) {
  510. Melder_throw (me, U": cannot compute mean of column ", columnNumber, U" for group \"", group, U"\" of column ", groupColumnNumber, U".");
  511. }
  512. }
  513. double Table_getQuantile (Table me, integer columnNumber, double quantile) {
  514. try {
  515. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  516. Table_numericize_checkDefined (me, columnNumber);
  517. if (my rows.size < 1)
  518. return undefined;
  519. autoVEC sortingColumn = VECraw (my rows.size);
  520. for (integer irow = 1; irow <= my rows.size; irow ++) {
  521. TableRow row = my rows.at [irow];
  522. sortingColumn [irow] = row -> cells [columnNumber]. number;
  523. }
  524. VECsort_inplace (sortingColumn.get());
  525. return NUMquantile (sortingColumn.get(), quantile);
  526. } catch (MelderError) {
  527. Melder_throw (me, U": cannot compute the ", quantile, U" quantile of column ", columnNumber, U".");
  528. }
  529. }
  530. double Table_getStdev (Table me, integer columnNumber) {
  531. try {
  532. double mean = Table_getMean (me, columnNumber); // already checks for columnNumber and undefined cells
  533. if (my rows.size < 2)
  534. return undefined;
  535. longdouble sum = 0.0;
  536. for (integer irow = 1; irow <= my rows.size; irow ++) {
  537. TableRow row = my rows.at [irow];
  538. double d = row -> cells [columnNumber]. number - mean;
  539. sum += d * d;
  540. }
  541. return sqrt ((double) sum / (my rows.size - 1));
  542. } catch (MelderError) {
  543. Melder_throw (me, U": cannot compute the standard deviation of column ", columnNumber, U".");
  544. }
  545. }
  546. integer Table_drawRowFromDistribution (Table me, integer columnNumber) {
  547. try {
  548. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  549. Table_numericize_checkDefined (me, columnNumber);
  550. if (my rows.size < 1)
  551. Melder_throw (me, U": no rows.");
  552. longdouble total = 0.0;
  553. for (integer irow = 1; irow <= my rows.size; irow ++) {
  554. TableRow row = my rows.at [irow];
  555. total += row -> cells [columnNumber]. number;
  556. }
  557. if (total <= 0.0)
  558. Melder_throw (me, U": the total weight of column ", columnNumber, U" is not positive.");
  559. integer irow;
  560. do {
  561. double rand = NUMrandomUniform (0, (double) total);
  562. longdouble sum = 0.0;
  563. for (irow = 1; irow <= my rows.size; irow ++) {
  564. TableRow row = my rows.at [irow];
  565. sum += row -> cells [columnNumber]. number;
  566. if (rand <= sum)
  567. break;
  568. }
  569. } while (irow > my rows.size); // guard against rounding errors
  570. return irow;
  571. } catch (MelderError) {
  572. Melder_throw (me, U": cannot draw a row from the distribution of column ", Table_messageColumn (me, columnNumber), U".");
  573. }
  574. }
  575. autoTable Table_extractRowsWhereColumn_number (Table me, integer columnNumber, kMelder_number which, double criterion) {
  576. try {
  577. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  578. Table_numericize_Assert (me, columnNumber); // extraction should work even if cells are not defined
  579. autoTable thee = Table_create (0, my numberOfColumns);
  580. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  581. thy columnHeaders [icol]. label = Melder_dup (my columnHeaders [icol]. label.get());
  582. for (integer irow = 1; irow <= my rows.size; irow ++) {
  583. TableRow row = my rows.at [irow];
  584. if (Melder_numberMatchesCriterion (row -> cells [columnNumber]. number, which, criterion)) {
  585. autoTableRow newRow = Data_copy (row);
  586. thy rows. addItem_move (newRow.move());
  587. }
  588. }
  589. if (thy rows.size == 0)
  590. Melder_warning (U"No row matches criterion.");
  591. return thee;
  592. } catch (MelderError) {
  593. Melder_throw (me, U": rows not extracted.");
  594. }
  595. }
  596. autoTable Table_extractRowsWhereColumn_string (Table me, integer columnNumber, kMelder_string which, conststring32 criterion) {
  597. try {
  598. Table_checkSpecifiedColumnNumberWithinRange (me, columnNumber);
  599. autoTable thee = Table_create (0, my numberOfColumns);
  600. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  601. thy columnHeaders [icol]. label = Melder_dup (my columnHeaders [icol]. label.get());
  602. for (integer irow = 1; irow <= my rows.size; irow ++) {
  603. TableRow row = my rows.at [irow];
  604. if (Melder_stringMatchesCriterion (row -> cells [columnNumber]. string.get(), which, criterion, true)) {
  605. autoTableRow newRow = Data_copy (row);
  606. thy rows. addItem_move (newRow.move());
  607. }
  608. }
  609. if (thy rows.size == 0) {
  610. Melder_warning (U"No row matches criterion.");
  611. }
  612. return thee;
  613. } catch (MelderError) {
  614. Melder_throw (me, U": rows not extracted.");
  615. }
  616. }
  617. static void Table_columns_checkExist (Table me, conststring32vector columnNames) {
  618. for (integer i = 1; i <= columnNames.size; i ++) {
  619. if (Table_findColumnIndexFromColumnLabel (me, columnNames [i]) == 0)
  620. Melder_throw (me, U": column \"", columnNames [i], U"\" does not exist.");
  621. }
  622. }
  623. static void Table_columns_checkCrossSectionEmpty (conststring32vector factors, conststring32vector vars) {
  624. for (integer ifactor = 1; ifactor <= factors.size; ifactor ++) {
  625. for (integer ivar = 1; ivar <= vars.size; ivar ++) {
  626. if (str32equ (factors [ifactor], vars [ivar]))
  627. Melder_throw (U"Factor \"", factors [ifactor], U"\" is also used as dependent variable.");
  628. }
  629. }
  630. }
  631. autoTable Table_collapseRows (Table me, conststring32 factors_string, conststring32 columnsToSum_string,
  632. conststring32 columnsToAverage_string, conststring32 columnsToMedianize_string,
  633. conststring32 columnsToAverageLogarithmically_string, conststring32 columnsToMedianizeLogarithmically_string)
  634. {
  635. bool originalChanged = false;
  636. try {
  637. Melder_assert (factors_string);
  638. /*
  639. Parse the six strings of tokens.
  640. */
  641. autostring32vector factors = STRVECtokenize (factors_string);
  642. if (factors.size < 1)
  643. Melder_throw (U"In order to pool table data, you must supply at least one independent variable.");
  644. Table_columns_checkExist (me, factors.get());
  645. autostring32vector columnsToSum = STRVECtokenize (columnsToSum_string);
  646. Table_columns_checkExist (me, columnsToSum.get());
  647. Table_columns_checkCrossSectionEmpty (factors.get(), columnsToSum.get());
  648. autostring32vector columnsToAverage = STRVECtokenize (columnsToAverage_string);
  649. Table_columns_checkExist (me, columnsToAverage.get());
  650. Table_columns_checkCrossSectionEmpty (factors.get(), columnsToAverage.get());
  651. autostring32vector columnsToMedianize = STRVECtokenize (columnsToMedianize_string);
  652. Table_columns_checkExist (me, columnsToMedianize.get());
  653. Table_columns_checkCrossSectionEmpty (factors.get(), columnsToMedianize.get());
  654. autostring32vector columnsToAverageLogarithmically = STRVECtokenize (columnsToAverageLogarithmically_string);
  655. Table_columns_checkExist (me, columnsToAverageLogarithmically.get());
  656. Table_columns_checkCrossSectionEmpty (factors.get(), columnsToAverageLogarithmically.get());
  657. autostring32vector columnsToMedianizeLogarithmically = STRVECtokenize (columnsToMedianizeLogarithmically_string);
  658. Table_columns_checkExist (me, columnsToMedianizeLogarithmically.get());
  659. Table_columns_checkCrossSectionEmpty (factors.get(), columnsToMedianizeLogarithmically.get());
  660. autoTable thee = Table_createWithoutColumnNames (0,
  661. factors.size + columnsToSum.size + columnsToAverage.size + columnsToMedianize.size +
  662. columnsToAverageLogarithmically.size + columnsToMedianizeLogarithmically.size);
  663. Melder_assert (thy numberOfColumns > 0);
  664. autoVEC sortingColumn;
  665. if (columnsToMedianize.size > 0 || columnsToMedianizeLogarithmically.size > 0)
  666. sortingColumn = VECzero (my rows.size);
  667. /*
  668. Set the column names. Within the dependent variables, the same name may occur more than once.
  669. */
  670. autoINTVEC columns = INTVECzero (thy numberOfColumns);
  671. {
  672. integer icol = 0;
  673. for (integer i = 1; i <= factors.size; i ++) {
  674. Table_setColumnLabel (thee.get(), ++ icol, factors [i].get());
  675. columns [icol] = Table_findColumnIndexFromColumnLabel (me, factors [i].get());
  676. }
  677. for (integer i = 1; i <= columnsToSum.size; i ++) {
  678. Table_setColumnLabel (thee.get(), ++ icol, columnsToSum [i].get());
  679. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columnsToSum [i].get());
  680. }
  681. for (integer i = 1; i <= columnsToAverage.size; i ++) {
  682. Table_setColumnLabel (thee.get(), ++ icol, columnsToAverage [i].get());
  683. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columnsToAverage [i].get());
  684. }
  685. for (integer i = 1; i <= columnsToMedianize.size; i ++) {
  686. Table_setColumnLabel (thee.get(), ++ icol, columnsToMedianize [i].get());
  687. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columnsToMedianize [i].get());
  688. }
  689. for (integer i = 1; i <= columnsToAverageLogarithmically.size; i ++) {
  690. Table_setColumnLabel (thee.get(), ++ icol, columnsToAverageLogarithmically [i].get());
  691. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columnsToAverageLogarithmically [i].get());
  692. }
  693. for (integer i = 1; i <= columnsToMedianizeLogarithmically.size; i ++) {
  694. Table_setColumnLabel (thee.get(), ++ icol, columnsToMedianizeLogarithmically [i].get());
  695. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columnsToMedianizeLogarithmically [i].get());
  696. }
  697. Melder_assert (icol == thy numberOfColumns);
  698. }
  699. /*
  700. Make sure that all the columns in the original table that we will use in the pooled table are defined.
  701. */
  702. for (integer icol = 1; icol <= thy numberOfColumns; icol ++) {
  703. Table_numericize_checkDefined (me, columns [icol]);
  704. }
  705. /*
  706. Remember the present sorting of the original table.
  707. (This is safe: the sorting index may change only vacuously when numericizing.)
  708. But this cannot be done before the previous block!
  709. */
  710. for (integer irow = 1; irow <= my rows.size; irow ++) {
  711. TableRow row = my rows.at [irow];
  712. row -> sortingIndex = irow;
  713. }
  714. /*
  715. We will now sort the original table temporarily, by the factors (independent variables) only.
  716. */
  717. Table_sortRows_Assert (me, constINTVEC (columns.at, factors.size)); /* This works only because the factors come first. */
  718. originalChanged = true;
  719. /*
  720. Find stretches of identical factors.
  721. */
  722. for (integer irow = 1; irow <= my rows.size; irow ++) {
  723. integer rowmin = irow, rowmax = irow;
  724. for (;;) {
  725. bool identical = true;
  726. if (++ rowmax > my rows.size)
  727. break;
  728. for (integer icol = 1; icol <= factors.size; icol ++) {
  729. if (my rows.at [rowmax] -> cells [columns [icol]]. number !=
  730. my rows.at [rowmin] -> cells [columns [icol]]. number)
  731. {
  732. identical = false;
  733. break;
  734. }
  735. }
  736. if (! identical)
  737. break;
  738. }
  739. rowmax --;
  740. /*
  741. We have the stretch.
  742. */
  743. Table_insertRow (thee.get(), thy rows.size + 1);
  744. {// scope
  745. integer icol = 0;
  746. for (integer i = 1; i <= factors.size; i ++) {
  747. ++ icol;
  748. Table_setStringValue (thee.get(), thy rows.size, icol,
  749. my rows.at [rowmin] -> cells [columns [icol]]. string.get());
  750. }
  751. for (integer i = 1; i <= columnsToSum.size; i ++) {
  752. ++ icol;
  753. longdouble sum = 0.0;
  754. for (integer jrow = rowmin; jrow <= rowmax; jrow ++)
  755. sum += my rows.at [jrow] -> cells [columns [icol]]. number;
  756. Table_setNumericValue (thee.get(), thy rows.size, icol, (double) sum);
  757. }
  758. for (integer i = 1; i <= columnsToAverage.size; i ++) {
  759. ++ icol;
  760. longdouble sum = 0.0;
  761. for (integer jrow = rowmin; jrow <= rowmax; jrow ++)
  762. sum += my rows.at [jrow] -> cells [columns [icol]]. number;
  763. Table_setNumericValue (thee.get(), thy rows.size, icol, (double) sum / (rowmax - rowmin + 1));
  764. }
  765. for (integer i = 1; i <= columnsToMedianize.size; i ++) {
  766. ++ icol;
  767. for (integer jrow = rowmin; jrow <= rowmax; jrow ++)
  768. sortingColumn [jrow] = my rows.at [jrow] -> cells [columns [icol]]. number;
  769. VEC part = sortingColumn.subview (rowmin, rowmax);
  770. VECsort_inplace (part);
  771. double median = NUMquantile (part, 0.5);
  772. Table_setNumericValue (thee.get(), thy rows.size, icol, median);
  773. }
  774. for (integer i = 1; i <= columnsToAverageLogarithmically.size; i ++) {
  775. ++ icol;
  776. longdouble sum = 0.0;
  777. for (integer jrow = rowmin; jrow <= rowmax; jrow ++) {
  778. double value = my rows.at [jrow] -> cells [columns [icol]]. number;
  779. if (value <= 0.0) {
  780. Melder_throw (
  781. U"The cell in column \"", columnsToAverageLogarithmically [i].get(),
  782. U"\" of row ", jrow, U" of ", me,
  783. U" is not positive.\nCannot average logarithmically."
  784. );
  785. }
  786. sum += log (value);
  787. }
  788. Table_setNumericValue (thee.get(), thy rows.size, icol, exp (double (sum / (rowmax - rowmin + 1))));
  789. }
  790. for (integer i = 1; i <= columnsToMedianizeLogarithmically.size; i ++) {
  791. ++ icol;
  792. for (integer jrow = rowmin; jrow <= rowmax; jrow ++) {
  793. double value = my rows.at [jrow] -> cells [columns [icol]]. number;
  794. if (value <= 0.0) {
  795. Melder_throw (
  796. U"The cell in column \"", columnsToMedianizeLogarithmically [i].get(),
  797. U"\" of row ", jrow, U" of ", me,
  798. U" is not positive.\nCannot medianize logarithmically."
  799. );
  800. }
  801. sortingColumn [jrow] = log (value);
  802. }
  803. VEC part = sortingColumn.subview (rowmin, rowmax);
  804. VECsort_inplace (part);
  805. double median = NUMquantile (part, 0.5);
  806. Table_setNumericValue (thee.get(), thy rows.size, icol, exp (median));
  807. }
  808. Melder_assert (icol == thy numberOfColumns);
  809. }
  810. irow = rowmax;
  811. }
  812. if (originalChanged)
  813. sortRowsByIndex_NoError (me); // unsort the original table
  814. return thee;
  815. } catch (MelderError) {
  816. if (originalChanged)
  817. sortRowsByIndex_NoError (me); // unsort the original table // UGLY
  818. throw;
  819. }
  820. }
  821. static autostring32vector Table_getLevels_ (Table me, integer column) {
  822. try {
  823. for (integer irow = 1; irow <= my rows.size; irow ++) {
  824. TableRow row = my rows.at [irow];
  825. row -> sortingIndex = irow;
  826. }
  827. integer columns [2] = { 0, column };
  828. Table_sortRows_Assert (me, constINTVEC (columns, 1));
  829. integer numberOfLevels = 0;
  830. integer irow = 1;
  831. while (irow <= my rows.size) {
  832. double value = my rows.at [irow] -> cells [column]. number;
  833. numberOfLevels ++;
  834. while (++ irow <= my rows.size && my rows.at [irow] -> cells [column]. number == value) { }
  835. }
  836. autostring32vector result (numberOfLevels);
  837. numberOfLevels = 0;
  838. irow = 1;
  839. while (irow <= my rows.size) {
  840. double value = my rows.at [irow] -> cells [column]. number;
  841. result [++ numberOfLevels] = Melder_dup (Table_getStringValue_Assert (me, irow, column));
  842. while (++ irow <= my rows.size && my rows.at [irow] -> cells [column]. number == value) { }
  843. }
  844. sortRowsByIndex_NoError (me); // unsort the original table
  845. return result;
  846. } catch (MelderError) {
  847. sortRowsByIndex_NoError (me); // unsort the original table // UGLY
  848. throw;
  849. }
  850. }
  851. autoTable Table_rowsToColumns (Table me, conststring32 factors_string, integer columnToTranspose, conststring32 columnsToExpand_string) {
  852. bool originalChanged = false;
  853. try {
  854. Melder_assert (factors_string);
  855. bool warned = false;
  856. /*
  857. Parse the two strings of tokens.
  858. */
  859. autostring32vector factors_names = STRVECtokenize (factors_string);
  860. const integer numberOfFactors = factors_names.size;
  861. if (numberOfFactors < 1)
  862. Melder_throw (U"In order to nest table data, you should supply at least one independent variable.");
  863. Table_columns_checkExist (me, factors_names.get());
  864. autostring32vector columnsToExpand_names = STRVECtokenize (columnsToExpand_string);
  865. const integer numberToExpand = columnsToExpand_names.size;
  866. if (numberToExpand < 1)
  867. Melder_throw (U"In order to nest table data, you should supply at least one dependent variable (to expand).");
  868. Table_columns_checkExist (me, columnsToExpand_names.get());
  869. Table_columns_checkCrossSectionEmpty (factors_names.get(), columnsToExpand_names.get());
  870. autostring32vector levels_names = Table_getLevels_ (me, columnToTranspose);
  871. const integer numberOfLevels = levels_names.size;
  872. /*
  873. Get the column numbers for the factors.
  874. */
  875. autoINTVEC factorColumns = INTVECzero (numberOfFactors);
  876. for (integer ifactor = 1; ifactor <= numberOfFactors; ifactor ++) {
  877. factorColumns [ifactor] = Table_findColumnIndexFromColumnLabel (me, factors_names [ifactor].get());
  878. /*
  879. Make sure that all the columns in the original table that we will use in the nested table are defined.
  880. */
  881. Table_numericize_checkDefined (me, factorColumns [ifactor]);
  882. }
  883. /*
  884. Get the column numbers for the expandable variables.
  885. */
  886. autoINTVEC columnsToExpand = INTVECzero (numberToExpand);
  887. for (integer iexpand = 1; iexpand <= numberToExpand; iexpand ++) {
  888. columnsToExpand [iexpand] = Table_findColumnIndexFromColumnLabel (me, columnsToExpand_names [iexpand].get());
  889. Table_numericize_checkDefined (me, columnsToExpand [iexpand]);
  890. }
  891. /*
  892. Create the new table, with column names.
  893. */
  894. autoTable thee = Table_createWithoutColumnNames (0, numberOfFactors + (numberOfLevels * numberToExpand));
  895. Melder_assert (thy numberOfColumns > 0);
  896. for (integer ifactor = 1; ifactor <= numberOfFactors; ifactor ++)
  897. Table_setColumnLabel (thee.get(), ifactor, factors_names [ifactor].get());
  898. for (integer iexpand = 1; iexpand <= numberToExpand; iexpand ++) {
  899. for (integer ilevel = 1; ilevel <= numberOfLevels; ilevel ++) {
  900. //Melder_casual (U"Number of factors: ", numberOfFactors);
  901. //Melder_casual (U"Level: ", ilevel, U" out of ", numberOfLevels);
  902. integer columnNumber = numberOfFactors + (iexpand - 1) * numberOfLevels + ilevel;
  903. //Melder_casual (U"Column number: ", columnNumber);
  904. Table_setColumnLabel (thee.get(), columnNumber,
  905. Melder_cat (columnsToExpand_names [iexpand].get(), U".", levels_names [ilevel].get()));
  906. }
  907. }
  908. /*
  909. Remember the present sorting of the original table.
  910. (This is safe: the sorting index may change only vacuously when numericizing.)
  911. But this cannot be done before the previous blocks that numericize!
  912. */
  913. for (integer irow = 1; irow <= my rows.size; irow ++) {
  914. TableRow row = my rows.at [irow];
  915. row -> sortingIndex = irow;
  916. }
  917. /*
  918. We will now sort the original table temporarily, by the factors (independent variables) only.
  919. */
  920. Table_sortRows_Assert (me, factorColumns.get());
  921. originalChanged = true;
  922. /*
  923. Find stretches of identical factors.
  924. */
  925. for (integer irow = 1; irow <= my rows.size; irow ++) {
  926. integer rowmin = irow, rowmax = irow;
  927. for (;;) {
  928. bool identical = true;
  929. if (++ rowmax > my rows.size) break;
  930. for (integer ifactor = 1; ifactor <= numberOfFactors; ifactor ++) {
  931. if (my rows.at [rowmax] -> cells [factorColumns [ifactor]]. number !=
  932. my rows.at [rowmin] -> cells [factorColumns [ifactor]]. number)
  933. {
  934. identical = false;
  935. break;
  936. }
  937. }
  938. if (! identical) break;
  939. }
  940. #if 0
  941. if (rowmax - rowmin > numberOfLevels && ! warned) {
  942. Melder_warning (U"Some rows of the original table have not been included in the new table. "
  943. U"You could perhaps add more factors.");
  944. warned = true;
  945. }
  946. #endif
  947. rowmax --;
  948. /*
  949. We have the stretch.
  950. */
  951. Table_insertRow (thee.get(), thy rows.size + 1);
  952. TableRow thyRow = thy rows.at [thy rows.size];
  953. for (integer ifactor = 1; ifactor <= numberOfFactors; ifactor ++) {
  954. Table_setStringValue (thee.get(), thy rows.size, ifactor,
  955. my rows.at [rowmin] -> cells [factorColumns [ifactor]]. string.get());
  956. }
  957. for (integer iexpand = 1; iexpand <= numberToExpand; iexpand ++) {
  958. for (integer jrow = rowmin; jrow <= rowmax; jrow ++) {
  959. TableRow myRow = my rows.at [jrow];
  960. const double value = myRow -> cells [columnsToExpand [iexpand]]. number;
  961. const integer level = Melder_iround (myRow -> cells [columnToTranspose]. number);
  962. const integer thyColumn = numberOfFactors + (iexpand - 1) * numberOfLevels + level;
  963. if (thyRow -> cells [thyColumn]. string && ! warned) {
  964. Melder_warning (U"Some information from the original table has not been included in the new table. "
  965. U"You could perhaps add more factors.");
  966. warned = true;
  967. }
  968. Table_setNumericValue (thee.get(), thy rows.size, thyColumn, value);
  969. }
  970. }
  971. irow = rowmax;
  972. }
  973. if (originalChanged) sortRowsByIndex_NoError (me); // unsort the original table
  974. return thee;
  975. } catch (MelderError) {
  976. if (originalChanged) sortRowsByIndex_NoError (me); // unsort the original table // UGLY
  977. throw;
  978. }
  979. }
  980. autoTable Table_transpose (Table me) {
  981. try {
  982. autoTable thee = Table_createWithoutColumnNames (my numberOfColumns, 1 + my rows.size);
  983. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  984. Table_setStringValue (thee.get(), icol, 1, my columnHeaders [icol]. label.get());
  985. for (integer irow = 1; irow <= my rows.size; irow ++) {
  986. for (integer icol = 1; icol <= my numberOfColumns; icol ++)
  987. Table_setStringValue (thee.get(), icol, 1 + irow, Table_getStringValue_Assert (me, irow, icol));
  988. }
  989. return thee;
  990. } catch (MelderError) {
  991. Melder_throw (me, U": not transposed.");
  992. }
  993. }
  994. static constINTVEC *cellCompare_columns;
  995. static int cellCompare (const void *first, const void *second) {
  996. TableRow me = * (TableRow *) first, thee = * (TableRow *) second;
  997. integer ncol = cellCompare_columns->size;
  998. for (integer icol = 1; icol <= ncol; icol ++) {
  999. integer cellNumber = cellCompare_columns->at [icol];
  1000. if (my cells [cellNumber]. number < thy cells [cellNumber]. number)
  1001. return -1;
  1002. if (my cells [cellNumber]. number > thy cells [cellNumber]. number)
  1003. return +1;
  1004. }
  1005. return 0;
  1006. }
  1007. void Table_sortRows_Assert (Table me, constINTVEC columns) {
  1008. for (integer icol = 1; icol <= columns.size; icol ++)
  1009. Table_numericize_Assert (me, columns [icol]);
  1010. cellCompare_columns = & columns;
  1011. qsort (& my rows.at [1], (unsigned long) my rows.size, sizeof (TableRow), cellCompare);
  1012. }
  1013. void Table_sortRows_string (Table me, conststring32 columns_string) {
  1014. try {
  1015. autoSTRVEC columns_tokens = STRVECtokenize (columns_string);
  1016. integer numberOfColumns = columns_tokens.size;
  1017. if (numberOfColumns < 1)
  1018. Melder_throw (me, U": you specified an empty list of columns.");
  1019. autoINTVEC columns = INTVECraw (numberOfColumns);
  1020. for (integer icol = 1; icol <= numberOfColumns; icol ++) {
  1021. columns [icol] = Table_findColumnIndexFromColumnLabel (me, columns_tokens [icol].get());
  1022. if (columns [icol] == 0)
  1023. Melder_throw (U"Column \"", columns_tokens [icol].get(), U"\" does not exist.");
  1024. }
  1025. Table_sortRows_Assert (me, columns.get());
  1026. } catch (MelderError) {
  1027. Melder_throw (me, U": rows not sorted.");
  1028. }
  1029. }
  1030. void Table_randomizeRows (Table me) noexcept {
  1031. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1032. integer jrow = NUMrandomInteger (irow, my rows.size);
  1033. TableRow tmp = my rows.at [irow];
  1034. my rows.at [irow] = my rows.at [jrow];
  1035. my rows.at [jrow] = tmp;
  1036. }
  1037. }
  1038. void Table_reflectRows (Table me) noexcept {
  1039. for (integer irow = 1; irow <= my rows.size / 2; irow ++) {
  1040. integer jrow = my rows.size + 1 - irow;
  1041. TableRow tmp = my rows.at [irow];
  1042. my rows.at [irow] = my rows.at [jrow];
  1043. my rows.at [jrow] = tmp;
  1044. }
  1045. }
  1046. autoTable Tables_append (OrderedOf<structTable>* me) {
  1047. try {
  1048. if (my size == 0)
  1049. Melder_throw (U"Cannot add zero tables.");
  1050. Table thee = my at [1];
  1051. integer nrow = thy rows.size;
  1052. integer ncol = thy numberOfColumns;
  1053. Table firstTable = thee;
  1054. for (integer itab = 2; itab <= my size; itab ++) {
  1055. thee = my at [itab];
  1056. nrow += thy rows.size;
  1057. if (thy numberOfColumns != ncol)
  1058. Melder_throw (U"Numbers of columns do not match.");
  1059. for (integer icol = 1; icol <= ncol; icol ++) {
  1060. if (! Melder_equ (thy columnHeaders [icol]. label.get(), firstTable -> columnHeaders [icol]. label.get())) {
  1061. Melder_throw (U"The label of column ", icol, U" of ", thee,
  1062. U" (", thy columnHeaders [icol]. label.get(), U") does not match the label of column ", icol,
  1063. U" of ", firstTable, U" (", firstTable -> columnHeaders [icol]. label.get(), U")."
  1064. );
  1065. }
  1066. }
  1067. }
  1068. autoTable him = Table_createWithoutColumnNames (nrow, ncol);
  1069. for (integer icol = 1; icol <= ncol; icol ++)
  1070. Table_setColumnLabel (him.get(), icol, thy columnHeaders [icol]. label.get());
  1071. nrow = 0;
  1072. for (integer itab = 1; itab <= my size; itab ++) {
  1073. thee = my at [itab];
  1074. for (integer irow = 1; irow <= thy rows.size; irow ++) {
  1075. nrow ++;
  1076. for (integer icol = 1; icol <= ncol; icol ++)
  1077. Table_setStringValue (him.get(), nrow, icol, Table_getStringValue_Assert (thee, irow, icol));
  1078. }
  1079. }
  1080. return him;
  1081. } catch (MelderError) {
  1082. Melder_throw (U"Table objects not appended.");
  1083. }
  1084. }
  1085. void Table_appendSumColumn (Table me, integer column1, integer column2, conststring32 label) { // safe
  1086. try {
  1087. /*
  1088. Check without change.
  1089. */
  1090. Table_checkSpecifiedColumnNumberWithinRange (me, column1);
  1091. Table_checkSpecifiedColumnNumberWithinRange (me, column2);
  1092. Table_numericize_checkDefined (me, column1);
  1093. Table_numericize_checkDefined (me, column2);
  1094. autoTable thee = Table_createWithoutColumnNames (my rows.size, 1);
  1095. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1096. TableRow myRow = my rows.at [irow];
  1097. Table_setNumericValue (thee.get(), irow, 1, myRow -> cells [column1]. number + myRow -> cells [column2]. number);
  1098. }
  1099. /*
  1100. Safe change.
  1101. */
  1102. Table_appendColumn (me, label);
  1103. /*
  1104. Change without error.
  1105. */
  1106. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1107. TableRow myRow = my rows.at [irow];
  1108. TableRow thyRow = thy rows.at [irow];
  1109. TableCell myCell = & myRow -> cells [my numberOfColumns];
  1110. TableCell thyCell = & thyRow -> cells [1];
  1111. myCell -> string = thyCell -> string. move();
  1112. }
  1113. } catch (MelderError) {
  1114. Melder_throw (me, U": sum column not appended.");
  1115. }
  1116. }
  1117. void Table_appendDifferenceColumn (Table me, integer column1, integer column2, conststring32 label) { // safe
  1118. try {
  1119. /*
  1120. Check without change.
  1121. */
  1122. Table_checkSpecifiedColumnNumberWithinRange (me, column1);
  1123. Table_checkSpecifiedColumnNumberWithinRange (me, column2);
  1124. Table_numericize_checkDefined (me, column1);
  1125. Table_numericize_checkDefined (me, column2);
  1126. autoTable thee = Table_createWithoutColumnNames (my rows.size, 1);
  1127. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1128. TableRow myRow = my rows.at [irow];
  1129. Table_setNumericValue (thee.get(), irow, 1, myRow -> cells [column1]. number - myRow -> cells [column2]. number);
  1130. }
  1131. /*
  1132. Safe change.
  1133. */
  1134. Table_appendColumn (me, label);
  1135. /*
  1136. Change without error.
  1137. */
  1138. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1139. TableRow myRow = my rows.at [irow];
  1140. TableRow thyRow = thy rows.at [irow];
  1141. TableCell myCell = & myRow -> cells [my numberOfColumns];
  1142. TableCell thyCell = & thyRow -> cells [1];
  1143. myCell -> string = thyCell -> string. move();
  1144. }
  1145. } catch (MelderError) {
  1146. Melder_throw (me, U": difference column not appended.");
  1147. }
  1148. }
  1149. void Table_appendProductColumn (Table me, integer column1, integer column2, conststring32 label) { // safe
  1150. try {
  1151. /*
  1152. Check without change.
  1153. */
  1154. Table_checkSpecifiedColumnNumberWithinRange (me, column1);
  1155. Table_checkSpecifiedColumnNumberWithinRange (me, column2);
  1156. Table_numericize_checkDefined (me, column1);
  1157. Table_numericize_checkDefined (me, column2);
  1158. autoTable thee = Table_createWithoutColumnNames (my rows.size, 1);
  1159. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1160. TableRow myRow = my rows.at [irow];
  1161. Table_setNumericValue (thee.get(), irow, 1, myRow -> cells [column1]. number * myRow -> cells [column2]. number);
  1162. }
  1163. /*
  1164. Safe change.
  1165. */
  1166. Table_appendColumn (me, label);
  1167. /*
  1168. Change without error.
  1169. */
  1170. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1171. TableRow myRow = my rows.at [irow];
  1172. TableRow thyRow = thy rows.at [irow];
  1173. TableCell myCell = & myRow -> cells [my numberOfColumns];
  1174. TableCell thyCell = & thyRow -> cells [1];
  1175. myCell -> string = thyCell -> string. move();
  1176. }
  1177. } catch (MelderError) {
  1178. Melder_throw (me, U": product column not appended.");
  1179. }
  1180. }
  1181. void Table_appendQuotientColumn (Table me, integer column1, integer column2, conststring32 label) { // safe
  1182. try {
  1183. /*
  1184. Check without change.
  1185. */
  1186. Table_checkSpecifiedColumnNumberWithinRange (me, column1);
  1187. Table_checkSpecifiedColumnNumberWithinRange (me, column2);
  1188. Table_numericize_checkDefined (me, column1);
  1189. Table_numericize_checkDefined (me, column2);
  1190. autoTable thee = Table_createWithoutColumnNames (my rows.size, 1);
  1191. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1192. TableRow myRow = my rows.at [irow];
  1193. double value = myRow -> cells [column2]. number == 0.0 ? undefined :
  1194. myRow -> cells [column1]. number / myRow -> cells [column2]. number;
  1195. Table_setNumericValue (thee.get(), irow, 1, value);
  1196. }
  1197. /*
  1198. Safe change.
  1199. */
  1200. Table_appendColumn (me, label);
  1201. /*
  1202. Change without error.
  1203. */
  1204. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1205. TableRow myRow = my rows.at [irow];
  1206. TableRow thyRow = thy rows.at [irow];
  1207. TableCell myCell = & myRow -> cells [my numberOfColumns];
  1208. TableCell thyCell = & thyRow -> cells [1];
  1209. myCell -> string = thyCell -> string. move();
  1210. }
  1211. } catch (MelderError) {
  1212. Melder_throw (me, U": quotient column not appended.");
  1213. }
  1214. }
  1215. void Table_formula_columnRange (Table me, integer fromColumn, integer toColumn, conststring32 expression, Interpreter interpreter) {
  1216. try {
  1217. Table_checkSpecifiedColumnNumberWithinRange (me, fromColumn);
  1218. Table_checkSpecifiedColumnNumberWithinRange (me, toColumn);
  1219. Formula_compile (interpreter, me, expression, kFormula_EXPRESSION_TYPE_UNKNOWN, true);
  1220. Formula_Result result;
  1221. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1222. for (integer icol = fromColumn; icol <= toColumn; icol ++) {
  1223. Formula_run (irow, icol, & result);
  1224. if (result. expressionType == kFormula_EXPRESSION_TYPE_STRING) {
  1225. Table_setStringValue (me, irow, icol, result. stringResult.get());
  1226. } else if (result. expressionType == kFormula_EXPRESSION_TYPE_NUMERIC) {
  1227. Table_setNumericValue (me, irow, icol, result. numericResult);
  1228. } else if (result. expressionType == kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR) {
  1229. Melder_throw (me, U": cannot put vectors into cells.");
  1230. } else if (result. expressionType == kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX) {
  1231. Melder_throw (me, U": cannot put matrices into cells.");
  1232. } else if (result. expressionType == kFormula_EXPRESSION_TYPE_STRING_ARRAY) {
  1233. Melder_throw (me, U": cannot put string arrays into cells.");
  1234. }
  1235. }
  1236. }
  1237. } catch (MelderError) {
  1238. Melder_throw (me, U": application of formula not completed.");
  1239. }
  1240. }
  1241. void Table_formula (Table me, integer icol, conststring32 expression, Interpreter interpreter) {
  1242. Table_formula_columnRange (me, icol, icol, expression, interpreter);
  1243. }
  1244. double Table_getCorrelation_pearsonR (Table me, integer column1, integer column2, double significanceLevel,
  1245. double *out_significance, double *out_lowerLimit, double *out_upperLimit)
  1246. {
  1247. integer n = my rows.size;
  1248. double correlation;
  1249. longdouble sum1 = 0.0, sum2 = 0.0, sum12 = 0.0, sum11 = 0.0, sum22 = 0.0;
  1250. if (out_significance) *out_significance = undefined;
  1251. if (out_lowerLimit) *out_lowerLimit = undefined;
  1252. if (out_upperLimit) *out_upperLimit = undefined;
  1253. if (column1 < 1 || column1 > my numberOfColumns) return undefined;
  1254. if (column2 < 1 || column2 > my numberOfColumns) return undefined;
  1255. if (n < 2) return undefined;
  1256. Table_numericize_Assert (me, column1);
  1257. Table_numericize_Assert (me, column2);
  1258. for (integer irow = 1; irow <= n; irow ++) {
  1259. TableRow row = my rows.at [irow];
  1260. sum1 += row -> cells [column1]. number;
  1261. sum2 += row -> cells [column2]. number;
  1262. }
  1263. double mean1 = (double) sum1 / n;
  1264. double mean2 = (double) sum2 / n;
  1265. for (integer irow = 1; irow <= n; irow ++) {
  1266. TableRow row = my rows.at [irow];
  1267. double d1 = row -> cells [column1]. number - mean1, d2 = row -> cells [column2]. number - mean2;
  1268. sum12 += d1 * d2;
  1269. sum11 += d1 * d1;
  1270. sum22 += d2 * d2;
  1271. }
  1272. correlation = sum11 == 0.0 || sum22 == 0.0 ? undefined : (double) sum12 / sqrt ((double) sum11 * (double) sum22);
  1273. if (out_significance && isdefined (correlation) && n >= 3)
  1274. *out_significance = fabs (correlation) == 1.0 ? 0.0 :
  1275. /* One-sided: */
  1276. NUMstudentQ (fabs (correlation) * sqrt ((n - 2) / (1 - correlation * correlation)), n - 2);
  1277. if ((out_lowerLimit || out_upperLimit) && isdefined (correlation) && n >= 4) {
  1278. if (fabs (correlation) == 1.0) {
  1279. if (out_lowerLimit)
  1280. *out_lowerLimit = correlation;
  1281. if (out_upperLimit)
  1282. *out_upperLimit = correlation;
  1283. } else {
  1284. double z = 0.5 * log ((1.0 + correlation) / (1.0 - correlation));
  1285. double dz = NUMinvGaussQ (significanceLevel) / sqrt (n - 3);
  1286. if (out_lowerLimit)
  1287. *out_lowerLimit = tanh (z - dz);
  1288. if (out_upperLimit)
  1289. *out_upperLimit = tanh (z + dz);
  1290. }
  1291. }
  1292. return correlation;
  1293. }
  1294. double Table_getCorrelation_kendallTau (Table me, integer column1, integer column2, double significanceLevel,
  1295. double *out_significance, double *out_lowerLimit, double *out_upperLimit)
  1296. {
  1297. integer n = my rows.size;
  1298. double correlation, denominator;
  1299. integer numberOfConcordants = 0, numberOfDiscordants = 0, numberOfExtra1 = 0, numberOfExtra2 = 0;
  1300. if (out_significance) *out_significance = undefined;
  1301. if (out_lowerLimit) *out_lowerLimit = undefined;
  1302. if (out_upperLimit) *out_upperLimit = undefined;
  1303. if (column1 < 1 || column1 > my numberOfColumns) return undefined;
  1304. if (column2 < 1 || column2 > my numberOfColumns) return undefined;
  1305. Table_numericize_Assert (me, column1);
  1306. Table_numericize_Assert (me, column2);
  1307. for (integer irow = 1; irow < n; irow ++) {
  1308. TableRow rowi = my rows.at [irow];
  1309. for (integer jrow = irow + 1; jrow <= n; jrow ++) {
  1310. TableRow rowj = my rows.at [jrow];
  1311. double diff1 = rowi -> cells [column1]. number - rowj -> cells [column1]. number;
  1312. double diff2 = rowi -> cells [column2]. number - rowj -> cells [column2]. number;
  1313. double concord = diff1 * diff2;
  1314. if (concord > 0.0) {
  1315. numberOfConcordants ++;
  1316. } else if (concord < 0.0) {
  1317. numberOfDiscordants ++;
  1318. } else if (diff1 != 0.0) {
  1319. numberOfExtra1 ++;
  1320. } else {
  1321. numberOfExtra2 ++;
  1322. }
  1323. }
  1324. }
  1325. denominator = sqrt ((numberOfConcordants + numberOfDiscordants + numberOfExtra1) *
  1326. (numberOfConcordants + numberOfDiscordants + numberOfExtra2));
  1327. correlation = denominator == 0.0 ? undefined : (numberOfConcordants - numberOfDiscordants) / denominator;
  1328. if ((out_significance || out_lowerLimit || out_upperLimit) && isdefined (correlation) && n >= 2) {
  1329. double standardError = sqrt ((4 * n + 10.0) / (9 * n * (n - 1)));
  1330. if (out_significance)
  1331. *out_significance = NUMgaussQ (fabs (correlation) / standardError); // one-sided
  1332. if (out_lowerLimit)
  1333. *out_lowerLimit = correlation - NUMinvGaussQ (significanceLevel) * standardError;
  1334. if (out_upperLimit)
  1335. *out_upperLimit = correlation + NUMinvGaussQ (significanceLevel) * standardError;
  1336. }
  1337. return correlation;
  1338. }
  1339. double Table_getDifference_studentT (Table me, integer column1, integer column2, double significanceLevel,
  1340. double *out_t, double *out_numberOfDegreesOfFreedom, double *out_significance, double *out_lowerLimit, double *out_upperLimit)
  1341. {
  1342. if (out_t) *out_t = undefined;
  1343. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = undefined;
  1344. if (out_significance) *out_significance = undefined;
  1345. if (out_lowerLimit) *out_lowerLimit = undefined;
  1346. if (out_upperLimit) *out_upperLimit = undefined;
  1347. integer n = my rows.size;
  1348. if (n < 1) return undefined;
  1349. if (column1 < 1 || column1 > my numberOfColumns) return undefined;
  1350. if (column2 < 1 || column2 > my numberOfColumns) return undefined;
  1351. Table_numericize_Assert (me, column1);
  1352. Table_numericize_Assert (me, column2);
  1353. longdouble sum = 0.0;
  1354. for (integer irow = 1; irow <= n; irow ++) {
  1355. TableRow row = my rows.at [irow];
  1356. sum += row -> cells [column1]. number - row -> cells [column2]. number;
  1357. }
  1358. double meanDifference = (double) sum / n;
  1359. integer degreesOfFreedom = n - 1;
  1360. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = degreesOfFreedom;
  1361. if (degreesOfFreedom >= 1 && (out_t || out_significance || out_lowerLimit || out_upperLimit)) {
  1362. longdouble sumOfSquares = 0.0;
  1363. for (integer irow = 1; irow <= n; irow ++) {
  1364. TableRow row = my rows.at [irow];
  1365. double diff = (row -> cells [column1]. number - row -> cells [column2]. number) - meanDifference;
  1366. sumOfSquares += diff * diff;
  1367. }
  1368. double standardError = sqrt ((double) sumOfSquares / degreesOfFreedom / n);
  1369. if (out_t && standardError != 0.0) *out_t = meanDifference / standardError;
  1370. if (out_significance) *out_significance =
  1371. standardError == 0.0 ? 0.0 : NUMstudentQ (fabs (meanDifference) / standardError, degreesOfFreedom);
  1372. if (out_lowerLimit) *out_lowerLimit =
  1373. meanDifference - standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1374. if (out_upperLimit) *out_upperLimit =
  1375. meanDifference + standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1376. }
  1377. return meanDifference;
  1378. }
  1379. double Table_getMean_studentT (Table me, integer column, double significanceLevel,
  1380. double *out_tFromZero, double *out_numberOfDegreesOfFreedom, double *out_significanceFromZero, double *out_lowerLimit, double *out_upperLimit)
  1381. {
  1382. integer n = my rows.size;
  1383. if (out_tFromZero) *out_tFromZero = undefined;
  1384. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = undefined;
  1385. if (out_significanceFromZero) *out_significanceFromZero = undefined;
  1386. if (out_lowerLimit) *out_lowerLimit = undefined;
  1387. if (out_upperLimit) *out_upperLimit = undefined;
  1388. if (n < 1) return undefined;
  1389. if (column < 1 || column > my numberOfColumns) return undefined;
  1390. integer degreesOfFreedom = n - 1;
  1391. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = degreesOfFreedom;
  1392. Table_numericize_Assert (me, column);
  1393. longdouble sum = 0.0;
  1394. for (integer irow = 1; irow <= n; irow ++) {
  1395. TableRow row = my rows.at [irow];
  1396. sum += row -> cells [column]. number;
  1397. }
  1398. double mean = double (sum / n);
  1399. if (n >= 2 && (out_tFromZero || out_significanceFromZero || out_lowerLimit || out_upperLimit)) {
  1400. longdouble sumOfSquares = 0.0;
  1401. for (integer irow = 1; irow <= n; irow ++) {
  1402. TableRow row = my rows.at [irow];
  1403. double diff = row -> cells [column]. number - mean;
  1404. sumOfSquares += diff * diff;
  1405. }
  1406. double standardError = sqrt ((double) sumOfSquares / degreesOfFreedom / n);
  1407. if (out_tFromZero && standardError != 0.0) *out_tFromZero = mean / standardError;
  1408. if (out_significanceFromZero) *out_significanceFromZero =
  1409. standardError == 0.0 ? 0.0 : NUMstudentQ (fabs (mean) / standardError, degreesOfFreedom);
  1410. if (out_lowerLimit) *out_lowerLimit =
  1411. mean - standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1412. if (out_upperLimit) *out_upperLimit =
  1413. mean + standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1414. }
  1415. return mean;
  1416. }
  1417. double Table_getGroupMean_studentT (Table me, integer column, integer groupColumn, conststring32 group, double significanceLevel,
  1418. double *out_tFromZero, double *out_numberOfDegreesOfFreedom, double *out_significanceFromZero, double *out_lowerLimit, double *out_upperLimit)
  1419. {
  1420. if (out_tFromZero) *out_tFromZero = undefined;
  1421. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = undefined;
  1422. if (out_significanceFromZero) *out_significanceFromZero = undefined;
  1423. if (out_lowerLimit) *out_lowerLimit = undefined;
  1424. if (out_upperLimit) *out_upperLimit = undefined;
  1425. if (column < 1 || column > my numberOfColumns) return undefined;
  1426. Table_numericize_Assert (me, column);
  1427. integer n = 0;
  1428. longdouble sum = 0.0;
  1429. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1430. TableRow row = my rows.at [irow];
  1431. if (row -> cells [groupColumn]. string) {
  1432. if (str32equ (row -> cells [groupColumn]. string.get(), group)) {
  1433. n += 1;
  1434. sum += row -> cells [column]. number;
  1435. }
  1436. }
  1437. }
  1438. if (n < 1) return undefined;
  1439. double mean = (double) sum / n;
  1440. integer degreesOfFreedom = n - 1;
  1441. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = degreesOfFreedom;
  1442. if (degreesOfFreedom >= 1 && (out_tFromZero || out_significanceFromZero || out_lowerLimit || out_upperLimit)) {
  1443. longdouble sumOfSquares = 0.0;
  1444. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1445. TableRow row = my rows.at [irow];
  1446. if (row -> cells [groupColumn]. string) {
  1447. if (str32equ (row -> cells [groupColumn]. string.get(), group)) {
  1448. double diff = row -> cells [column]. number - mean;
  1449. sumOfSquares += diff * diff;
  1450. }
  1451. }
  1452. }
  1453. double standardError = sqrt ((double) sumOfSquares / degreesOfFreedom / n);
  1454. if (out_tFromZero && standardError != 0.0) *out_tFromZero = mean / standardError;
  1455. if (out_significanceFromZero) *out_significanceFromZero =
  1456. standardError == 0.0 ? 0.0 : NUMstudentQ (fabs (mean) / standardError, degreesOfFreedom);
  1457. if (out_lowerLimit) *out_lowerLimit =
  1458. mean - standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1459. if (out_upperLimit) *out_upperLimit =
  1460. mean + standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1461. }
  1462. return mean;
  1463. }
  1464. double Table_getGroupDifference_studentT (Table me, integer column, integer groupColumn, conststring32 group1, conststring32 group2, double significanceLevel,
  1465. double *out_tFromZero, double *out_numberOfDegreesOfFreedom, double *out_significanceFromZero, double *out_lowerLimit, double *out_upperLimit)
  1466. {
  1467. if (out_tFromZero) *out_tFromZero = undefined;
  1468. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = undefined;
  1469. if (out_significanceFromZero) *out_significanceFromZero = undefined;
  1470. if (out_lowerLimit) *out_lowerLimit = undefined;
  1471. if (out_upperLimit) *out_upperLimit = undefined;
  1472. if (column < 1 || column > my numberOfColumns) return undefined;
  1473. if (groupColumn < 1 || groupColumn > my numberOfColumns) return undefined;
  1474. Table_numericize_Assert (me, column);
  1475. integer n1 = 0, n2 = 0;
  1476. longdouble sum1 = 0.0, sum2 = 0.0;
  1477. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1478. TableRow row = my rows.at [irow];
  1479. if (row -> cells [groupColumn]. string) {
  1480. if (str32equ (row -> cells [groupColumn]. string.get(), group1)) {
  1481. n1 ++;
  1482. sum1 += row -> cells [column]. number;
  1483. } else if (str32equ (row -> cells [groupColumn]. string.get(), group2)) {
  1484. n2 ++;
  1485. sum2 += row -> cells [column]. number;
  1486. }
  1487. }
  1488. }
  1489. if (n1 < 1 || n2 < 1) return undefined;
  1490. integer degreesOfFreedom = n1 + n2 - 2;
  1491. if (out_numberOfDegreesOfFreedom) *out_numberOfDegreesOfFreedom = degreesOfFreedom;
  1492. double mean1 = (double) sum1 / n1;
  1493. double mean2 = (double) sum2 / n2;
  1494. double difference = mean1 - mean2;
  1495. if (degreesOfFreedom >= 1 && (out_tFromZero || out_significanceFromZero || out_lowerLimit || out_upperLimit)) {
  1496. longdouble sumOfSquares = 0.0;
  1497. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1498. TableRow row = my rows.at [irow];
  1499. if (row -> cells [groupColumn]. string) {
  1500. if (str32equ (row -> cells [groupColumn]. string.get(), group1)) {
  1501. double diff = row -> cells [column]. number - mean1;
  1502. sumOfSquares += diff * diff;
  1503. } else if (str32equ (row -> cells [groupColumn]. string.get(), group2)) {
  1504. double diff = row -> cells [column]. number - mean2;
  1505. sumOfSquares += diff * diff;
  1506. }
  1507. }
  1508. }
  1509. double standardError = sqrt ((double) sumOfSquares / degreesOfFreedom * (1.0 / n1 + 1.0 / n2));
  1510. if (out_tFromZero && standardError != 0.0) *out_tFromZero = difference / standardError;
  1511. if (out_significanceFromZero) *out_significanceFromZero =
  1512. standardError == 0.0 ? 0.0 : NUMstudentQ (fabs (difference) / standardError, degreesOfFreedom);
  1513. if (out_lowerLimit) *out_lowerLimit =
  1514. difference - standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1515. if (out_upperLimit) *out_upperLimit =
  1516. difference + standardError * NUMinvStudentQ (significanceLevel, degreesOfFreedom);
  1517. }
  1518. return difference;
  1519. }
  1520. double Table_getGroupDifference_wilcoxonRankSum (Table me, integer column, integer groupColumn, conststring32 group1, conststring32 group2,
  1521. double *out_rankSum, double *out_significanceFromZero)
  1522. {
  1523. if (out_rankSum) *out_rankSum = undefined;
  1524. if (out_significanceFromZero) *out_significanceFromZero = undefined;
  1525. if (column < 1 || column > my numberOfColumns) return undefined;
  1526. if (groupColumn < 1 || groupColumn > my numberOfColumns) return undefined;
  1527. Table_numericize_Assert (me, column);
  1528. integer n1 = 0, n2 = 0;
  1529. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1530. TableRow row = my rows.at [irow];
  1531. if (row -> cells [groupColumn]. string) {
  1532. if (str32equ (row -> cells [groupColumn]. string.get(), group1)) {
  1533. n1 ++;
  1534. } else if (str32equ (row -> cells [groupColumn]. string.get(), group2)) {
  1535. n2 ++;
  1536. }
  1537. }
  1538. }
  1539. integer n = n1 + n2;
  1540. if (n1 < 1 || n2 < 1 || n < 3) return undefined;
  1541. autoTable ranks = Table_createWithoutColumnNames (n, 3); // column 1 = group, 2 = value, 3 = rank
  1542. for (integer irow = 1, jrow = 0; irow <= my rows.size; irow ++) {
  1543. TableRow row = my rows.at [irow];
  1544. if (row -> cells [groupColumn]. string) {
  1545. if (str32equ (row -> cells [groupColumn]. string.get(), group1)) {
  1546. Table_setNumericValue (ranks.get(), ++ jrow, 1, 1.0);
  1547. Table_setNumericValue (ranks.get(), jrow, 2, row -> cells [column]. number);
  1548. } else if (str32equ (row -> cells [groupColumn]. string.get(), group2)) {
  1549. Table_setNumericValue (ranks.get(), ++ jrow, 1, 2.0);
  1550. Table_setNumericValue (ranks.get(), jrow, 2, row -> cells [column]. number);
  1551. }
  1552. }
  1553. }
  1554. Table_numericize_Assert (ranks.get(), 1);
  1555. Table_numericize_Assert (ranks.get(), 2);
  1556. Table_numericize_Assert (ranks.get(), 3);
  1557. integer columns [1+1] = { 0, 2 }; // we're gonna sort by column 2
  1558. Table_sortRows_Assert (ranks.get(), constINTVEC (columns, 1)); // we sort by one column only
  1559. double totalNumberOfTies3 = 0.0;
  1560. for (integer irow = 1; irow <= ranks -> rows.size; irow ++) {
  1561. TableRow row = ranks -> rows.at [irow];
  1562. double value = row -> cells [2]. number;
  1563. integer rowOfLastTie = irow + 1;
  1564. for (; rowOfLastTie <= ranks -> rows.size; rowOfLastTie ++) {
  1565. TableRow row2 = ranks -> rows.at [rowOfLastTie];
  1566. double value2 = row2 -> cells [2]. number;
  1567. if (value2 != value)
  1568. break;
  1569. }
  1570. rowOfLastTie --;
  1571. double averageRank = 0.5 * ((double) irow + (double) rowOfLastTie);
  1572. for (integer jrow = irow; jrow <= rowOfLastTie; jrow ++)
  1573. Table_setNumericValue (ranks.get(), jrow, 3, averageRank);
  1574. integer numberOfTies = rowOfLastTie - irow + 1;
  1575. totalNumberOfTies3 += (double) (numberOfTies - 1) * (double) numberOfTies * (double) (numberOfTies + 1);
  1576. }
  1577. Table_numericize_Assert (ranks.get(), 3);
  1578. double maximumRankSum = (double) n1 * (double) n2;
  1579. longdouble rankSum = 0.0;
  1580. for (integer irow = 1; irow <= ranks -> rows.size; irow ++) {
  1581. TableRow row = ranks -> rows.at [irow];
  1582. if (row -> cells [1]. number == 1.0)
  1583. rankSum += row -> cells [3]. number;
  1584. }
  1585. rankSum -= 0.5 * (double) n1 * ((double) n1 + 1.0);
  1586. double stdev = sqrt (maximumRankSum * ((double) n + 1.0 - totalNumberOfTies3 / n / (n - 1)) / 12.0);
  1587. if (out_rankSum)
  1588. *out_rankSum = (double) rankSum;
  1589. if (out_significanceFromZero)
  1590. *out_significanceFromZero = NUMgaussQ (fabs ((double) rankSum - 0.5 * maximumRankSum) / stdev);
  1591. return (double) rankSum / maximumRankSum;
  1592. }
  1593. double Table_getFisherF (Table me, integer col1, integer col2);
  1594. double Table_getOneWayAnovaSignificance (Table me, integer col1, integer col2);
  1595. double Table_getFisherFLowerLimit (Table me, integer col1, integer col2, double significanceLevel);
  1596. double Table_getFisherFUpperLimit (Table me, integer col1, integer col2, double significanceLevel);
  1597. bool Table_getExtrema (Table me, integer icol, double *minimum, double *maximum) {
  1598. integer n = my rows.size;
  1599. if (icol < 1 || icol > my numberOfColumns || n == 0) {
  1600. *minimum = *maximum = undefined;
  1601. return false;
  1602. }
  1603. Table_numericize_Assert (me, icol);
  1604. *minimum = *maximum = my rows.at [1] -> cells [icol]. number;
  1605. for (integer irow = 2; irow <= n; irow ++) {
  1606. double value = my rows.at [irow] -> cells [icol]. number;
  1607. if (value < *minimum) *minimum = value;
  1608. if (value > *maximum) *maximum = value;
  1609. }
  1610. return true;
  1611. }
  1612. void Table_scatterPlot_mark (Table me, Graphics g, integer xcolumn, integer ycolumn,
  1613. double xmin, double xmax, double ymin, double ymax, double markSize_mm, conststring32 mark, bool garnish)
  1614. {
  1615. if (xcolumn < 1 || xcolumn > my numberOfColumns || ycolumn < 1 || ycolumn > my numberOfColumns) return;
  1616. Table_numericize_Assert (me, xcolumn);
  1617. Table_numericize_Assert (me, ycolumn);
  1618. if (xmin == xmax) {
  1619. if (! Table_getExtrema (me, xcolumn, & xmin, & xmax)) return;
  1620. if (xmin == xmax) {
  1621. xmin -= 0.5;
  1622. xmax += 0.5;
  1623. }
  1624. }
  1625. if (ymin == ymax) {
  1626. if (! Table_getExtrema (me, ycolumn, & ymin, & ymax)) return;
  1627. if (ymin == ymax) {
  1628. ymin -= 0.5;
  1629. ymax += 0.5;
  1630. }
  1631. }
  1632. Graphics_setInner (g);
  1633. Graphics_setWindow (g, xmin, xmax, ymin, ymax);
  1634. Graphics_setTextAlignment (g, Graphics_CENTRE, Graphics_HALF);
  1635. integer n = my rows.size;
  1636. for (integer irow = 1; irow <= n; irow ++) {
  1637. TableRow row = my rows.at [irow];
  1638. Graphics_mark (g, row -> cells [xcolumn]. number, row -> cells [ycolumn]. number, markSize_mm, mark);
  1639. }
  1640. Graphics_unsetInner (g);
  1641. if (garnish) {
  1642. Graphics_drawInnerBox (g);
  1643. Graphics_marksBottom (g, 2, true, true, false);
  1644. if (my columnHeaders [xcolumn]. label)
  1645. Graphics_textBottom (g, true, my columnHeaders [xcolumn]. label.get());
  1646. Graphics_marksLeft (g, 2, true, true, false);
  1647. if (my columnHeaders [ycolumn]. label)
  1648. Graphics_textLeft (g, true, my columnHeaders [ycolumn]. label.get());
  1649. }
  1650. }
  1651. void Table_scatterPlot (Table me, Graphics g, integer xcolumn, integer ycolumn,
  1652. double xmin, double xmax, double ymin, double ymax, integer markColumn, int fontSize, bool garnish)
  1653. {
  1654. int saveFontSize = Graphics_inqFontSize (g);
  1655. if (xcolumn < 1 || xcolumn > my numberOfColumns || ycolumn < 1 || ycolumn > my numberOfColumns) return;
  1656. Table_numericize_Assert (me, xcolumn);
  1657. Table_numericize_Assert (me, ycolumn);
  1658. if (xmin == xmax) {
  1659. if (! Table_getExtrema (me, xcolumn, & xmin, & xmax)) return;
  1660. if (xmin == xmax) {
  1661. xmin -= 0.5;
  1662. xmax += 0.5;
  1663. }
  1664. }
  1665. if (ymin == ymax) {
  1666. if (! Table_getExtrema (me, ycolumn, & ymin, & ymax)) return;
  1667. if (ymin == ymax) {
  1668. ymin -= 0.5;
  1669. ymax += 0.5;
  1670. }
  1671. }
  1672. Graphics_setInner (g);
  1673. Graphics_setWindow (g, xmin, xmax, ymin, ymax);
  1674. Graphics_setTextAlignment (g, Graphics_CENTRE, Graphics_HALF);
  1675. Graphics_setFontSize (g, fontSize);
  1676. integer n = my rows.size;
  1677. for (integer irow = 1; irow <= n; irow ++) {
  1678. TableRow row = my rows.at [irow];
  1679. conststring32 mark = row -> cells [markColumn]. string.get();
  1680. if (mark)
  1681. Graphics_text (g, row -> cells [xcolumn]. number, row -> cells [ycolumn]. number, mark);
  1682. }
  1683. Graphics_setFontSize (g, saveFontSize);
  1684. Graphics_unsetInner (g);
  1685. if (garnish) {
  1686. Graphics_drawInnerBox (g);
  1687. Graphics_marksBottom (g, 2, true, true, false);
  1688. if (my columnHeaders [xcolumn]. label)
  1689. Graphics_textBottom (g, true, my columnHeaders [xcolumn]. label.get());
  1690. Graphics_marksLeft (g, 2, true, true, false);
  1691. if (my columnHeaders [ycolumn]. label)
  1692. Graphics_textLeft (g, true, my columnHeaders [ycolumn]. label.get());
  1693. }
  1694. }
  1695. void Table_drawEllipse_e (Table me, Graphics g, integer xcolumn, integer ycolumn,
  1696. double xmin, double xmax, double ymin, double ymax, double numberOfSigmas, bool garnish)
  1697. {
  1698. try {
  1699. if (xcolumn < 1 || xcolumn > my numberOfColumns || ycolumn < 1 || ycolumn > my numberOfColumns) return;
  1700. Table_numericize_Assert (me, xcolumn);
  1701. Table_numericize_Assert (me, ycolumn);
  1702. if (xmin == xmax) {
  1703. if (! Table_getExtrema (me, xcolumn, & xmin, & xmax)) return;
  1704. if (xmin == xmax) {
  1705. xmin -= 0.5;
  1706. xmax += 0.5;
  1707. }
  1708. }
  1709. if (ymin == ymax) {
  1710. if (! Table_getExtrema (me, ycolumn, & ymin, & ymax)) return;
  1711. if (ymin == ymax) {
  1712. ymin -= 0.5;
  1713. ymax += 0.5;
  1714. }
  1715. }
  1716. autoTableOfReal tableOfReal = TableOfReal_create (my rows.size, 2);
  1717. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1718. tableOfReal -> data [irow] [1] = Table_getNumericValue_Assert (me, irow, xcolumn);
  1719. tableOfReal -> data [irow] [2] = Table_getNumericValue_Assert (me, irow, ycolumn);
  1720. }
  1721. autoSSCP sscp = TableOfReal_to_SSCP (tableOfReal.get(), 0, 0, 0, 0);
  1722. SSCP_drawConcentrationEllipse (sscp.get(), g, numberOfSigmas, 0, 1, 2, xmin, xmax, ymin, ymax, garnish);
  1723. } catch (MelderError) {
  1724. Melder_clearError (); // drawing errors shall be ignored
  1725. }
  1726. }
  1727. static conststring32 visibleString (conststring32 s) {
  1728. return ( s && s [0] != U'\0' ? s : U"?" );
  1729. }
  1730. void Table_list (Table me, bool includeRowNumbers) {
  1731. MelderInfo_open ();
  1732. if (includeRowNumbers) {
  1733. MelderInfo_write (U"row");
  1734. if (my numberOfColumns > 0) MelderInfo_write (U"\t");
  1735. }
  1736. for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
  1737. if (icol > 1) MelderInfo_write (U"\t");
  1738. MelderInfo_write (visibleString (my columnHeaders [icol]. label.get()));
  1739. }
  1740. MelderInfo_write (U"\n");
  1741. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1742. if (includeRowNumbers) {
  1743. MelderInfo_write (irow);
  1744. if (my numberOfColumns > 0) MelderInfo_write (U"\t");
  1745. }
  1746. TableRow row = my rows.at [irow];
  1747. for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
  1748. if (icol > 1) MelderInfo_write (U"\t");
  1749. MelderInfo_write (visibleString (row -> cells [icol]. string.get()));
  1750. }
  1751. MelderInfo_write (U"\n");
  1752. }
  1753. MelderInfo_close ();
  1754. }
  1755. static void writeToCharacterSeparatedFile (Table me, MelderFile file, char32 separator, bool interpretQuotes) {
  1756. autoMelderString buffer;
  1757. for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
  1758. if (icol != 1) MelderString_appendCharacter (& buffer, separator);
  1759. conststring32 s = my columnHeaders [icol]. label.get();
  1760. MelderString_append (& buffer, ( s && s [0] != U'\0' ? s : U"?" ));
  1761. }
  1762. MelderString_appendCharacter (& buffer, U'\n');
  1763. for (integer irow = 1; irow <= my rows.size; irow ++) {
  1764. TableRow row = my rows.at [irow];
  1765. for (integer icol = 1; icol <= my numberOfColumns; icol ++) {
  1766. if (icol != 1) MelderString_appendCharacter (& buffer, separator);
  1767. conststring32 s = row -> cells [icol]. string.get();
  1768. if (! s) s = U"";
  1769. if (s [0] == U'\0') {
  1770. bool separatorIsInvisible = ( separator == U'\t' );
  1771. bool emptyStringsWillBeVisibleEnough = ! separatorIsInvisible; // it's fine to have ",,,,,," in a comma environment
  1772. bool replaceEmptyStringsWithSomethingVisible = ! emptyStringsWillBeVisibleEnough;
  1773. if (replaceEmptyStringsWithSomethingVisible) {
  1774. MelderString_appendCharacter (& buffer, U'?');
  1775. }
  1776. } else if (str32chr (s, separator)) {
  1777. if (interpretQuotes) {
  1778. MelderString_appendCharacter (& buffer, U'\"');
  1779. MelderString_append (& buffer, s);
  1780. MelderString_appendCharacter (& buffer, U'\"');
  1781. } else {
  1782. conststring32 separatorText =
  1783. separator == U'\t' ? U"a separating tab" :
  1784. separator == U',' ? U"a separating comma" :
  1785. separator == U';' ? U"a separating semicolon" :
  1786. U"a separator symbol";
  1787. Melder_throw (U"Row ", irow, U" contains ", separatorText, U" inside a cell without providing the possiblity of quoting.");
  1788. }
  1789. } else {
  1790. MelderString_append (& buffer, s);
  1791. }
  1792. }
  1793. MelderString_appendCharacter (& buffer, U'\n');
  1794. }
  1795. MelderFile_writeText (file, buffer.string, Melder_getOutputEncoding ());
  1796. }
  1797. void Table_writeToTabSeparatedFile (Table me, MelderFile file) {
  1798. try {
  1799. writeToCharacterSeparatedFile (me, file, U'\t', false);
  1800. } catch (MelderError) {
  1801. Melder_throw (me, U": not written to tab-separated file.");
  1802. }
  1803. }
  1804. void Table_writeToCommaSeparatedFile (Table me, MelderFile file) {
  1805. try {
  1806. writeToCharacterSeparatedFile (me, file, U',', true);
  1807. } catch (MelderError) {
  1808. Melder_throw (me, U": not written to comma-separated file.");
  1809. }
  1810. }
  1811. void Table_writeToSemicolonSeparatedFile (Table me, MelderFile file) {
  1812. try {
  1813. writeToCharacterSeparatedFile (me, file, U';', true);
  1814. } catch (MelderError) {
  1815. Melder_throw (me, U": not written to comma-separated file.");
  1816. }
  1817. }
  1818. autoTable Table_readFromTableFile (MelderFile file) {
  1819. try {
  1820. autostring32 string = MelderFile_readText (file);
  1821. /*
  1822. Count columns.
  1823. */
  1824. integer numberOfColumns = 0;
  1825. char32 *p = & string [0];
  1826. for (;;) {
  1827. char32 kar = *p++;
  1828. if (kar == U'\n' || kar == U'\0') break;
  1829. if (kar == U' ' || kar == U'\t') continue;
  1830. numberOfColumns ++;
  1831. do { kar = *p++; } while (kar != U' ' && kar != U'\t' && kar != U'\n' && kar != U'\0');
  1832. if (kar == U'\n' || kar == U'\0') break;
  1833. }
  1834. if (numberOfColumns < 1) Melder_throw (U"No columns.");
  1835. /*
  1836. Count elements.
  1837. */
  1838. p = & string [0];
  1839. integer numberOfElements = 0;
  1840. for (;;) {
  1841. char32 kar = *p++;
  1842. if (kar == U'\0') break;
  1843. if (kar == U' ' || kar == U'\t' || kar == U'\n') continue;
  1844. numberOfElements ++;
  1845. do { kar = *p++; } while (kar != U' ' && kar != U'\t' && kar != U'\n' && kar != U'\0');
  1846. if (kar == U'\0') break;
  1847. }
  1848. /*
  1849. Check if all columns are complete.
  1850. */
  1851. if (numberOfElements == 0 || numberOfElements % numberOfColumns != 0)
  1852. Melder_throw (U"The number of elements (", numberOfElements, U") is not a multiple of the number of columns (", numberOfColumns, U").");
  1853. /*
  1854. Create empty table.
  1855. */
  1856. integer numberOfRows = numberOfElements / numberOfColumns - 1;
  1857. autoTable me = Table_create (numberOfRows, numberOfColumns);
  1858. /*
  1859. Read elements.
  1860. */
  1861. p = & string [0];
  1862. for (integer icol = 1; icol <= numberOfColumns; icol ++) {
  1863. while (*p == U' ' || *p == U'\t') { Melder_assert (*p != U'\0'); p ++; }
  1864. static MelderString buffer { };
  1865. MelderString_empty (& buffer);
  1866. while (*p != U' ' && *p != U'\t' && *p != U'\n') { MelderString_appendCharacter (& buffer, *p); p ++; }
  1867. Table_setColumnLabel (me.get(), icol, buffer.string);
  1868. MelderString_empty (& buffer);
  1869. }
  1870. for (integer irow = 1; irow <= numberOfRows; irow ++) {
  1871. TableRow row = my rows.at [irow];
  1872. for (integer icol = 1; icol <= numberOfColumns; icol ++) {
  1873. while (*p == U' ' || *p == U'\t' || *p == U'\n') { Melder_assert (*p != U'\0'); p ++; }
  1874. static MelderString buffer { };
  1875. MelderString_empty (& buffer);
  1876. while (*p != U' ' && *p != U'\t' && *p != U'\n' && *p != U'\0') { MelderString_appendCharacter (& buffer, *p); p ++; }
  1877. row -> cells [icol]. string = Melder_dup_f (buffer.string);
  1878. MelderString_empty (& buffer);
  1879. }
  1880. }
  1881. return me;
  1882. } catch (MelderError) {
  1883. Melder_throw (U"Table object not read from space-separated text file ", file, U".");
  1884. }
  1885. }
  1886. autoTable Table_readFromCharacterSeparatedTextFile (MelderFile file, char32 separator, bool interpretQuotes) {
  1887. try {
  1888. autostring32 string = MelderFile_readText (file);
  1889. /*
  1890. Kill final new-line symbols.
  1891. */
  1892. for (int64 length = str32len (string.get());
  1893. length > 0 && string [length - 1] == U'\n';
  1894. length = str32len (string.get()))
  1895. {
  1896. string [length - 1] = U'\0';
  1897. }
  1898. /*
  1899. Count columns.
  1900. */
  1901. integer numberOfColumns = 1;
  1902. const char32 *p = & string [0];
  1903. for (;;) {
  1904. char32 kar = *p++;
  1905. if (kar == U'\0') Melder_throw (U"No rows.");
  1906. if (kar == U'\n') break;
  1907. if (kar == separator) numberOfColumns ++;
  1908. }
  1909. /*
  1910. Count rows.
  1911. */
  1912. integer numberOfRows = 1;
  1913. {// scope
  1914. bool withinQuotes = false;
  1915. for (;;) {
  1916. char32 kar = *p++;
  1917. if (interpretQuotes && kar == U'\"')
  1918. withinQuotes = ! withinQuotes;
  1919. if (! withinQuotes) {
  1920. if (kar == U'\0') break;
  1921. if (kar == U'\n') numberOfRows ++;
  1922. }
  1923. }
  1924. }
  1925. /*
  1926. Create empty table.
  1927. */
  1928. autoTable me = Table_create (numberOfRows, numberOfColumns);
  1929. /*
  1930. Read column names.
  1931. */
  1932. autoMelderString buffer;
  1933. p = & string [0];
  1934. for (integer icol = 1; icol <= numberOfColumns; icol ++) {
  1935. MelderString_empty (& buffer);
  1936. while (*p != separator && *p != U'\n') {
  1937. Melder_assert (*p != U'\0');
  1938. MelderString_appendCharacter (& buffer, *p);
  1939. p ++;
  1940. }
  1941. p ++;
  1942. Table_setColumnLabel (me.get(), icol, buffer.string);
  1943. }
  1944. /*
  1945. Read cells.
  1946. */
  1947. for (integer irow = 1; irow <= numberOfRows; irow ++) {
  1948. TableRow row = my rows.at [irow];
  1949. for (integer icol = 1; icol <= numberOfColumns; icol ++) {
  1950. MelderString_empty (& buffer);
  1951. bool withinQuotes = false;
  1952. while (*p != separator && *p != U'\n' && *p != U'\0' || withinQuotes) {
  1953. if (interpretQuotes && *p == U'\"') {
  1954. withinQuotes = ! withinQuotes;
  1955. } else {
  1956. MelderString_appendCharacter (& buffer, *p);
  1957. }
  1958. p ++;
  1959. }
  1960. if (*p == U'\0') {
  1961. if (irow != numberOfRows)
  1962. Melder_fatal (U"irow ", irow, U", nrow ", numberOfRows, U", icol ", icol, U", ncol ", numberOfColumns);
  1963. if (icol != numberOfColumns)
  1964. Melder_throw (U"Last row incomplete.");
  1965. } else if (*p == U'\n') {
  1966. if (icol != numberOfColumns)
  1967. Melder_throw (U"Row ", irow, U" incomplete.");
  1968. p ++;
  1969. } else {
  1970. Melder_assert (*p == separator);
  1971. p ++;
  1972. }
  1973. row -> cells [icol]. string = Melder_dup (buffer.string); // BUG? could be null
  1974. }
  1975. }
  1976. return me;
  1977. } catch (MelderError) {
  1978. Melder_throw (U"Table object not read from character-separated text file ", file, U".");
  1979. }
  1980. }
  1981. /* End of file Table.cpp */