open_files.c 17 KB

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