open_files.c 18 KB

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