open_files.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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, quitting 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. G_verbose_message(_("Non-NULL cells: %ld"), globals->notnullcells);
  96. if (globals->notnullcells < 2)
  97. G_fatal_error(_("Insufficient number of non-NULL cells in current region"));
  98. /* segment lib segment size */
  99. srows = 64;
  100. scols = 64;
  101. nseg = manage_memory(srows, scols, globals);
  102. /* create segment structures */
  103. if (segment_open
  104. (&globals->bands_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
  105. scols, inlen, nseg) != 1)
  106. G_fatal_error("Unable to create input temporary files");
  107. if (segment_open
  108. (&globals->rid_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
  109. scols, outlen, nseg * 2) != 1)
  110. G_fatal_error("Unable to create input temporary files");
  111. /* load input bands to segment structure */
  112. if (Ref.nfiles > 1)
  113. G_message(_("Loading input bands..."));
  114. else
  115. G_message(_("Loading input band..."));
  116. globals->bands_val = (double *)G_malloc(inlen);
  117. globals->second_val = (double *)G_malloc(inlen);
  118. /* initial segment ID */
  119. s = 1;
  120. globals->row_min = globals->nrows;
  121. globals->row_max = 0;
  122. globals->col_min = globals->ncols;
  123. globals->col_max = 0;
  124. for (row = 0; row < globals->nrows; row++) {
  125. G_percent(row, globals->nrows, 4);
  126. for (n = 0; n < Ref.nfiles; n++) {
  127. Rast_get_d_row(in_fd[n], inbuf[n], row);
  128. }
  129. for (col = 0; col < globals->ncols; col++) {
  130. is_null = 0; /*Assume there is data */
  131. for (n = 0; n < Ref.nfiles; n++) {
  132. globals->bands_val[n] = inbuf[n][col];
  133. if (Rast_is_d_null_value(&inbuf[n][col])) {
  134. is_null = 1;
  135. }
  136. else {
  137. if (globals->weighted == FALSE)
  138. /* scaled version */
  139. globals->bands_val[n] = (inbuf[n][col] - min[n]) / (max[n] - min[n]);
  140. }
  141. }
  142. if (segment_put(&globals->bands_seg,
  143. (void *)globals->bands_val, row, col) != 1)
  144. G_fatal_error(_("Unable to write to temporary file"));
  145. if (!is_null) {
  146. if (!globals->seeds) {
  147. /* sequentially number all cells with a unique segment ID */
  148. id = s;
  149. s++;
  150. }
  151. /* get min/max row/col to narrow the processing window */
  152. if (globals->row_min > row)
  153. globals->row_min = row;
  154. if (globals->row_max < row)
  155. globals->row_max = row;
  156. if (globals->col_min > col)
  157. globals->col_min = col;
  158. if (globals->col_max < col)
  159. globals->col_max = col;
  160. }
  161. else {
  162. /* all input bands NULL */
  163. Rast_set_c_null_value(&id, 1);
  164. FLAG_SET(globals->null_flag, row, col);
  165. }
  166. if (!globals->seeds || is_null) {
  167. if (segment_put(&globals->rid_seg,
  168. (void *)&id, row, col) != 1)
  169. G_fatal_error(_("Unable to write to temporary file"));
  170. }
  171. }
  172. }
  173. G_percent(1, 1, 1);
  174. G_debug(1, "nrows: %d, min row: %d, max row %d",
  175. globals->nrows, globals->row_min, globals->row_max);
  176. G_debug(1, "ncols: %d, min col: %d, max col %d",
  177. globals->ncols, globals->col_min, globals->col_max);
  178. globals->row_max++;
  179. globals->col_max++;
  180. globals->ncells = (long)(globals->row_max - globals->row_min) *
  181. (globals->col_max - globals->col_min);
  182. /* bounds/constraints */
  183. Rast_set_c_null_value(&globals->upper_bound, 1);
  184. Rast_set_c_null_value(&globals->lower_bound, 1);
  185. if (globals->bounds_map != NULL) {
  186. if (segment_open
  187. (&globals->bounds_seg, G_tempfile(), globals->nrows, globals->ncols,
  188. srows, scols, sizeof(CELL), nseg) != TRUE)
  189. G_fatal_error("Unable to create bounds temporary files");
  190. if (Rast_read_range(globals->bounds_map, globals->bounds_mapset, &range) != 1)
  191. G_fatal_error(_("No min/max found in raster map <%s>"),
  192. globals->bounds_map);
  193. Rast_get_range_min_max(&range, &globals->upper_bound,
  194. &globals->lower_bound);
  195. if (Rast_is_c_null_value(&globals->upper_bound) ||
  196. Rast_is_c_null_value(&globals->lower_bound)) {
  197. G_fatal_error(_("No min/max found in raster map <%s>"),
  198. globals->bounds_map);
  199. }
  200. bounds_fd = Rast_open_old(globals->bounds_map, globals->bounds_mapset);
  201. boundsbuf = Rast_allocate_c_buf();
  202. for (row = 0; row < globals->nrows; row++) {
  203. Rast_get_c_row(bounds_fd, boundsbuf, row);
  204. for (col = 0; col < globals->ncols; col++) {
  205. bounds_val = boundsbuf[col];
  206. if (FLAG_GET(globals->null_flag, row, col)) {
  207. Rast_set_c_null_value(&bounds_val, 1);
  208. }
  209. else {
  210. if (!Rast_is_c_null_value(&bounds_val)) {
  211. have_bounds = 1;
  212. if (globals->lower_bound > bounds_val)
  213. globals->lower_bound = bounds_val;
  214. if (globals->upper_bound < bounds_val)
  215. globals->upper_bound = bounds_val;
  216. }
  217. }
  218. if (segment_put(&globals->bounds_seg, &bounds_val, row, col) != 1)
  219. G_fatal_error(_("Unable to write to temporary file"));
  220. }
  221. }
  222. Rast_close(bounds_fd);
  223. G_free(boundsbuf);
  224. if (!have_bounds) {
  225. G_warning(_("There are no boundary constraints in '%s'"), globals->bounds_map);
  226. Rast_set_c_null_value(&globals->upper_bound, 1);
  227. Rast_set_c_null_value(&globals->lower_bound, 1);
  228. segment_close(&globals->bounds_seg);
  229. globals->bounds_map = NULL;
  230. globals->bounds_mapset = NULL;
  231. }
  232. }
  233. else {
  234. G_debug(1, "no boundary constraint supplied.");
  235. }
  236. /* other info */
  237. globals->candidate_count = 0; /* counter for remaining candidate pixels */
  238. /* Free memory */
  239. for (n = 0; n < Ref.nfiles; n++) {
  240. G_free(inbuf[n]);
  241. Rast_close(in_fd[n]);
  242. }
  243. globals->rs.sum = G_malloc(globals->datasize);
  244. globals->rs.mean = G_malloc(globals->datasize);
  245. globals->reg_tree = rgtree_create(globals->nbands, globals->datasize);
  246. globals->n_regions = s - 1;
  247. if (globals->seeds) {
  248. load_seeds(globals, srows, scols, nseg);
  249. }
  250. G_debug(1, "Number of initial regions: %d", globals->n_regions);
  251. G_free(inbuf);
  252. G_free(in_fd);
  253. G_free(fp_range);
  254. G_free(min);
  255. G_free(max);
  256. return TRUE;
  257. }
  258. static int load_seeds(struct globals *globals, int srows, int scols, int nseg)
  259. {
  260. int row, col;
  261. SEGMENT seeds_seg;
  262. CELL *seeds_buf, seeds_val;
  263. int seeds_fd;
  264. int spos, sneg, have_seeds;
  265. struct rc Ri;
  266. G_debug(1, "load_seeds()");
  267. G_message(_("Loading seeds from '%s'"), globals->seeds);
  268. if (segment_open
  269. (&seeds_seg, G_tempfile(), globals->nrows, globals->ncols,
  270. srows, scols, sizeof(CELL), nseg) != TRUE)
  271. G_fatal_error("Unable to create bounds temporary files");
  272. seeds_fd = Rast_open_old(globals->seeds, "");
  273. seeds_buf = Rast_allocate_c_buf();
  274. have_seeds = 0;
  275. /* load seeds map to segment structure */
  276. for (row = 0; row < globals->nrows; row++) {
  277. Rast_get_c_row(seeds_fd, seeds_buf, row);
  278. for (col = 0; col < globals->ncols; col++) {
  279. if (FLAG_GET(globals->null_flag, row, col)) {
  280. Rast_set_c_null_value(&seeds_val, 1);
  281. }
  282. else {
  283. seeds_val = seeds_buf[col];
  284. if (!Rast_is_c_null_value(&seeds_val))
  285. have_seeds = 1;
  286. }
  287. if (segment_put(&seeds_seg, &seeds_val, row, col) != 1)
  288. G_fatal_error(_("Unable to write to temporary file"));
  289. }
  290. }
  291. if (!have_seeds) {
  292. G_warning(_("No seeds found in '%s'!"), globals->seeds);
  293. G_free(seeds_buf);
  294. Rast_close(seeds_fd);
  295. segment_close(&seeds_seg);
  296. return 0;
  297. }
  298. spos = 1;
  299. sneg = -1;
  300. /* convert seeds to regions */
  301. G_debug(1, "convert seeds to regions");
  302. Rast_set_c_null_value(&seeds_val, 1);
  303. for (row = 0; row < globals->nrows; row++) {
  304. Rast_get_c_row(seeds_fd, seeds_buf, row);
  305. for (col = 0; col < globals->ncols; col++) {
  306. if (!(FLAG_GET(globals->null_flag, row, col)) &&
  307. !(FLAG_GET(globals->candidate_flag, row, col))) {
  308. if (Rast_is_c_null_value(&(seeds_buf[col]))) {
  309. if (segment_put(&globals->rid_seg, &sneg, row, col) != 1)
  310. G_fatal_error(_("Unable to write to temporary file"));
  311. sneg--;
  312. globals->n_regions--;
  313. }
  314. else {
  315. Ri.row = row;
  316. Ri.col = col;
  317. read_seed(globals, &seeds_seg, &Ri, spos);
  318. spos++;
  319. }
  320. }
  321. }
  322. }
  323. G_free(seeds_buf);
  324. Rast_close(seeds_fd);
  325. segment_close(&seeds_seg);
  326. globals->n_regions = spos - 1;
  327. flag_clear_all(globals->candidate_flag);
  328. return 1;
  329. }
  330. static int read_seed(struct globals *globals, SEGMENT *seeds_seg, struct rc *Ri, int new_id)
  331. {
  332. int n, i, Ri_id, Rk_id;
  333. struct rc ngbr_rc, next;
  334. struct rclist rilist;
  335. int neighbors[8][2];
  336. G_debug(4, "read_seed()");
  337. /* get Ri's segment ID from input seeds */
  338. segment_get(seeds_seg, &Ri_id, Ri->row, Ri->col);
  339. /* set new segment id */
  340. if (segment_put(&globals->rid_seg, &new_id, Ri->row, Ri->col) != 1)
  341. G_fatal_error(_("Unable to write to temporary file"));
  342. /* set candidate flag */
  343. FLAG_SET(globals->candidate_flag, Ri->row, Ri->col);
  344. /* initialize region stats */
  345. globals->rs.count = 1;
  346. globals->rs.id = new_id;
  347. segment_get(&globals->bands_seg, (void *)globals->bands_val,
  348. Ri->row, Ri->col);
  349. for (i = 0; i < globals->nbands; i++) {
  350. globals->rs.sum[i] = globals->bands_val[i];
  351. globals->rs.mean[i] = globals->bands_val[i];
  352. }
  353. /* go through seed, spreading outwards from head */
  354. rclist_init(&rilist);
  355. rclist_add(&rilist, Ri->row, Ri->col);
  356. while (rclist_drop(&rilist, &next)) {
  357. G_debug(5, "find_pixel_neighbors for row: %d , col %d",
  358. next.row, next.col);
  359. globals->find_neighbors(next.row, next.col, neighbors);
  360. for (n = 0; n < globals->nn; n++) {
  361. ngbr_rc.row = neighbors[n][0];
  362. ngbr_rc.col = neighbors[n][1];
  363. if (ngbr_rc.row < 0 || ngbr_rc.row >= globals->nrows ||
  364. ngbr_rc.col < 0 || ngbr_rc.col >= globals->ncols) {
  365. continue;
  366. }
  367. if (FLAG_GET(globals->null_flag, ngbr_rc.row, ngbr_rc.col)) {
  368. continue;
  369. }
  370. if (FLAG_GET(globals->candidate_flag, ngbr_rc.row, ngbr_rc.col)) {
  371. continue;
  372. }
  373. segment_get(seeds_seg, (void *) &Rk_id, ngbr_rc.row, ngbr_rc.col);
  374. G_debug(5, "Rk ID = %d Ri ID = %d", Rk_id, Ri_id);
  375. if (Rk_id != Ri_id) {
  376. continue;
  377. }
  378. /* set segment id */
  379. if (segment_put(&globals->rid_seg,
  380. &new_id, ngbr_rc.row, ngbr_rc.col) != 1)
  381. G_fatal_error(_("Unable to write to temporary file"));
  382. /* set candidate flag */
  383. FLAG_SET(globals->candidate_flag, ngbr_rc.row, ngbr_rc.col);
  384. /* add to list of cells to check */
  385. rclist_add(&rilist, ngbr_rc.row, ngbr_rc.col);
  386. /* update region stats */
  387. segment_get(&globals->bands_seg, (void *)globals->bands_val,
  388. ngbr_rc.row, ngbr_rc.col);
  389. for (i = 0; i < globals->nbands; i++) {
  390. globals->rs.sum[i] += globals->bands_val[i];
  391. }
  392. globals->rs.count++;
  393. }
  394. }
  395. if (rgtree_find(globals->reg_tree, &(globals->rs)) != NULL) {
  396. G_fatal_error(_("Segment %d is already registered!"), new_id);
  397. }
  398. /* insert into region tree */
  399. if (globals->rs.count >= globals->min_reg_size) {
  400. for (i = 0; i < globals->nbands; i++)
  401. globals->rs.mean[i] = globals->rs.sum[i] / globals->rs.count;
  402. rgtree_insert(globals->reg_tree, &(globals->rs));
  403. }
  404. else {
  405. update_band_vals(Ri->row, Ri->col, &(globals->rs), globals);
  406. }
  407. if (globals->rs.count > 1)
  408. globals->n_regions -= (globals->rs.count - 1);
  409. return 1;
  410. }
  411. static int manage_memory(int srows, int scols, struct globals *globals)
  412. {
  413. double reg_size_mb, segs_mb;
  414. int reg_size_count, nseg, nseg_total;
  415. /* minimum region size to store in search tree */
  416. reg_size_mb = 2 * globals->datasize + /* mean, sum */
  417. 2 * sizeof(int) + /* id, count */
  418. sizeof(unsigned char) +
  419. 2 * sizeof(struct REG_NODE *);
  420. reg_size_mb /= (1024. * 1024.);
  421. /* put aside some memory for segment structures */
  422. segs_mb = globals->mb * 0.1;
  423. if (segs_mb > 10)
  424. segs_mb = 10;
  425. /* calculate number of region stats that can be kept in memory */
  426. reg_size_count = (globals->mb - segs_mb) / reg_size_mb;
  427. globals->min_reg_size = 3;
  428. if (reg_size_count < (double) globals->notnullcells / globals->min_reg_size) {
  429. globals->min_reg_size = (double) globals->notnullcells / reg_size_count;
  430. }
  431. else {
  432. reg_size_count = (double) globals->notnullcells / globals->min_reg_size;
  433. /* recalculate segs_mb */
  434. segs_mb = globals->mb - reg_size_count * reg_size_mb;
  435. }
  436. G_verbose_message(_("Regions with at least %d cells are stored in memory"),
  437. globals->min_reg_size);
  438. /* calculate number of segments in memory */
  439. if (globals->bounds_map != NULL) {
  440. /* input bands, segment ids, bounds map */
  441. nseg = (1024. * 1024. * segs_mb) /
  442. (sizeof(DCELL) * globals->nbands * srows * scols +
  443. sizeof(CELL) * 4 * srows * scols);
  444. }
  445. else {
  446. /* input bands, segment ids */
  447. nseg = (1024. * 1024. * segs_mb) /
  448. (sizeof(DCELL) * globals->nbands * srows * scols +
  449. sizeof(CELL) * 2 * srows * scols);
  450. }
  451. nseg_total = (globals->nrows / srows + (globals->nrows % srows > 0)) *
  452. (globals->ncols / scols + (globals->ncols % scols > 0));
  453. if (nseg > nseg_total)
  454. nseg = nseg_total;
  455. G_debug(1, "current region: %d rows, %d cols", globals->nrows, globals->ncols);
  456. G_debug(1, "segmented to tiles with size: %d rows, %d cols", srows,
  457. scols);
  458. G_verbose_message(_("Number of segments in memory: %d of %d total"),
  459. nseg, nseg_total);
  460. return nseg;
  461. }