main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. G_add_keyword(_("regression"));
  110. module->description =
  111. _("Calculates multiple linear regression from raster maps.");
  112. /* Define the different options */
  113. input_mapx = G_define_standard_option(G_OPT_R_INPUTS);
  114. input_mapx->key = "mapx";
  115. input_mapx->description = (_("Map for x coefficient"));
  116. input_mapy = G_define_standard_option(G_OPT_R_INPUT);
  117. input_mapy->key = "mapy";
  118. input_mapy->description = (_("Map for y coefficient"));
  119. output_res = G_define_standard_option(G_OPT_R_OUTPUT);
  120. output_res->key = "residuals";
  121. output_res->required = NO;
  122. output_res->description = (_("Map to store residuals"));
  123. output_est = G_define_standard_option(G_OPT_R_OUTPUT);
  124. output_est->key = "estimates";
  125. output_est->required = NO;
  126. output_est->description = (_("Map to store estimates"));
  127. output_opt = G_define_standard_option(G_OPT_F_OUTPUT);
  128. output_opt->key = "output";
  129. output_opt->required = NO;
  130. output_opt->description =
  131. (_("ASCII file for storing regression coefficients (output to screen if file not specified)."));
  132. shell_style = G_define_flag();
  133. shell_style->key = 'g';
  134. shell_style->description = _("Print in shell script style");
  135. if (G_parser(argc, argv))
  136. exit(EXIT_FAILURE);
  137. name = output_opt->answer;
  138. if (name != NULL && strcmp(name, "-") != 0) {
  139. if (NULL == freopen(name, "w", stdout)) {
  140. G_fatal_error(_("Unable to open file <%s> for writing"), name);
  141. }
  142. }
  143. G_get_window(&region);
  144. rows = region.rows;
  145. cols = region.cols;
  146. /* count x maps */
  147. for (i = 0; input_mapx->answers[i]; i++);
  148. n_predictors = i;
  149. /* allocate memory for x maps */
  150. mapx_fd = (int *)G_malloc(n_predictors * sizeof(int));
  151. sumX = (double *)G_malloc(n_predictors * sizeof(double));
  152. sumsqX = (double *)G_malloc(n_predictors * sizeof(double));
  153. sumXY = (double *)G_malloc(n_predictors * sizeof(double));
  154. SSerr_without = (double *)G_malloc(n_predictors * sizeof(double));
  155. meanX = (double *)G_malloc(n_predictors * sizeof(double));
  156. varX = (double *)G_malloc(n_predictors * sizeof(double));
  157. sdX = (double *)G_malloc(n_predictors * sizeof(double));
  158. mapx_buf = (DCELL **)G_malloc(n_predictors * sizeof(DCELL *));
  159. mapx_val = (DCELL *)G_malloc((n_predictors + 1) * sizeof(DCELL));
  160. /* ordinary least squares */
  161. m = NULL;
  162. m_all = (struct MATRIX *)G_malloc((n_predictors + 1) * sizeof(struct MATRIX));
  163. a = (double **)G_malloc((n_predictors + 1) * sizeof(double *));
  164. B = (double **)G_malloc((n_predictors + 1) * sizeof(double *));
  165. m = &(m_all[0]);
  166. m->n = n_predictors + 1;
  167. m->v = (double *)G_malloc(m->n * m->n * sizeof(double));
  168. a[0] = (double *)G_malloc(m->n * sizeof(double));
  169. B[0] = (double *)G_malloc(m->n * sizeof(double));
  170. for (i = 0; i < m->n; i++) {
  171. for (j = i; j < m->n; j++)
  172. M(m, i, j) = 0.0;
  173. a[0][i] = 0.0;
  174. B[0][i] = 0.0;
  175. }
  176. for (k = 1; k <= n_predictors; k++) {
  177. m = &(m_all[k]);
  178. m->n = n_predictors;
  179. m->v = (double *)G_malloc(m->n * m->n * sizeof(double));
  180. a[k] = (double *)G_malloc(m->n * sizeof(double));
  181. B[k] = (double *)G_malloc(m->n * sizeof(double));
  182. for (i = 0; i < m->n; i++) {
  183. for (j = i; j < m->n; j++)
  184. M(m, i, j) = 0.0;
  185. a[k][i] = 0.0;
  186. B[k][i] = 0.0;
  187. }
  188. }
  189. /* open maps */
  190. G_debug(1, "open maps");
  191. for (i = 0; i < n_predictors; i++) {
  192. mapx_fd[i] = Rast_open_old(input_mapx->answers[i], "");
  193. }
  194. mapy_fd = Rast_open_old(input_mapy->answer, "");
  195. for (i = 0; i < n_predictors; i++)
  196. mapx_buf[i] = Rast_allocate_d_buf();
  197. mapy_buf = Rast_allocate_d_buf();
  198. for (i = 0; i < n_predictors; i++) {
  199. sumX[i] = sumsqX[i] = sumXY[i] = 0.0;
  200. meanX[i] = varX[i] = sdX[i] = 0.0;
  201. SSerr_without[i] = 0.0;
  202. }
  203. sumY = sumsqY = meanY = varY = sdY = 0.0;
  204. sumYest = meanYest = varYest = sdYest = 0.0;
  205. meanYres = varYres = sdYres = 0.0;
  206. /* read input maps */
  207. G_message(_("First pass..."));
  208. n_valid = 0;
  209. mapx_val[0] = 1.0;
  210. for (r = 0; r < rows; r++) {
  211. G_percent(r, rows, 2);
  212. for (i = 0; i < n_predictors; i++)
  213. Rast_get_d_row(mapx_fd[i], mapx_buf[i], r);
  214. Rast_get_d_row(mapy_fd, mapy_buf, r);
  215. for (c = 0; c < cols; c++) {
  216. int isnull = 0;
  217. for (i = 0; i < n_predictors; i++) {
  218. mapx_val[i + 1] = mapx_buf[i][c];
  219. if (Rast_is_d_null_value(&(mapx_val[i + 1]))) {
  220. isnull = 1;
  221. break;
  222. }
  223. }
  224. if (isnull)
  225. continue;
  226. mapy_val = mapy_buf[c];
  227. if (Rast_is_d_null_value(&mapy_val))
  228. continue;
  229. for (i = 0; i <= n_predictors; i++) {
  230. double val1 = mapx_val[i];
  231. for (j = i; j <= n_predictors; j++) {
  232. double val2 = mapx_val[j];
  233. m = &(m_all[0]);
  234. M(m, i, j) += val1 * val2;
  235. /* linear model without predictor k */
  236. for (k = 1; k <= n_predictors; k++) {
  237. if (k != i && k != j) {
  238. int i2 = k > i ? i : i - 1;
  239. int j2 = k > j ? j : j - 1;
  240. m = &(m_all[k]);
  241. M(m, i2, j2) += val1 * val2;
  242. }
  243. }
  244. }
  245. a[0][i] += mapy_val * val1;
  246. for (k = 1; k <= n_predictors; k++) {
  247. if (k != i) {
  248. int i2 = k > i ? i : i - 1;
  249. a[k][i2] += mapy_val * val1;
  250. }
  251. }
  252. if (i > 0) {
  253. sumX[i - 1] += val1;
  254. sumsqX[i - 1] += val1 * val1;
  255. sumXY[i - 1] += val1 * mapy_val;
  256. }
  257. }
  258. sumY += mapy_val;
  259. sumsqY += mapy_val * mapy_val;
  260. count++;
  261. }
  262. }
  263. G_percent(rows, rows, 2);
  264. if (count < n_predictors + 1)
  265. G_fatal_error(_("Not enough valid cells available"));
  266. for (k = 0; k <= n_predictors; k++) {
  267. m = &(m_all[k]);
  268. /* TRANSPOSE VALUES IN UPPER HALF OF M TO OTHER HALF */
  269. for (i = 1; i < m->n; i++)
  270. for (j = 0; j < i; j++)
  271. M(m, i, j) = M(m, j, i);
  272. if (!solvemat(m, a[k], B[k])) {
  273. for (i = 0; i <= n_predictors; i++) {
  274. fprintf(stdout, "b%d=0.0\n", i);
  275. }
  276. G_fatal_error(_("Multiple regression failed"));
  277. }
  278. }
  279. /* second pass */
  280. G_message(_("Second pass..."));
  281. /* residuals output */
  282. if (output_res->answer) {
  283. mapres_fd = Rast_open_new(output_res->answer, DCELL_TYPE);
  284. mapres_buf = Rast_allocate_d_buf();
  285. }
  286. else {
  287. mapres_fd = -1;
  288. mapres_buf = NULL;
  289. }
  290. /* estimates output */
  291. if (output_est->answer) {
  292. mapest_fd = Rast_open_new(output_est->answer, DCELL_TYPE);
  293. mapest_buf = Rast_allocate_d_buf();
  294. }
  295. else {
  296. mapest_fd = -1;
  297. mapest_buf = NULL;
  298. }
  299. for (i = 0; i < n_predictors; i++)
  300. meanX[i] = sumX[i] / count;
  301. meanY = sumY / count;
  302. SStot = SSerr = SSreg = 0.0;
  303. for (r = 0; r < rows; r++) {
  304. G_percent(r, rows, 2);
  305. for (i = 0; i < n_predictors; i++)
  306. Rast_get_d_row(mapx_fd[i], mapx_buf[i], r);
  307. Rast_get_d_row(mapy_fd, mapy_buf, r);
  308. if (mapres_buf)
  309. Rast_set_d_null_value(mapres_buf, cols);
  310. if (mapest_buf)
  311. Rast_set_d_null_value(mapest_buf, cols);
  312. for (c = 0; c < cols; c++) {
  313. int isnull = 0;
  314. for (i = 0; i < n_predictors; i++) {
  315. mapx_val[i + 1] = mapx_buf[i][c];
  316. if (Rast_is_d_null_value(&(mapx_val[i + 1]))) {
  317. isnull = 1;
  318. break;
  319. }
  320. }
  321. if (isnull)
  322. continue;
  323. yest = 0.0;
  324. for (i = 0; i <= n_predictors; i++) {
  325. yest += B[0][i] * mapx_val[i];
  326. }
  327. if (mapest_buf)
  328. mapest_buf[c] = yest;
  329. mapy_val = mapy_buf[c];
  330. if (Rast_is_d_null_value(&mapy_val))
  331. continue;
  332. yres = mapy_val - yest;
  333. if (mapres_buf)
  334. mapres_buf[c] = yres;
  335. SStot += (mapy_val - meanY) * (mapy_val - meanY);
  336. SSreg += (yest - meanY) * (yest - meanY);
  337. SSerr += yres * yres;
  338. for (k = 1; k <= n_predictors; k++) {
  339. double yesti = 0.0;
  340. double yresi;
  341. /* linear model without predictor k */
  342. for (i = 0; i <= n_predictors; i++) {
  343. if (i != k) {
  344. j = k > i ? i : i - 1;
  345. yesti += B[k][j] * mapx_val[i];
  346. }
  347. }
  348. yresi = mapy_val - yesti;
  349. /* linear model without predictor k */
  350. SSerr_without[k - 1] += yresi * yresi;
  351. varX[k - 1] = (mapx_val[k] - meanX[k - 1]) * (mapx_val[k] - meanX[k - 1]);
  352. }
  353. }
  354. if (mapres_buf)
  355. Rast_put_d_row(mapres_fd, mapres_buf);
  356. if (mapest_buf)
  357. Rast_put_d_row(mapest_fd, mapest_buf);
  358. }
  359. G_percent(rows, rows, 2);
  360. fprintf(stdout, "n=%d\n", count);
  361. /* coefficient of determination aka R squared */
  362. Rsq = 1 - (SSerr / SStot);
  363. fprintf(stdout, "Rsq=%f\n", Rsq);
  364. /* adjusted coefficient of determination */
  365. Rsqadj = 1 - ((SSerr * (count - 1)) / (SStot * (count - n_predictors - 1)));
  366. fprintf(stdout, "Rsqadj=%f\n", Rsqadj);
  367. /* F statistic */
  368. /* F = ((SStot - SSerr) / (n_predictors)) / (SSerr / (count - n_predictors));
  369. * , or: */
  370. F = ((SStot - SSerr) * (count - n_predictors - 1)) / (SSerr * (n_predictors));
  371. fprintf(stdout, "F=%f\n", F);
  372. i = 0;
  373. /* constant aka estimate for intercept in R */
  374. fprintf(stdout, "b%d=%f\n", i, B[0][i]);
  375. /* t score for R squared of the full model, unused */
  376. t = sqrt(Rsq) * sqrt((count - 2) / (1 - Rsq));
  377. /*
  378. fprintf(stdout, "t%d=%f\n", i, t);
  379. */
  380. /* AIC, corrected AIC, and BIC information criteria for the full model */
  381. AIC = count * log(SSerr / count) + 2 * (n_predictors + 1);
  382. fprintf(stdout, "AIC=%f\n", AIC);
  383. AICc = AIC + (2 * n_predictors * (n_predictors + 1)) / (count - n_predictors - 1);
  384. fprintf(stdout, "AICc=%f\n", AICc);
  385. BIC = count * log(SSerr / count) + log(count) * (n_predictors + 1);
  386. fprintf(stdout, "BIC=%f\n", BIC);
  387. /* error variance of the model, identical to R */
  388. SE = SSerr / (count - n_predictors - 1);
  389. /*
  390. fprintf(stdout, "SE=%f\n", SE);
  391. fprintf(stdout, "SSerr=%f\n", SSerr);
  392. */
  393. for (i = 0; i < n_predictors; i++) {
  394. fprintf(stdout, "\npredictor%d=%s\n", i + 1, input_mapx->answers[i]);
  395. fprintf(stdout, "b%d=%f\n", i + 1, B[0][i + 1]);
  396. if (n_predictors > 1) {
  397. double Rsqi, SEi, sumsqX_corr;
  398. /* corrected sum of squares for predictor [i] */
  399. sumsqX_corr = sumsqX[i] - sumX[i] * sumX[i] / (count - n_predictors - 1);
  400. /* standard error SE for predictor [i] */
  401. /* SE[i] with only one predictor: sqrt(SE / sumsqX_corr)
  402. * this does not work with more than one predictor */
  403. /* in R, SEi is sqrt(diag(R) * resvar) with
  404. * R = ???
  405. * resvar = rss / rdf = SE global
  406. * rss = sum of squares of the residuals
  407. * rdf = residual degrees of freedom = count - n_predictors - 1 */
  408. SEi = sqrt(SE / (Rsq * sumsqX_corr));
  409. /*
  410. fprintf(stdout, "SE%d=%f\n", i + 1, SEi);
  411. */
  412. /* Sum of squares for predictor [i] */
  413. /*
  414. fprintf(stdout, "SSerr%d=%f\n", i + 1, SSerr_without[i] - SSerr);
  415. */
  416. /* R squared of the model without predictor [i] */
  417. /* Rsqi = 1 - SSerr_without[i] / SStot; */
  418. /* the additional amount of variance explained
  419. * when including predictor [i] :
  420. * Rsq - Rsqi */
  421. Rsqi = (SSerr_without[i] - SSerr) / SStot;
  422. fprintf(stdout, "Rsq%d=%f\n", i + 1, Rsqi);
  423. /* t score for Student's t distribution, unused */
  424. t = (B[0][i + 1]) / SEi;
  425. /*
  426. fprintf(stdout, "t%d=%f\n", i + 1, t);
  427. */
  428. /* F score for Fisher's F distribution
  429. * here: F score to test if including predictor [i]
  430. * yields a significant improvement
  431. * after Lothar Sachs, Angewandte Statistik:
  432. * F = (Rsq - Rsqi) * (count - n_predictors - 1) / (1 - Rsq) */
  433. /* same like Sumsq / SE */
  434. /* same like (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1) */
  435. /* same like R-stats when entered in R-stats as last predictor */
  436. F = (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1);
  437. fprintf(stdout, "F%d=%f\n", i + 1, F);
  438. /* AIC, corrected AIC, and BIC information criteria for
  439. * the model without predictor [i] */
  440. AIC = count * log(SSerr_without[i] / count) + 2 * (n_predictors);
  441. fprintf(stdout, "AIC%d=%f\n", i + 1, AIC);
  442. AICc = AIC + (2 * (n_predictors - 1) * n_predictors) / (count - n_predictors - 2);
  443. fprintf(stdout, "AICc%d=%f\n", i + 1, AICc);
  444. BIC = count * log(SSerr_without[i] / count) + (n_predictors - 1) * log(count);
  445. fprintf(stdout, "BIC%d=%f\n", i + 1, BIC);
  446. }
  447. }
  448. for (i = 0; i < n_predictors; i++) {
  449. Rast_close(mapx_fd[i]);
  450. G_free(mapx_buf[i]);
  451. }
  452. Rast_close(mapy_fd);
  453. G_free(mapy_buf);
  454. if (mapres_fd > -1) {
  455. struct History history;
  456. Rast_close(mapres_fd);
  457. G_free(mapres_buf);
  458. Rast_short_history(output_res->answer, "raster", &history);
  459. Rast_command_history(&history);
  460. Rast_write_history(output_res->answer, &history);
  461. }
  462. if (mapest_fd > -1) {
  463. struct History history;
  464. Rast_close(mapest_fd);
  465. G_free(mapest_buf);
  466. Rast_short_history(output_est->answer, "raster", &history);
  467. Rast_command_history(&history);
  468. Rast_write_history(output_est->answer, &history);
  469. }
  470. exit(EXIT_SUCCESS);
  471. }