open_files.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /* PURPOSE: opening input rasters and creating segmentation files */
  2. #include <stdlib.h>
  3. #include <grass/gis.h>
  4. #include <grass/glocale.h>
  5. #include <grass/imagery.h>
  6. #include <grass/segment.h> /* segmentation library */
  7. #include "iseg.h"
  8. static int load_seeds(struct globals *, int, int, int);
  9. static int read_seed(struct globals *, SEGMENT *, struct rc *, int);
  10. static int manage_memory(int, int, struct globals *);
  11. int open_files(struct globals *globals)
  12. {
  13. struct Ref Ref; /* group reference list */
  14. int *in_fd, bounds_fd, is_null;
  15. int n, row, col, srows, scols, inlen, outlen, nseg;
  16. DCELL **inbuf; /* buffers to store lines from each of the imagery group rasters */
  17. CELL *boundsbuf, bounds_val;
  18. int have_bounds = 0;
  19. CELL s, id;
  20. struct Range range; /* min/max values of bounds map */
  21. struct FPRange *fp_range; /* min/max values of each input raster */
  22. DCELL *min, *max;
  23. struct ngbr_stats Ri, Rk;
  24. /*allocate memory for flags */
  25. globals->null_flag = flag_create(globals->nrows, globals->ncols);
  26. globals->candidate_flag = flag_create(globals->nrows, globals->ncols);
  27. flag_clear_all(globals->null_flag);
  28. flag_clear_all(globals->candidate_flag);
  29. G_debug(1, "Checking image group...");
  30. /* ****** open the input rasters ******* */
  31. if (!I_get_group_ref(globals->image_group, &Ref))
  32. G_fatal_error(_("Unable to read REF file for group <%s>"),
  33. globals->image_group);
  34. if (Ref.nfiles <= 0)
  35. G_fatal_error(_("Group <%s> contains no raster maps"),
  36. globals->image_group);
  37. /* Read Imagery Group */
  38. in_fd = G_malloc(Ref.nfiles * sizeof(int));
  39. inbuf = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *));
  40. fp_range = G_malloc(Ref.nfiles * sizeof(struct FPRange));
  41. min = G_malloc(Ref.nfiles * sizeof(DCELL));
  42. max = G_malloc(Ref.nfiles * sizeof(DCELL));
  43. G_debug(1, "Opening input rasters...");
  44. for (n = 0; n < Ref.nfiles; n++) {
  45. inbuf[n] = Rast_allocate_d_buf();
  46. in_fd[n] = Rast_open_old(Ref.file[n].name, Ref.file[n].mapset);
  47. }
  48. /* Get min/max values of each input raster for scaling */
  49. globals->max_diff = 0.;
  50. globals->nbands = Ref.nfiles;
  51. for (n = 0; n < Ref.nfiles; n++) {
  52. /* returns -1 on error, 2 on empty range, quiting either way. */
  53. if (Rast_read_fp_range(Ref.file[n].name, Ref.file[n].mapset, &fp_range[n]) != 1)
  54. G_fatal_error(_("No min/max found in raster map <%s>"),
  55. Ref.file[n].name);
  56. Rast_get_fp_range_min_max(&(fp_range[n]), &min[n], &max[n]);
  57. G_debug(1, "Range for layer %d: min = %f, max = %f",
  58. n, min[n], max[n]);
  59. }
  60. if (globals->weighted == FALSE)
  61. globals->max_diff = Ref.nfiles;
  62. else {
  63. /* max difference with selected similarity method */
  64. Ri.mean = max;
  65. Rk.mean = min;
  66. globals->max_diff = 1;
  67. globals->max_diff = (*globals->calculate_similarity) (&Ri, &Rk, globals);
  68. }
  69. /* ********** find out file segmentation size ************ */
  70. G_debug(1, "Calculate temp file sizes...");
  71. /* size of each element to be stored */
  72. inlen = sizeof(DCELL) * Ref.nfiles;
  73. outlen = sizeof(CELL);
  74. G_debug(1, "data element size, in: %d , out: %d ", inlen, outlen);
  75. globals->datasize = sizeof(double) * globals->nbands;
  76. /* count non-null cells */
  77. globals->notnullcells = (long)globals->nrows * globals->ncols;
  78. for (row = 0; row < globals->nrows; row++) {
  79. for (n = 0; n < Ref.nfiles; n++) {
  80. Rast_get_d_row(in_fd[n], inbuf[n], row);
  81. }
  82. for (col = 0; col < globals->ncols; col++) {
  83. is_null = 0; /*Assume there is data */
  84. for (n = 0; n < Ref.nfiles; n++) {
  85. if (Rast_is_d_null_value(&inbuf[n][col])) {
  86. is_null = 1;
  87. }
  88. }
  89. if (is_null) {
  90. globals->notnullcells--;
  91. FLAG_SET(globals->null_flag, row, col);
  92. }
  93. }
  94. }
  95. if (globals->notnullcells < 2)
  96. G_fatal_error(_("Insufficient number of non-NULL cells in current region"));
  97. /* segment lib segment size */
  98. srows = 64;
  99. scols = 64;
  100. nseg = manage_memory(srows, scols, globals);
  101. /* create segment structures */
  102. if (segment_open
  103. (&globals->bands_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
  104. scols, inlen, nseg) != 1)
  105. G_fatal_error("Unable to create input temporary files");
  106. if (segment_open
  107. (&globals->rid_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
  108. scols, outlen, nseg * 2) != 1)
  109. G_fatal_error("Unable to create input temporary files");
  110. /* load input bands to segment structure */
  111. if (Ref.nfiles > 1)
  112. G_message(_("Loading input bands..."));
  113. else
  114. G_message(_("Loading input band..."));
  115. globals->bands_val = (double *)G_malloc(inlen);
  116. globals->second_val = (double *)G_malloc(inlen);
  117. /* initial segment ID */
  118. s = 1;
  119. globals->row_min = globals->nrows;
  120. globals->row_max = 0;
  121. globals->col_min = globals->ncols;
  122. globals->col_max = 0;
  123. for (row = 0; row < globals->nrows; row++) {
  124. G_percent(row, globals->nrows, 4);
  125. for (n = 0; n < Ref.nfiles; n++) {
  126. Rast_get_d_row(in_fd[n], inbuf[n], row);
  127. }
  128. for (col = 0; col < globals->ncols; col++) {
  129. is_null = 0; /*Assume there is data */
  130. for (n = 0; n < Ref.nfiles; n++) {
  131. globals->bands_val[n] = inbuf[n][col];
  132. if (Rast_is_d_null_value(&inbuf[n][col])) {
  133. is_null = 1;
  134. }
  135. else {
  136. if (globals->weighted == FALSE)
  137. /* scaled version */
  138. globals->bands_val[n] = (inbuf[n][col] - min[n]) / (max[n] - min[n]);
  139. }
  140. }
  141. if (segment_put(&globals->bands_seg,
  142. (void *)globals->bands_val, row, col) != 1)
  143. G_fatal_error(_("Unable to write to temporary file"));
  144. if (!is_null) {
  145. if (!globals->seeds) {
  146. /* sequentially number all cells with a unique segment ID */
  147. id = s;
  148. s++;
  149. }
  150. /* get min/max row/col to narrow the processing window */
  151. if (globals->row_min > row)
  152. globals->row_min = row;
  153. if (globals->row_max < row)
  154. globals->row_max = row;
  155. if (globals->col_min > col)
  156. globals->col_min = col;
  157. if (globals->col_max < col)
  158. globals->col_max = col;
  159. }
  160. else {
  161. /* all input bands NULL */
  162. Rast_set_c_null_value(&id, 1);
  163. FLAG_SET(globals->null_flag, row, col);
  164. }
  165. if (!globals->seeds || is_null) {
  166. if (segment_put(&globals->rid_seg,
  167. (void *)&id, row, col) != 1)
  168. G_fatal_error(_("Unable to write to temporary file"));
  169. }
  170. }
  171. }
  172. G_debug(1, "nrows: %d, min row: %d, max row %d",
  173. globals->nrows, globals->row_min, globals->row_max);
  174. G_debug(1, "ncols: %d, min col: %d, max col %d",
  175. globals->ncols, globals->col_min, globals->col_max);
  176. globals->row_max++;
  177. globals->col_max++;
  178. globals->ncells = (long)(globals->row_max - globals->row_min) *
  179. (globals->col_max - globals->col_min);
  180. /* bounds/constraints */
  181. Rast_set_c_null_value(&globals->upper_bound, 1);
  182. Rast_set_c_null_value(&globals->lower_bound, 1);
  183. if (globals->bounds_map != NULL) {
  184. if (segment_open
  185. (&globals->bounds_seg, G_tempfile(), globals->nrows, globals->ncols,
  186. srows, scols, sizeof(CELL), nseg) != TRUE)
  187. G_fatal_error("Unable to create bounds temporary files");
  188. if (Rast_read_range(globals->bounds_map, globals->bounds_mapset, &range) != 1)
  189. G_fatal_error(_("No min/max found in raster map <%s>"),
  190. globals->bounds_map);
  191. Rast_get_range_min_max(&range, &globals->upper_bound,
  192. &globals->lower_bound);
  193. if (Rast_is_c_null_value(&globals->upper_bound) ||
  194. Rast_is_c_null_value(&globals->lower_bound)) {
  195. G_fatal_error(_("No min/max found in raster map <%s>"),
  196. globals->bounds_map);
  197. }
  198. bounds_fd = Rast_open_old(globals->bounds_map, globals->bounds_mapset);
  199. boundsbuf = Rast_allocate_c_buf();
  200. for (row = 0; row < globals->nrows; row++) {
  201. Rast_get_c_row(bounds_fd, boundsbuf, row);
  202. for (col = 0; col < globals->ncols; col++) {
  203. bounds_val = boundsbuf[col];
  204. if (FLAG_GET(globals->null_flag, row, col)) {
  205. Rast_set_c_null_value(&bounds_val, 1);
  206. }
  207. else {
  208. if (!Rast_is_c_null_value(&bounds_val)) {
  209. have_bounds = 1;
  210. if (globals->lower_bound > bounds_val)
  211. globals->lower_bound = bounds_val;
  212. if (globals->upper_bound < bounds_val)
  213. globals->upper_bound = bounds_val;
  214. }
  215. }
  216. if (segment_put(&globals->bounds_seg, &bounds_val, row, col) != 1)
  217. G_fatal_error(_("Unable to write to temporary file"));
  218. }
  219. }
  220. Rast_close(bounds_fd);
  221. G_free(boundsbuf);
  222. if (!have_bounds) {
  223. G_warning(_("There are no boundary constraints in '%s'"), globals->bounds_map);
  224. Rast_set_c_null_value(&globals->upper_bound, 1);
  225. Rast_set_c_null_value(&globals->lower_bound, 1);
  226. segment_close(&globals->bounds_seg);
  227. globals->bounds_map = NULL;
  228. globals->bounds_mapset = NULL;
  229. }
  230. }
  231. else {
  232. G_debug(1, "no boundary constraint supplied.");
  233. }
  234. /* other info */
  235. globals->candidate_count = 0; /* counter for remaining candidate pixels */
  236. /* Free memory */
  237. for (n = 0; n < Ref.nfiles; n++) {
  238. G_free(inbuf[n]);
  239. Rast_close(in_fd[n]);
  240. }
  241. globals->rs.sum = G_malloc(globals->datasize);
  242. globals->rs.mean = G_malloc(globals->datasize);
  243. globals->reg_tree = rgtree_create(globals->nbands, globals->datasize);
  244. globals->n_regions = s - 1;
  245. if (globals->seeds) {
  246. load_seeds(globals, srows, scols, nseg);
  247. }
  248. G_free(inbuf);
  249. G_free(in_fd);
  250. G_free(fp_range);
  251. G_free(min);
  252. G_free(max);
  253. return TRUE;
  254. }
  255. static int load_seeds(struct globals *globals, int srows, int scols, int nseg)
  256. {
  257. int row, col;
  258. SEGMENT seeds_seg;
  259. CELL *seeds_buf, seeds_val;
  260. int seeds_fd;
  261. int spos, sneg, have_seeds;
  262. struct rc Ri;
  263. G_debug(1, "load_seeds()");
  264. G_message(_("Loading seeds from '%s'"), globals->seeds);
  265. if (segment_open
  266. (&seeds_seg, G_tempfile(), globals->nrows, globals->ncols,
  267. srows, scols, sizeof(CELL), nseg) != TRUE)
  268. G_fatal_error("Unable to create bounds temporary files");
  269. seeds_fd = Rast_open_old(globals->seeds, "");
  270. seeds_buf = Rast_allocate_c_buf();
  271. have_seeds = 0;
  272. /* load seeds map to segment structure */
  273. for (row = 0; row < globals->nrows; row++) {
  274. Rast_get_c_row(seeds_fd, seeds_buf, row);
  275. for (col = 0; col < globals->ncols; col++) {
  276. if (FLAG_GET(globals->null_flag, row, col)) {
  277. Rast_set_c_null_value(&seeds_val, 1);
  278. }
  279. else {
  280. seeds_val = seeds_buf[col];
  281. if (!Rast_is_c_null_value(&seeds_val))
  282. have_seeds = 1;
  283. }
  284. if (segment_put(&seeds_seg, &seeds_val, row, col) != 1)
  285. G_fatal_error(_("Unable to write to temporary file"));
  286. }
  287. }
  288. if (!have_seeds) {
  289. G_warning(_("No seeds found in '%s'!"), globals->seeds);
  290. G_free(seeds_buf);
  291. Rast_close(seeds_fd);
  292. segment_close(&seeds_seg);
  293. return 0;
  294. }
  295. spos = 1;
  296. sneg = -1;
  297. /* convert seeds to regions */
  298. G_debug(1, "convert seeds to regions");
  299. Rast_set_c_null_value(&seeds_val, 1);
  300. for (row = 0; row < globals->nrows; row++) {
  301. Rast_get_c_row(seeds_fd, seeds_buf, row);
  302. for (col = 0; col < globals->ncols; col++) {
  303. if (!(FLAG_GET(globals->null_flag, row, col)) &&
  304. !(FLAG_GET(globals->candidate_flag, row, col))) {
  305. if (Rast_is_c_null_value(&(seeds_buf[col]))) {
  306. if (segment_put(&globals->rid_seg, &sneg, row, col) != 1)
  307. G_fatal_error(_("Unable to write to temporary file"));
  308. sneg--;
  309. }
  310. else {
  311. Ri.row = row;
  312. Ri.col = col;
  313. read_seed(globals, &seeds_seg, &Ri, spos);
  314. spos++;
  315. }
  316. }
  317. }
  318. }
  319. G_free(seeds_buf);
  320. Rast_close(seeds_fd);
  321. segment_close(&seeds_seg);
  322. globals->n_regions = spos - 1;
  323. flag_clear_all(globals->candidate_flag);
  324. return 1;
  325. }
  326. static int read_seed(struct globals *globals, SEGMENT *seeds_seg, struct rc *Ri, int new_id)
  327. {
  328. int n, i, Ri_id, Rk_id;
  329. struct rc ngbr_rc, next;
  330. struct rclist rilist;
  331. int neighbors[8][2];
  332. G_debug(4, "read_seed()");
  333. /* get Ri's segment ID from input seeds */
  334. segment_get(seeds_seg, &Ri_id, Ri->row, Ri->col);
  335. /* set new segment id */
  336. if (segment_put(&globals->rid_seg, &new_id, Ri->row, Ri->col) != 1)
  337. G_fatal_error(_("Unable to write to temporary file"));
  338. /* set candidate flag */
  339. FLAG_SET(globals->candidate_flag, Ri->row, Ri->col);
  340. /* initialize region stats */
  341. globals->rs.count = 1;
  342. globals->rs.id = new_id;
  343. segment_get(&globals->bands_seg, (void *)globals->bands_val,
  344. Ri->row, Ri->col);
  345. for (i = 0; i < globals->nbands; i++) {
  346. globals->rs.sum[i] = globals->bands_val[i];
  347. globals->rs.mean[i] = globals->bands_val[i];
  348. }
  349. /* go through seed, spreading outwards from head */
  350. rclist_init(&rilist);
  351. rclist_add(&rilist, Ri->row, Ri->col);
  352. while (rclist_drop(&rilist, &next)) {
  353. G_debug(5, "find_pixel_neighbors for row: %d , col %d",
  354. next.row, next.col);
  355. globals->find_neighbors(next.row, next.col, neighbors);
  356. for (n = 0; n < globals->nn; n++) {
  357. ngbr_rc.row = neighbors[n][0];
  358. ngbr_rc.col = neighbors[n][1];
  359. if (ngbr_rc.row < 0 || ngbr_rc.row >= globals->nrows ||
  360. ngbr_rc.col < 0 || ngbr_rc.col >= globals->ncols) {
  361. continue;
  362. }
  363. if (FLAG_GET(globals->null_flag, ngbr_rc.row, ngbr_rc.col)) {
  364. continue;
  365. }
  366. if (FLAG_GET(globals->candidate_flag, ngbr_rc.row, ngbr_rc.col)) {
  367. continue;
  368. }
  369. segment_get(seeds_seg, (void *) &Rk_id, ngbr_rc.row, ngbr_rc.col);
  370. G_debug(5, "Rk ID = %d Ri ID = %d", Rk_id, Ri_id);
  371. if (Rk_id != Ri_id) {
  372. continue;
  373. }
  374. /* set segment id */
  375. if (segment_put(&globals->rid_seg,
  376. &new_id, ngbr_rc.row, ngbr_rc.col) != 1)
  377. G_fatal_error(_("Unable to write to temporary file"));
  378. /* set candidate flag */
  379. FLAG_SET(globals->candidate_flag, ngbr_rc.row, ngbr_rc.col);
  380. /* add to list of cells to check */
  381. rclist_add(&rilist, ngbr_rc.row, ngbr_rc.col);
  382. /* update region stats */
  383. segment_get(&globals->bands_seg, (void *)globals->bands_val,
  384. ngbr_rc.row, ngbr_rc.col);
  385. for (i = 0; i < globals->nbands; i++) {
  386. globals->rs.sum[i] += globals->bands_val[i];
  387. }
  388. globals->rs.count++;
  389. }
  390. }
  391. if (rgtree_find(globals->reg_tree, &(globals->rs)) != NULL) {
  392. G_fatal_error(_("Segment %d is already registered!"), new_id);
  393. }
  394. /* insert into region tree */
  395. if (globals->rs.count >= globals->min_reg_size) {
  396. for (i = 0; i < globals->nbands; i++)
  397. globals->rs.mean[i] = globals->rs.sum[i] / globals->rs.count;
  398. rgtree_insert(globals->reg_tree, &(globals->rs));
  399. }
  400. else {
  401. update_band_vals(Ri->row, Ri->col, &(globals->rs), globals);
  402. }
  403. return 1;
  404. }
  405. static int manage_memory(int srows, int scols, struct globals *globals)
  406. {
  407. double reg_size_mb, segs_mb;
  408. int reg_size_count, nseg, nseg_total;
  409. /* minimum region size to store in search tree */
  410. reg_size_mb = 2 * globals->datasize + /* mean, sum */
  411. 2 * sizeof(int) + /* id, count */
  412. sizeof(unsigned char) +
  413. 2 * sizeof(struct REG_NODE *);
  414. reg_size_mb /= (1024. * 1024.);
  415. /* put aside some memory for segment structures */
  416. segs_mb = globals->mb * 0.1;
  417. if (segs_mb > 10)
  418. segs_mb = 10;
  419. /* calculate number of region stats that can be kept in memory */
  420. reg_size_count = (globals->mb - segs_mb) / reg_size_mb;
  421. globals->min_reg_size = 3;
  422. if (reg_size_count < (double) globals->notnullcells / globals->min_reg_size) {
  423. globals->min_reg_size = (double) globals->notnullcells / reg_size_count;
  424. }
  425. else {
  426. reg_size_count = (double) globals->notnullcells / globals->min_reg_size;
  427. /* recalculate segs_mb */
  428. segs_mb = globals->mb - reg_size_count * reg_size_mb;
  429. }
  430. G_verbose_message(_("Regions with at least %d cells are stored in memory"),
  431. globals->min_reg_size);
  432. /* calculate number of segments in memory */
  433. if (globals->bounds_map != NULL) {
  434. /* input bands, segment ids, bounds map */
  435. nseg = (1024. * 1024. * segs_mb) /
  436. (sizeof(DCELL) * globals->nbands * srows * scols +
  437. sizeof(CELL) * 4 * srows * scols);
  438. }
  439. else {
  440. /* input bands, segment ids, bounds map */
  441. nseg = (1024. * 1024. * segs_mb) /
  442. (sizeof(DCELL) * globals->nbands * srows * scols +
  443. sizeof(CELL) * 2 * srows * scols);
  444. }
  445. nseg_total = (globals->nrows / srows + (globals->nrows % srows > 0)) *
  446. (globals->ncols / scols + (globals->ncols % scols > 0));
  447. if (nseg > nseg_total)
  448. nseg = nseg_total;
  449. G_debug(1, "current region: %d rows, %d cols", globals->nrows, globals->ncols);
  450. G_debug(1, "segmented to tiles with size: %d rows, %d cols", srows,
  451. scols);
  452. G_verbose_message(_("Number of segments in memory: %d of %d total"),
  453. nseg, nseg_total);
  454. return nseg;
  455. }