aboutsummaryrefslogtreecommitdiff
path: root/vendor/voclient/voapps/votstat.c
blob: 0065e314f35c05e15092170cdfe4e3bd731c8ac6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
 *  VOTSTAT -- Compute statistics for numeric columns of a VOTable.
 *
 *    Usage:
 *		votstat [<otps>] <votable>
 *
 *  @file       votstat.c
 *  @author     Mike Fitzpatrick
 *  @date       6/03/12
 *
 *  @brief      Compute statistics for numeric columns of a VOTable.
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

#include "votParse.h"			/* keep these in order!		*/
#include "voApps.h"



/*  Global task declarations.
 */
static int vot		= 0;		/* VOTable handle		*/

static int  do_all	= 0;		/* all columns?			*/
static int  do_return   = 0;		/* return result?		*/


/*  A result buffer should be defined to point to the result object if it is
 *  created dynamically, e.g. a list of votable columns.  The task is
 *  responsible for initially allocating this pointer and then resizing as
 *  needed.
 */
#ifdef USE_RESBUF
#define	SZ_RESBUF	8192

static char *resbuf;
#endif


/*  Task specific option declarations.  Task options are declared using the
 *  getopt_long(3) syntax.
 */
int  votstat (int argc, char **argv, size_t *len, void **result);

static Task  self       = {  "votstat",  votstat,  0,  0,  0  };
static char  *opts 	= "%:hao:r";
static struct option long_opts[] = {
        { "test",         1, 0,   '%'},
        { "help",         2, 0,   'h'},
        { "all",          2, 0,   'a'},
        { "output",       1, 0,   'o'},
        { "return",       2, 0,   'r'},
        { NULL,           0, 0,    0 }
};


/*  Standard usage method.
 */
static void Usage (void);
static void Tests (char *input);

void vot_colStat (int tdata, int col, int nrows, double *min, double *max, 
	double *mean, double *stddev); 

extern int    vot_isNumericField (handle_t field);
extern double vot_atof (char *v);


/**
 *  Application entry point.
 */
int
votstat (int argc, char **argv, size_t *reslen, void **result)
{
    /*  These declarations are required for the VOApps param interface.
     */
    char **pargv, optval[SZ_FNAME];

    /*  These declarations are specific to the task.
     */
    char  *iname, *oname, *name, *id, *fstr;
    int    ch = 0, status = OK, numeric = 0;
    int    res, tab, data, tdata, field;
    int    i, ncols, nrows, pos = 0;
    FILE  *fd = (FILE *) NULL;


    /* Initialize result object	whether we return an object or not.
     */
    *reslen = 0;	
    *result = NULL;

    iname  = NULL; 		/* initialize local task values  	*/
    oname  = NULL;


    /*  Parse the argument list.  
     */
    pargv = vo_paramInit (argc, argv, opts, long_opts);
    while ((ch = vo_paramNext(opts,long_opts,argc,pargv,optval,&pos)) != 0) {
        if (ch > 0) {
	    switch (ch) {
	    case '%':  Tests (optval);			return (self.nfail);
	    case 'h':  Usage ();			return (OK);
	    case 'a':  do_all++;			break;
	    case 'o':  oname = strdup (optval);		break;
	    case 'r':  do_return=1;	    	    	break;
	    default:
		fprintf (stderr, "Invalid option '%s'\n", optval);
		return (1);
	    }

        } else if (ch == PARG_ERR) {
            return (ERR);

	} else {
	    /*  Process the positional arguments.
	     */
	    iname = strdup (optval);
	    break;
	}
    }


    /*  Sanity checks.  Tasks should validate input and accept stdin/stdout
     *  where it makes sense.
     */
    if (iname == NULL) iname = strdup ("stdin");
    if (oname == NULL) oname = strdup ("stdout");
    if (strcmp(iname, "-") == 0) { free (iname), iname = strdup ("stdin");  }
    if (strcmp(oname, "-") == 0) { free (oname), oname = strdup ("stdout"); }

    if (strcmp ("stdout", oname) == 0) 
	fd = stdout;
    else {
	if ((fd = fopen (oname, "w+")) == (FILE *) NULL) {
	    fprintf (stderr, "Cannot open output file '%s'\n", oname);
	    return (ERR);
	}
    }

    /* Open the table.  This also parses it.
    */
    if ( (vot = vot_openVOTABLE (iname) ) <= 0) {
        fprintf (stderr, "Error opening VOTable '%s'\n", iname);
        return (1);
    }

    res   = vot_getRESOURCE (vot);      /* get handles          */
    if (vot_getLength (res) > 1) {
        fprintf (stderr, "Error: multiple RESOURCE elements not supported\n");
        goto clean_up_;
    }
    tab   = vot_getTABLE (res);
    if ((data = vot_getDATA (tab)) <= 0)
	goto clean_up_;
    tdata = vot_getTABLEDATA (data);
    nrows = vot_getNRows (tdata);
    ncols = vot_getNCols (tdata);


    fprintf (fd, "# %3s  %-20.20s  %9.9s  %9.9s  %9.9s  %9.9s\n#\n",
	"Col", "Name", "Min", "Max", "Mean", "StdDev");

    for (i=0,field=vot_getFIELD(tab); field; field=vot_getNext (field), i++) {
        name  = vot_getAttr (field, "name");
        id    = vot_getAttr (field, "id");

	numeric = vot_isNumericField (field);
	fstr = (name ? name : (id ? id : "(none)"));

	if (do_all && !numeric)		/* non-numeric column		*/
            fprintf (fd, "  %3d  %-20.20s\n", i, fstr);

	else if (do_all || numeric) {	/* numeric column		*/
	    double  min, max, mean, stddev;

	    vot_colStat (tdata, i, nrows, &min, &max, &mean, &stddev);

	    if (mean > 1.0e6 || mean < 1.0e-3)
                fprintf (fd, "  %3d  %-20.20s  %9.4g  %9.4g  %9.4g  %9.4g\n",
                    i, fstr, min, max, mean, stddev);
	    else
                fprintf (fd, "  %3d  %-20.20s  %9.2f  %9.2f  %9.2f  %9.2f\n",
                    i, fstr, min, max, mean, stddev);
	}
    }


    /*  Clean up.  Rememebr to free whatever pointers were created when
     *  parsing arguments.
     */
clean_up_:
    if (iname) free (iname);
    if (oname) free (oname);

    vo_paramFree (argc, pargv);
    vot_closeVOTABLE (vot);

    if (fd != stdout)
	fclose (fd);

    return (status);	/* status must be OK or ERR (i.e. 0 or 1)     	*/
}


/**
 *  VOT_COLSTAT -- Determine the statistics of a table column.
 */
void
vot_colStat (int tdata, int col, int nrows, double *min, double *max, 
		double *mean, double *stddev)
{
    register int i = 0;
    double  sum = 0.0, sum2 = 0.0, val = 0.0;


    *min    =  0.99e306;
    *max    = -0.99e306;
    *mean   = 0.0;
    *stddev = 0.0;

    for (i=0; i < nrows; i++) {
	val   = vot_atof (vot_getTableCell (tdata, i, col));
	sum  += val;
	sum2 += (val * val);
	if (val < (*min))  *min = val;
	if (val > (*max))  *max = val;
    }

    *mean = (double) (sum / (double) nrows);
    *stddev = sqrt ( ( sum2 / (double) nrows) - 
	( (sum / (double) nrows) * (sum / (double) nrows) ));
}


/**
 *  USAGE -- Print task help summary.
 */
static void
Usage (void)
{
    fprintf (stderr, "\n  Usage:\n\t"
        "votstat [<opts>] votable.xml\n\n"
        "  where\n"
        "       -h,--help		this message\n"
        "       -%%,--test		run unit tests\n"
        "       -r,--return		return result from method\n"
	"\n"
        "       -a,--all		print all columns\n"
        "       -o,--output=<file>	output file\n"
	"\n"
 	"  Examples:\n\n"
	"    1) Print statistics for a VOTable\n\n"
	"	  %% votstat test.xml\n"
	"\n"
	"    2) Print statistics for all column in a VOTable and save \n"
        "       results to a file.\n\n"
	"	    %% votstat -a -o stats test.xml\n"
	"\n"
    );
}



/**
 *  Tests -- Task unit tests.
 */
static void
Tests (char *input)
{
   Task *task = &self;

   vo_taskTest (task, "--help", NULL);
}