ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rcollate.c
Revision: 2.9
Committed: Fri May 30 00:00:54 2014 UTC (9 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.8: +88 -25 lines
Log Message:
Added NROWS, NCOLS and NCOMP to matrix headers

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: rcollate.c,v 2.8 2014/02/21 13:49:00 greg Exp $";
3 #endif
4 /*
5 * Utility to re-order records in a binary or ASCII data file (matrix)
6 */
7
8 #include <stdlib.h>
9 #include <string.h>
10 #include <ctype.h>
11 #include "platform.h"
12 #include "rtio.h"
13 #include "resolu.h"
14 #ifdef _WIN32
15 #undef ftello
16 #define ftello ftell
17 #undef ssize_t
18 #define ssize_t size_t
19 #else
20 #include <sys/mman.h>
21 #endif
22
23 #ifdef getc_unlocked /* avoid horrendous overhead of flockfile */
24 #undef getc
25 #undef putc
26 #define getc getc_unlocked
27 #define putc putc_unlocked
28 #endif
29
30 typedef struct {
31 void *base; /* pointer to base memory */
32 size_t len; /* allocated memory length */
33 int mapped; /* memory-mapped file? */
34 } MEMLOAD; /* file loaded/mapped into memory */
35
36 typedef struct {
37 int nw_rec; /* number of words per record */
38 int nrecs; /* number of records we found */
39 char *rec[1]; /* record array (extends struct) */
40 } RECINDEX;
41
42 int warnings = 1; /* report warnings? */
43
44 /* free loaded file */
45 static void
46 free_load(MEMLOAD *mp)
47 {
48 if (mp == NULL || (mp->base == NULL) | (mp->len <= 0))
49 return;
50 #ifdef MAP_FILE
51 if (mp->mapped)
52 munmap(mp->base, mp->len);
53 else
54 #endif
55 free(mp->base);
56 mp->base = NULL;
57 mp->len = 0;
58 }
59
60 /* load a file into memory */
61 static int
62 load_file(MEMLOAD *mp, FILE *fp)
63 {
64 int fd;
65 off_t skip, flen;
66
67 if (mp == NULL)
68 return(-1);
69 mp->base = NULL;
70 mp->len = 0;
71 mp->mapped = 0;
72 if (fp == NULL)
73 return(-1);
74 fd = fileno(fp);
75 skip = ftello(fp);
76 flen = lseek(fd, 0, SEEK_END);
77 if (flen <= skip)
78 return((int)(flen - skip));
79 mp->len = (size_t)(flen - skip);
80 #ifdef MAP_FILE
81 if (mp->len > 1L<<20) { /* map file if > 1 MByte */
82 mp->base = mmap(NULL, mp->len, PROT_READ, MAP_PRIVATE, fd, skip);
83 if (mp->base != MAP_FAILED) {
84 mp->mapped = 1;
85 return(1); /* mmap() success */
86 }
87 mp->base = NULL; /* fall back to reading it in... */
88 }
89 #endif
90 if (lseek(fd, skip, SEEK_SET) != skip ||
91 (mp->base = malloc(mp->len)) == NULL) {
92 mp->len = 0;
93 return(-1);
94 }
95 if (read(fd, (char *)mp->base, mp->len) != mp->len) {
96 free_load(mp);
97 return(-1);
98 }
99 return(1);
100 }
101
102 /* load memory from an input stream, starting from current position */
103 static int
104 load_stream(MEMLOAD *mp, FILE *fp)
105 {
106 size_t alloced = 0;
107 char buf[8192];
108 size_t nr;
109
110 if (mp == NULL)
111 return(-1);
112 mp->base = NULL;
113 mp->len = 0;
114 mp->mapped = 0;
115 if (fp == NULL)
116 return(-1);
117 while ((nr = fread(buf, 1, sizeof(buf), fp)) > 0) {
118 if (!alloced)
119 mp->base = malloc(nr);
120 else if (mp->len+nr > alloced)
121 mp->base = realloc(mp->base,
122 alloced = alloced*(2+(nr==sizeof(buf)))/2+nr);
123 if (mp->base == NULL)
124 return(-1);
125 memcpy((char *)mp->base + mp->len, buf, nr);
126 mp->len += nr;
127 }
128 if (ferror(fp)) {
129 free_load(mp);
130 return(-1);
131 }
132 if (alloced > mp->len*5/4) /* don't waste too much space */
133 mp->base = realloc(mp->base, mp->len);
134 return(mp->len > 0);
135 }
136
137 /* free a record index */
138 #define free_records(rp) free(rp)
139
140 /* compute record index */
141 static RECINDEX *
142 index_records(const MEMLOAD *mp, int nw_rec)
143 {
144 RECINDEX *rp;
145 char *cp, *mend;
146 int n;
147
148 if (mp == NULL || (mp->base == NULL) | (mp->len <= 0))
149 return(NULL);
150 if (nw_rec <= 0)
151 return(NULL);
152 rp = (RECINDEX *)malloc(sizeof(RECINDEX) + mp->len/(2*nw_rec)*sizeof(char *));
153 if (rp == NULL)
154 return(NULL);
155 rp->nw_rec = nw_rec;
156 rp->nrecs = 0;
157 cp = (char *)mp->base;
158 mend = cp + mp->len;
159 for ( ; ; ) { /* whitespace-separated words */
160 while (cp < mend && !*cp | isspace(*cp))
161 ++cp;
162 if (cp >= mend)
163 break;
164 rp->rec[rp->nrecs++] = cp; /* point to first non-white */
165 n = rp->nw_rec;
166 while (++cp < mend) /* find end of record */
167 if (!*cp | isspace(*cp)) {
168 if (--n <= 0)
169 break; /* got requisite # words */
170 do { /* else find next word */
171 if (*cp == '\n') {
172 fprintf(stderr,
173 "Unexpected EOL in record!\n");
174 free_records(rp);
175 return(NULL);
176 }
177 if (++cp >= mend)
178 break;
179 } while (!*cp | isspace(*cp));
180 }
181 }
182 rp->rec[rp->nrecs] = mend; /* reallocate to save space */
183 rp = (RECINDEX *)realloc(rp,
184 sizeof(RECINDEX) + rp->nrecs*sizeof(char *));
185 return(rp);
186 }
187
188 /* count number of columns based on first EOL */
189 static int
190 count_columns(const RECINDEX *rp)
191 {
192 char *cp = rp->rec[0];
193 char *mend = rp->rec[rp->nrecs];
194 int i;
195
196 while (*cp != '\n')
197 if (++cp >= mend)
198 return(0);
199 for (i = 0; i < rp->nrecs; i++)
200 if (rp->rec[i] >= cp)
201 break;
202 return(i);
203 }
204
205 /* copy nth record from index to stdout */
206 static int
207 print_record(const RECINDEX *rp, int n)
208 {
209 int words2go = rp->nw_rec;
210 char *scp;
211
212 if ((n < 0) | (n >= rp->nrecs))
213 return(0);
214 scp = rp->rec[n];
215 do {
216 putc(*scp++, stdout);
217 if (!*scp | isspace(*scp)) {
218 if (--words2go <= 0)
219 break;
220 putc(' ', stdout); /* single space btwn. words */
221 do
222 if (++scp >= rp->rec[n+1])
223 break;
224 while (!*scp | isspace(*scp));
225 }
226 } while (scp < rp->rec[n+1]);
227 /* caller adds record sep. */
228 return(1);
229 }
230
231 /* copy a stream to stdout */
232 static int
233 output_stream(FILE *fp)
234 {
235 char buf[8192];
236 ssize_t n;
237
238 if (fp == NULL)
239 return(0);
240 fflush(stdout); /* assumes nothing in input buffer */
241 while ((n = read(fileno(fp), buf, sizeof(buf))) > 0)
242 if (write(fileno(stdout), buf, n) != n)
243 return(0);
244 return(n >= 0);
245 }
246
247 /* get next word from stream, leaving stream on EOL or start of next word */
248 static char *
249 fget_word(char buf[256], FILE *fp)
250 {
251 int c;
252 char *cp;
253 /* skip nul's and white space */
254 while (!(c = getc(fp)) || isspace(c))
255 ;
256 if (c == EOF)
257 return(NULL);
258 cp = buf;
259 do
260 *cp++ = c;
261 while ((c = getc(fp)) != EOF && !isspace(c) && cp < buf+255);
262 *cp = '\0';
263 while (isspace(c) & (c != '\n'))
264 c = getc(fp);
265 if (c != EOF)
266 ungetc(c, fp);
267 return(buf);
268 }
269
270 char *fmtid = NULL; /* format id */
271 int comp_size = 0; /* binary bytes/channel */
272 int n_comp = 0; /* components/record */
273 int ni_columns = 0; /* number of input columns */
274 int ni_rows = 0; /* number of input rows */
275 int no_columns = 0; /* number of output columns */
276 int no_rows = 0; /* number of output rows */
277
278 /* check settings and assign defaults */
279 static void
280 check_sizes()
281 {
282 if (fmtid == NULL) {
283 fmtid = "ascii";
284 } else if (!comp_size) {
285 if (!strcmp(fmtid, "float"))
286 comp_size = sizeof(float);
287 else if (!strcmp(fmtid, "double"))
288 comp_size = sizeof(double);
289 else if (!strcmp(fmtid, "byte"))
290 comp_size = 1;
291 }
292 if (n_comp <= 0)
293 n_comp = 3;
294 }
295
296 /* output transposed ASCII or binary data from memory */
297 static int
298 do_transpose(const MEMLOAD *mp)
299 {
300 static const char tabEOL[2] = {'\t','\n'};
301 RECINDEX *rp = NULL;
302 long nrecords;
303 int i, j;
304 /* propogate sizes */
305 if (ni_rows <= 0)
306 ni_rows = no_columns;
307 if (ni_columns <= 0)
308 ni_columns = no_rows;
309 /* get # records (& index) */
310 if (!comp_size) {
311 if ((rp = index_records(mp, n_comp)) == NULL)
312 return(0);
313 if (ni_columns <= 0)
314 ni_columns = count_columns(rp);
315 nrecords = rp->nrecs;
316 } else if ((ni_rows > 0) & (ni_columns > 0)) {
317 nrecords = ni_rows*ni_columns;
318 if (nrecords > mp->len/(n_comp*comp_size)) {
319 fprintf(stderr,
320 "Input too small for specified size and type\n");
321 return(0);
322 }
323 } else
324 nrecords = mp->len/(n_comp*comp_size);
325 /* check sizes */
326 if ((ni_rows <= 0) & (ni_columns > 0))
327 ni_rows = nrecords/ni_columns;
328 if ((ni_columns <= 0) & (ni_rows > 0))
329 ni_columns = nrecords/ni_rows;
330 if (nrecords != ni_rows*ni_columns)
331 goto badspec;
332 if (no_columns <= 0)
333 no_columns = ni_rows;
334 if (no_rows <= 0)
335 no_rows = ni_columns;
336 if ((no_rows != ni_columns) | (no_columns != ni_rows))
337 goto badspec;
338 /* transpose records */
339 for (i = 0; i < no_rows; i++) {
340 for (j = 0; j < no_columns; j++)
341 if (rp != NULL) { /* ASCII output */
342 print_record(rp, j*ni_columns + i);
343 putc(tabEOL[j >= no_columns-1], stdout);
344 } else { /* binary output */
345 fwrite((char *)mp->base +
346 (n_comp*comp_size)*(j*ni_columns + i),
347 n_comp*comp_size, 1, stdout);
348 }
349 if (ferror(stdout)) {
350 fprintf(stderr, "Error writing to stdout\n");
351 return(0);
352 }
353 }
354 if (rp != NULL)
355 free_records(rp);
356 return(1);
357 badspec:
358 fprintf(stderr, "Bad transpose specification -- check dimension(s)\n");
359 return(0);
360 }
361
362 /* resize ASCII stream input by ignoring EOLs between records */
363 static int
364 do_resize(FILE *fp)
365 {
366 long records2go = ni_rows*ni_columns;
367 int columns2go = no_columns;
368 char word[256];
369 /* sanity checks */
370 if (comp_size) {
371 fputs("Bad call to do_resize (binary input)\n", stderr);
372 return(0);
373 }
374 if (no_columns <= 0) {
375 fprintf(stderr, "Missing -oc specification\n");
376 return(0);
377 }
378 if ((records2go <= 0) & (no_rows > 0))
379 records2go = no_rows*no_columns;
380 else if (no_rows*no_columns != records2go) {
381 fprintf(stderr,
382 "Input and output data sizes disagree (%dx%d != %dx%d)\n",
383 ni_rows, ni_columns, no_rows, no_columns);
384 return(0);
385 }
386 do { /* reshape records */
387 int n;
388
389 for (n = n_comp; n--; ) {
390 if (fget_word(word, fp) == NULL) {
391 if (records2go > 0 || n < n_comp-1)
392 break;
393 goto done; /* normal EOD */
394 }
395 fputs(word, stdout);
396 if (n) { /* mid-record? */
397 int c = getc(fp);
398 if ((c == '\n') | (c == EOF))
399 break;
400 ungetc(c, fp);
401 putc(' ', stdout);
402 }
403 }
404 if (n >= 0) {
405 fprintf(stderr, "Incomplete record / unexpected EOF\n");
406 return(0);
407 }
408 if (--columns2go <= 0) { /* time to end output row? */
409 putc('\n', stdout);
410 columns2go = no_columns;
411 } else /* else separate records */
412 putc('\t', stdout);
413 } while (--records2go); /* expected EOD? */
414 done:
415 if (warnings && columns2go != no_columns)
416 fprintf(stderr, "Warning -- incomplete final row\n");
417 if (warnings && fget_word(word, fp) != NULL)
418 fprintf(stderr, "Warning -- characters beyond expected EOD\n");
419 return(1);
420 }
421
422 /* process a header line and copy to stdout */
423 static int
424 headline(char *s, void *p)
425 {
426 static char fmt[32];
427 int n;
428
429 if (formatval(fmt, s)) {
430 if (fmtid == NULL) {
431 fmtid = fmt;
432 return(0);
433 }
434 if (!strcmp(fmt, fmtid))
435 return(0);
436 fprintf(stderr, "Input format '%s' != '%s'\n", fmt, fmtid);
437 return(-1);
438 }
439 if (!strncmp(s, "NROWS=", 6)) {
440 n = atoi(s+6);
441 if ((ni_rows > 0) & (n != ni_rows)) {
442 fputs("Incorrect input row count\n", stderr);
443 return(-1);
444 }
445 ni_rows = n;
446 return(0);
447 }
448 if (!strncmp(s, "NCOLS=", 6)) {
449 n = atoi(s+6);
450 if ((ni_columns > 0) & (n != ni_columns)) {
451 fputs("Incorrect input column count\n", stderr);
452 return(-1);
453 }
454 ni_columns = n;
455 return(0);
456 }
457 if (!strncmp(s, "NCOMP=", 6)) {
458 n = atoi(s+6);
459 if ((n_comp > 0) & (n != n_comp)) {
460 fputs("Incorrect number of components", stderr);
461 return(-1);
462 }
463 n_comp = n;
464 return(0);
465 }
466 fputs(s, stdout); /* copy header info. */
467 return(0);
468 }
469
470 /* main routine for converting rows/columns in data file */
471 int
472 main(int argc, char *argv[])
473 {
474 int do_header = 1; /* header i/o? */
475 int transpose = 0; /* transpose rows & cols? */
476 int i;
477
478 for (i = 1; i < argc && argv[i][0] == '-'; i++)
479 switch (argv[i][1]) {
480 case 'i': /* input */
481 if (argv[i][2] == 'c') /* columns */
482 ni_columns = atoi(argv[++i]);
483 else if (argv[i][2] == 'r')
484 ni_rows = atoi(argv[++i]);
485 else
486 goto userr;
487 break;
488 case 'o': /* output */
489 if (argv[i][2] == 'c') /* columns */
490 no_columns = atoi(argv[++i]);
491 else if (argv[i][2] == 'r')
492 no_rows = atoi(argv[++i]);
493 else
494 goto userr;
495 break;
496 case 'h': /* header on/off */
497 do_header = !do_header;
498 break;
499 case 't': /* transpose on/off */
500 transpose = !transpose;
501 break;
502 case 'f': /* format */
503 switch (argv[i][2]) {
504 case 'a': /* ASCII */
505 case 'A':
506 fmtid = "ascii";
507 comp_size = 0;
508 break;
509 case 'f': /* float */
510 case 'F':
511 fmtid = "float";
512 comp_size = sizeof(float);
513 break;
514 case 'd': /* double */
515 case 'D':
516 fmtid = "double";
517 comp_size = sizeof(double);
518 break;
519 case 'b': /* binary (bytes) */
520 case 'B':
521 fmtid = "byte";
522 comp_size = 1;
523 break;
524 default:
525 goto userr;
526 }
527 if (argv[i][3]) {
528 if (!isdigit(argv[i][3]))
529 goto userr;
530 n_comp = atoi(argv[i]+3);
531 }
532 break;
533 case 'w': /* warnings on/off */
534 warnings = !warnings;
535 break;
536 default:
537 goto userr;
538 }
539 if (i < argc-1) /* arg count OK? */
540 goto userr;
541 /* open input file? */
542 if (i == argc-1 && freopen(argv[i], "r", stdin) == NULL) {
543 fprintf(stderr, "%s: cannot open for reading\n", argv[i]);
544 return(1);
545 }
546 if (comp_size) {
547 SET_FILE_BINARY(stdin);
548 SET_FILE_BINARY(stdout);
549 }
550 /* check for no-op */
551 if (!transpose && (comp_size ||
552 (no_columns == ni_columns) & (no_rows == ni_rows))) {
553 if (warnings)
554 fprintf(stderr, "%s: no-op -- copying input verbatim\n",
555 argv[0]);
556 if (!output_stream(stdin))
557 return(1);
558 return(0);
559 }
560 if (do_header) { /* read/write header */
561 if (getheader(stdin, &headline, NULL) < 0)
562 return(1);
563 check_sizes();
564 if (comp_size) { /* a little late... */
565 SET_FILE_BINARY(stdin);
566 SET_FILE_BINARY(stdout);
567 }
568 printargs(argc, argv, stdout);
569 if (transpose && (no_rows <= 0) & (no_columns <= 0)) {
570 if (ni_rows > 0) no_columns = ni_rows;
571 if (ni_columns > 0) no_rows = ni_columns;
572 }
573 if (no_rows > 0)
574 printf("NROWS=%d\n", no_rows);
575 if (no_columns > 0)
576 printf("NCOLS=%d\n", no_columns);
577 printf("NCOMP=%d\n", n_comp);
578 fputformat(fmtid, stdout);
579 fputc('\n', stdout); /* finish new header */
580 } else
581 check_sizes();
582 if (transpose) { /* transposing rows & columns? */
583 MEMLOAD myMem; /* need to load into memory */
584 if (i == argc-1) {
585 if (load_file(&myMem, stdin) <= 0) {
586 fprintf(stderr, "%s: error loading file into memory\n",
587 argv[i]);
588 return(1);
589 }
590 } else if (load_stream(&myMem, stdin) <= 0) {
591 fprintf(stderr, "%s: error loading stdin into memory\n",
592 argv[0]);
593 return(1);
594 }
595 if (!do_transpose(&myMem))
596 return(1);
597 /* free_load(&myMem); */
598 } else if (!do_resize(stdin)) /* just reshaping input */
599 return(1);
600 return(0);
601 userr:
602 fprintf(stderr,
603 "Usage: %s [-h][-w][-f[afdb][N]][-t][-ic in_col][-ir in_row][-oc out_col][-or out_row] [input.dat]\n",
604 argv[0]);
605 return(1);
606 }