main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /****************************************************************************
  2. *
  3. * MODULE: r.regression.multi
  4. *
  5. * AUTHOR(S): Markus Metz
  6. *
  7. * PURPOSE: Calculates multiple linear regression from raster maps:
  8. * y = b0 + b1*x1 + b2*x2 + ... + bn*xn + e
  9. *
  10. * COPYRIGHT: (C) 2011 by the GRASS Development Team
  11. *
  12. * This program is free software under the GNU General Public
  13. * License (>=v2). Read the file COPYING that comes with GRASS
  14. * for details.
  15. *
  16. *****************************************************************************/
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <math.h>
  20. #include <string.h>
  21. #include <grass/gis.h>
  22. #include <grass/glocale.h>
  23. #include <grass/raster.h>
  24. struct MATRIX
  25. {
  26. int n; /* SIZE OF THIS MATRIX (N x N) */
  27. double *v;
  28. };
  29. #define M(m,row,col) (m)->v[((row) * ((m)->n)) + (col)]
  30. static int solvemat(struct MATRIX *m, double a[], double B[])
  31. {
  32. int i, j, i2, j2, imark;
  33. double factor, temp;
  34. double pivot; /* ACTUAL VALUE OF THE LARGEST PIVOT CANDIDATE */
  35. for (i = 0; i < m->n; i++) {
  36. j = i;
  37. /* find row with largest magnitude value for pivot value */
  38. pivot = M(m, i, j);
  39. imark = i;
  40. for (i2 = i + 1; i2 < m->n; i2++) {
  41. temp = fabs(M(m, i2, j));
  42. if (temp > fabs(pivot)) {
  43. pivot = M(m, i2, j);
  44. imark = i2;
  45. }
  46. }
  47. /* if the pivot is very small then the points are nearly co-linear */
  48. /* co-linear points result in an undefined matrix, and nearly */
  49. /* co-linear points results in a solution with rounding error */
  50. if (pivot == 0.0) {
  51. G_warning(_("Matrix is unsolvable"));
  52. return 0;
  53. }
  54. /* if row with highest pivot is not the current row, switch them */
  55. if (imark != i) {
  56. for (j2 = 0; j2 < m->n; j2++) {
  57. temp = M(m, imark, j2);
  58. M(m, imark, j2) = M(m, i, j2);
  59. M(m, i, j2) = temp;
  60. }
  61. temp = a[imark];
  62. a[imark] = a[i];
  63. a[i] = temp;
  64. }
  65. /* compute zeros above and below the pivot, and compute
  66. values for the rest of the row as well */
  67. for (i2 = 0; i2 < m->n; i2++) {
  68. if (i2 != i) {
  69. factor = M(m, i2, j) / pivot;
  70. for (j2 = j; j2 < m->n; j2++)
  71. M(m, i2, j2) -= factor * M(m, i, j2);
  72. a[i2] -= factor * a[i];
  73. }
  74. }
  75. }
  76. /* SINCE ALL OTHER VALUES IN THE MATRIX ARE ZERO NOW, CALCULATE THE
  77. COEFFICIENTS BY DIVIDING THE COLUMN VECTORS BY THE DIAGONAL VALUES. */
  78. for (i = 0; i < m->n; i++) {
  79. B[i] = a[i] / M(m, i, i);
  80. }
  81. return 1;
  82. }
  83. int main(int argc, char *argv[])
  84. {
  85. unsigned int r, c, rows, cols, n_valid; /* totals */
  86. int *mapx_fd, mapy_fd, mapres_fd, mapest_fd;
  87. int i, j, k, n_predictors;
  88. double *sumX, sumY, *sumsqX, sumsqY, *sumXY;
  89. double *meanX, meanY, *varX, varY, *sdX, sdY;
  90. double yest, yres; /* estimated y, residual */
  91. double sumYest, *SSerr_without;
  92. double SE;
  93. double meanYest, meanYres, varYest, varYres, sdYest, sdYres;
  94. double SStot, SSerr, SSreg;
  95. double **a;
  96. struct MATRIX *m, *m_all;
  97. double **B, Rsq, Rsqadj, F, t, AIC, AICc, BIC;
  98. unsigned int count = 0;
  99. DCELL **mapx_buf, *mapy_buf, *mapx_val, mapy_val, *mapres_buf, *mapest_buf;
  100. char *name;
  101. struct Option *input_mapx, *input_mapy, *output_res, *output_est, *output_opt;
  102. struct Flag *shell_style;
  103. struct Cell_head region;
  104. struct GModule *module;
  105. G_gisinit(argv[0]);
  106. module = G_define_module();
  107. G_add_keyword(_("raster"));
  108. G_add_keyword(_("statistics"));
  109. module->description =
  110. _("Calculates multiple linear regression from raster maps.");
  111. /* Define the different options */
  112. input_mapx = G_define_standard_option(G_OPT_R_INPUTS);
  113. input_mapx->key = "mapx";
  114. input_mapx->description = (_("Map for x coefficient"));
  115. input_mapy = G_define_standard_option(G_OPT_R_INPUT);
  116. input_mapy->key = "mapy";
  117. input_mapy->description = (_("Map for y coefficient"));
  118. output_res = G_define_standard_option(G_OPT_R_OUTPUT);
  119. output_res->key = "residuals";
  120. output_res->required = NO;
  121. output_res->description = (_("Map to store residuals"));
  122. output_est = G_define_standard_option(G_OPT_R_OUTPUT);
  123. output_est->key = "estimates";
  124. output_est->required = NO;
  125. output_est->description = (_("Map to store estimates"));
  126. output_opt = G_define_standard_option(G_OPT_F_OUTPUT);
  127. output_opt->key = "output";
  128. output_opt->required = NO;
  129. output_opt->description =
  130. (_("ASCII file for storing regression coefficients (output to screen if file not specified)."));
  131. shell_style = G_define_flag();
  132. shell_style->key = 'g';
  133. shell_style->description = _("Print in shell script style");
  134. if (G_parser(argc, argv))
  135. exit(EXIT_FAILURE);
  136. name = output_opt->answer;
  137. if (name != NULL && strcmp(name, "-") != 0) {
  138. if (NULL == freopen(name, "w", stdout)) {
  139. G_fatal_error(_("Unable to open file <%s> for writing"), name);
  140. }
  141. }
  142. G_get_window(&region);
  143. rows = region.rows;
  144. cols = region.cols;
  145. /* count x maps */
  146. for (i = 0; input_mapx->answers[i]; i++);
  147. n_predictors = i;
  148. /* allocate memory for x maps */
  149. mapx_fd = (int *)G_malloc(n_predictors * sizeof(int));
  150. sumX = (double *)G_malloc(n_predictors * sizeof(double));
  151. sumsqX = (double *)G_malloc(n_predictors * sizeof(double));
  152. sumXY = (double *)G_malloc(n_predictors * sizeof(double));
  153. SSerr_without = (double *)G_malloc(n_predictors * sizeof(double));
  154. meanX = (double *)G_malloc(n_predictors * sizeof(double));
  155. varX = (double *)G_malloc(n_predictors * sizeof(double));
  156. sdX = (double *)G_malloc(n_predictors * sizeof(double));
  157. mapx_buf = (DCELL **)G_malloc(n_predictors * sizeof(DCELL *));
  158. mapx_val = (DCELL *)G_malloc((n_predictors + 1) * sizeof(DCELL));
  159. /* ordinary least squares */
  160. m = NULL;
  161. m_all = (struct MATRIX *)G_malloc((n_predictors + 1) * sizeof(struct MATRIX));
  162. a = (double **)G_malloc((n_predictors + 1) * sizeof(double *));
  163. B = (double **)G_malloc((n_predictors + 1) * sizeof(double *));
  164. m = &(m_all[0]);
  165. m->n = n_predictors + 1;
  166. m->v = (double *)G_malloc(m->n * m->n * sizeof(double));
  167. a[0] = (double *)G_malloc(m->n * sizeof(double));
  168. B[0] = (double *)G_malloc(m->n * sizeof(double));
  169. for (i = 0; i < m->n; i++) {
  170. for (j = i; j < m->n; j++)
  171. M(m, i, j) = 0.0;
  172. a[0][i] = 0.0;
  173. B[0][i] = 0.0;
  174. }
  175. for (k = 1; k <= n_predictors; k++) {
  176. m = &(m_all[k]);
  177. m->n = n_predictors;
  178. m->v = (double *)G_malloc(m->n * m->n * sizeof(double));
  179. a[k] = (double *)G_malloc(m->n * sizeof(double));
  180. B[k] = (double *)G_malloc(m->n * sizeof(double));
  181. for (i = 0; i < m->n; i++) {
  182. for (j = i; j < m->n; j++)
  183. M(m, i, j) = 0.0;
  184. a[k][i] = 0.0;
  185. B[k][i] = 0.0;
  186. }
  187. }
  188. /* open maps */
  189. G_debug(1, "open maps");
  190. for (i = 0; i < n_predictors; i++) {
  191. mapx_fd[i] = Rast_open_old(input_mapx->answers[i], "");
  192. }
  193. mapy_fd = Rast_open_old(input_mapy->answer, "");
  194. for (i = 0; i < n_predictors; i++)
  195. mapx_buf[i] = Rast_allocate_d_buf();
  196. mapy_buf = Rast_allocate_d_buf();
  197. for (i = 0; i < n_predictors; i++) {
  198. sumX[i] = sumsqX[i] = sumXY[i] = 0.0;
  199. meanX[i] = varX[i] = sdX[i] = 0.0;
  200. SSerr_without[i] = 0.0;
  201. }
  202. sumY = sumsqY = meanY = varY = sdY = 0.0;
  203. sumYest = meanYest = varYest = sdYest = 0.0;
  204. meanYres = varYres = sdYres = 0.0;
  205. /* read input maps */
  206. G_message(_("First pass..."));
  207. n_valid = 0;
  208. mapx_val[0] = 1.0;
  209. for (r = 0; r < rows; r++) {
  210. G_percent(r, rows, 2);
  211. for (i = 0; i < n_predictors; i++)
  212. Rast_get_d_row(mapx_fd[i], mapx_buf[i], r);
  213. Rast_get_d_row(mapy_fd, mapy_buf, r);
  214. for (c = 0; c < cols; c++) {
  215. int isnull = 0;
  216. for (i = 0; i < n_predictors; i++) {
  217. mapx_val[i + 1] = mapx_buf[i][c];
  218. if (Rast_is_d_null_value(&(mapx_val[i + 1]))) {
  219. isnull = 1;
  220. break;
  221. }
  222. }
  223. if (isnull)
  224. continue;
  225. mapy_val = mapy_buf[c];
  226. if (Rast_is_d_null_value(&mapy_val))
  227. continue;
  228. for (i = 0; i <= n_predictors; i++) {
  229. double val1 = mapx_val[i];
  230. for (j = i; j <= n_predictors; j++) {
  231. double val2 = mapx_val[j];
  232. m = &(m_all[0]);
  233. M(m, i, j) += val1 * val2;
  234. /* linear model without predictor k */
  235. for (k = 1; k <= n_predictors; k++) {
  236. if (k != i && k != j) {
  237. int i2 = k > i ? i : i - 1;
  238. int j2 = k > j ? j : j - 1;
  239. m = &(m_all[k]);
  240. M(m, i2, j2) += val1 * val2;
  241. }
  242. }
  243. }
  244. a[0][i] += mapy_val * val1;
  245. for (k = 1; k <= n_predictors; k++) {
  246. if (k != i) {
  247. int i2 = k > i ? i : i - 1;
  248. a[k][i2] += mapy_val * val1;
  249. }
  250. }
  251. if (i > 0) {
  252. sumX[i - 1] += val1;
  253. sumsqX[i - 1] += val1 * val1;
  254. sumXY[i - 1] += val1 * mapy_val;
  255. }
  256. }
  257. sumY += mapy_val;
  258. sumsqY += mapy_val * mapy_val;
  259. count++;
  260. }
  261. }
  262. G_percent(rows, rows, 2);
  263. if (count < n_predictors + 1)
  264. G_fatal_error(_("Not enough valid cells available"));
  265. for (k = 0; k <= n_predictors; k++) {
  266. m = &(m_all[k]);
  267. /* TRANSPOSE VALUES IN UPPER HALF OF M TO OTHER HALF */
  268. for (i = 1; i < m->n; i++)
  269. for (j = 0; j < i; j++)
  270. M(m, i, j) = M(m, j, i);
  271. if (!solvemat(m, a[k], B[k])) {
  272. for (i = 0; i <= n_predictors; i++) {
  273. fprintf(stdout, "b%d=0.0\n", i);
  274. }
  275. G_fatal_error(_("Multiple regression failed"));
  276. }
  277. }
  278. /* second pass */
  279. G_message(_("Second pass..."));
  280. /* residuals output */
  281. if (output_res->answer) {
  282. mapres_fd = Rast_open_new(output_res->answer, DCELL_TYPE);
  283. mapres_buf = Rast_allocate_d_buf();
  284. }
  285. else {
  286. mapres_fd = -1;
  287. mapres_buf = NULL;
  288. }
  289. /* estimates output */
  290. if (output_est->answer) {
  291. mapest_fd = Rast_open_new(output_est->answer, DCELL_TYPE);
  292. mapest_buf = Rast_allocate_d_buf();
  293. }
  294. else {
  295. mapest_fd = -1;
  296. mapest_buf = NULL;
  297. }
  298. for (i = 0; i < n_predictors; i++)
  299. meanX[i] = sumX[i] / count;
  300. meanY = sumY / count;
  301. SStot = SSerr = SSreg = 0.0;
  302. for (r = 0; r < rows; r++) {
  303. G_percent(r, rows, 2);
  304. for (i = 0; i < n_predictors; i++)
  305. Rast_get_d_row(mapx_fd[i], mapx_buf[i], r);
  306. Rast_get_d_row(mapy_fd, mapy_buf, r);
  307. if (mapres_buf)
  308. Rast_set_d_null_value(mapres_buf, cols);
  309. if (mapest_buf)
  310. Rast_set_d_null_value(mapest_buf, cols);
  311. for (c = 0; c < cols; c++) {
  312. int isnull = 0;
  313. for (i = 0; i < n_predictors; i++) {
  314. mapx_val[i + 1] = mapx_buf[i][c];
  315. if (Rast_is_d_null_value(&(mapx_val[i + 1]))) {
  316. isnull = 1;
  317. break;
  318. }
  319. }
  320. if (isnull)
  321. continue;
  322. yest = 0.0;
  323. for (i = 0; i <= n_predictors; i++) {
  324. yest += B[0][i] * mapx_val[i];
  325. }
  326. if (mapest_buf)
  327. mapest_buf[c] = yest;
  328. mapy_val = mapy_buf[c];
  329. if (Rast_is_d_null_value(&mapy_val))
  330. continue;
  331. yres = mapy_val - yest;
  332. if (mapres_buf)
  333. mapres_buf[c] = yres;
  334. SStot += (mapy_val - meanY) * (mapy_val - meanY);
  335. SSreg += (yest - meanY) * (yest - meanY);
  336. SSerr += yres * yres;
  337. for (k = 1; k <= n_predictors; k++) {
  338. double yesti = 0.0;
  339. double yresi;
  340. /* linear model without predictor k */
  341. for (i = 0; i <= n_predictors; i++) {
  342. if (i != k) {
  343. j = k > i ? i : i - 1;
  344. yesti += B[k][j] * mapx_val[i];
  345. }
  346. }
  347. yresi = mapy_val - yesti;
  348. /* linear model without predictor k */
  349. SSerr_without[k - 1] += yresi * yresi;
  350. varX[k - 1] = (mapx_val[k] - meanX[k - 1]) * (mapx_val[k] - meanX[k - 1]);
  351. }
  352. }
  353. if (mapres_buf)
  354. Rast_put_d_row(mapres_fd, mapres_buf);
  355. if (mapest_buf)
  356. Rast_put_d_row(mapest_fd, mapest_buf);
  357. }
  358. G_percent(rows, rows, 2);
  359. fprintf(stdout, "n=%d\n", count);
  360. /* coefficient of determination aka R squared */
  361. Rsq = 1 - (SSerr / SStot);
  362. fprintf(stdout, "Rsq=%f\n", Rsq);
  363. /* adjusted coefficient of determination */
  364. Rsqadj = 1 - ((SSerr * (count - 1)) / (SStot * (count - n_predictors - 1)));
  365. fprintf(stdout, "Rsqadj=%f\n", Rsqadj);
  366. /* F statistic */
  367. /* F = ((SStot - SSerr) / (n_predictors)) / (SSerr / (count - n_predictors));
  368. * , or: */
  369. F = ((SStot - SSerr) * (count - n_predictors - 1)) / (SSerr * (n_predictors));
  370. fprintf(stdout, "F=%f\n", F);
  371. i = 0;
  372. /* constant aka estimate for intercept in R */
  373. fprintf(stdout, "b%d=%f\n", i, B[0][i]);
  374. /* t score for R squared of the full model, unused */
  375. t = sqrt(Rsq) * sqrt((count - 2) / (1 - Rsq));
  376. /*
  377. fprintf(stdout, "t%d=%f\n", i, t);
  378. */
  379. /* AIC, corrected AIC, and BIC information criteria for the full model */
  380. AIC = count * log(SSerr / count) + 2 * (n_predictors + 1);
  381. fprintf(stdout, "AIC=%f\n", AIC);
  382. AICc = AIC + (2 * n_predictors * (n_predictors + 1)) / (count - n_predictors - 1);
  383. fprintf(stdout, "AICc=%f\n", AICc);
  384. BIC = count * log(SSerr / count) + log(count) * (n_predictors + 1);
  385. fprintf(stdout, "BIC=%f\n", BIC);
  386. /* error variance of the model, identical to R */
  387. SE = SSerr / (count - n_predictors - 1);
  388. /*
  389. fprintf(stdout, "SE=%f\n", SE);
  390. fprintf(stdout, "SSerr=%f\n", SSerr);
  391. */
  392. for (i = 0; i < n_predictors; i++) {
  393. fprintf(stdout, "\npredictor%d=%s\n", i + 1, input_mapx->answers[i]);
  394. fprintf(stdout, "b%d=%f\n", i + 1, B[0][i + 1]);
  395. if (n_predictors > 1) {
  396. double Rsqi, SEi, sumsqX_corr;
  397. /* corrected sum of squares for predictor [i] */
  398. sumsqX_corr = sumsqX[i] - sumX[i] * sumX[i] / (count - n_predictors - 1);
  399. /* standard error SE for predictor [i] */
  400. /* SE[i] with only one predictor: sqrt(SE / sumsqX_corr)
  401. * this does not work with more than one predictor */
  402. /* in R, SEi is sqrt(diag(R) * resvar) with
  403. * R = ???
  404. * resvar = rss / rdf = SE global
  405. * rss = sum of squares of the residuals
  406. * rdf = residual degrees of freedom = count - n_predictors - 1 */
  407. SEi = sqrt(SE / (Rsq * sumsqX_corr));
  408. /*
  409. fprintf(stdout, "SE%d=%f\n", i + 1, SEi);
  410. */
  411. /* Sum of squares for predictor [i] */
  412. /*
  413. fprintf(stdout, "SSerr%d=%f\n", i + 1, SSerr_without[i] - SSerr);
  414. */
  415. /* R squared of the model without predictor [i] */
  416. /* Rsqi = 1 - SSerr_without[i] / SStot; */
  417. /* the additional amount of variance explained
  418. * when including predictor [i] :
  419. * Rsq - Rsqi */
  420. Rsqi = (SSerr_without[i] - SSerr) / SStot;
  421. fprintf(stdout, "Rsq%d=%f\n", i + 1, Rsqi);
  422. /* t score for Student's t distribution, unused */
  423. t = (B[0][i + 1]) / SEi;
  424. /*
  425. fprintf(stdout, "t%d=%f\n", i + 1, t);
  426. */
  427. /* F score for Fisher's F distribution
  428. * here: F score to test if including predictor [i]
  429. * yields a significant improvement
  430. * after Lothar Sachs, Angewandte Statistik:
  431. * F = (Rsq - Rsqi) * (count - n_predictors - 1) / (1 - Rsq) */
  432. /* same like Sumsq / SE */
  433. /* same like (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1) */
  434. /* same like R-stats when entered in R-stats as last predictor */
  435. F = (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1);
  436. fprintf(stdout, "F%d=%f\n", i + 1, F);
  437. /* AIC, corrected AIC, and BIC information criteria for
  438. * the model without predictor [i] */
  439. AIC = count * log(SSerr_without[i] / count) + 2 * (n_predictors);
  440. fprintf(stdout, "AIC%d=%f\n", i + 1, AIC);
  441. AICc = AIC + (2 * (n_predictors - 1) * n_predictors) / (count - n_predictors - 2);
  442. fprintf(stdout, "AICc%d=%f\n", i + 1, AICc);
  443. BIC = count * log(SSerr_without[i] / count) + (n_predictors - 1) * log(count);
  444. fprintf(stdout, "BIC%d=%f\n", i + 1, BIC);
  445. }
  446. }
  447. for (i = 0; i < n_predictors; i++) {
  448. Rast_close(mapx_fd[i]);
  449. G_free(mapx_buf[i]);
  450. }
  451. Rast_close(mapy_fd);
  452. G_free(mapy_buf);
  453. if (mapres_fd > -1) {
  454. struct History history;
  455. Rast_close(mapres_fd);
  456. G_free(mapres_buf);
  457. Rast_short_history(output_res->answer, "raster", &history);
  458. Rast_command_history(&history);
  459. Rast_write_history(output_res->answer, &history);
  460. }
  461. if (mapest_fd > -1) {
  462. struct History history;
  463. Rast_close(mapest_fd);
  464. G_free(mapest_buf);
  465. Rast_short_history(output_est->answer, "raster", &history);
  466. Rast_command_history(&history);
  467. Rast_write_history(output_est->answer, &history);
  468. }
  469. exit(EXIT_SUCCESS);
  470. }