1 /****************************************************************************
2 * RRDtool 1.3.2 Copyright by Tobi Oetiker, 1997-2008
3 ****************************************************************************
4 * rrd_rpncalc.c RPN calculator functions
5 ****************************************************************************/
8 #include "rrd_rpncalc.h"
9 // #include "rrd_graph.h"
18 unsigned short *offset);
20 time_t); /* used to implement LTIME */
30 /* count the number of rpn nodes */
31 while (rpnp[*count].op != OP_END)
33 if (++(*count) > DS_CDEF_MAX_RPN_NODES) {
34 rrd_set_error("Maximum %d RPN nodes permitted",
35 DS_CDEF_MAX_RPN_NODES);
40 *rpnc = (rpn_cdefds_t *) calloc(*count, sizeof(rpn_cdefds_t));
41 for (i = 0; rpnp[i].op != OP_END; i++) {
42 (*rpnc)[i].op = (char) rpnp[i].op;
43 if (rpnp[i].op == OP_NUMBER) {
44 /* rpnp.val is a double, rpnc.val is a short */
45 double temp = floor(rpnp[i].val);
47 if (temp < SHRT_MIN || temp > SHRT_MAX) {
49 ("constants must be integers in the interval (%d, %d)",
54 (*rpnc)[i].val = (short) temp;
55 } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
56 (*rpnc)[i].val = (short) rpnp[i].ptr;
59 /* terminate the sequence */
60 (*rpnc)[(*count) - 1].op = OP_END;
70 /* DS_CDEF_MAX_RPN_NODES is small, so at the expense of some wasted
71 * memory we avoid any reallocs */
72 rpnp = (rpnp_t *) calloc(DS_CDEF_MAX_RPN_NODES, sizeof(rpnp_t));
75 for (i = 0; rpnc[i].op != OP_END; ++i) {
76 rpnp[i].op = (long) rpnc[i].op;
77 if (rpnp[i].op == OP_NUMBER) {
78 rpnp[i].val = (double) rpnc[i].val;
79 } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
80 rpnp[i].ptr = (long) rpnc[i].val;
83 /* terminate the sequence */
88 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
89 * into a CDEF string. This function is used by rrd_dump.
91 * rpnc: an array of compact RPN operator nodes
92 * ds_def: a pointer to the data source definition section of an RRD header
93 * for lookup of data source names by index
94 * str: out string, memory is allocated by the function, must be freed by the
101 unsigned short i, offset = 0;
102 char buffer[7]; /* short as a string */
104 for (i = 0; rpnc[i].op != OP_END; i++) {
106 (*str)[offset++] = ',';
108 #define add_op(VV,VVV) \
109 if (addop2str(rpnc[i].op, VV, VVV, str, &offset) == 1) continue;
111 if (rpnc[i].op == OP_NUMBER) {
112 /* convert a short into a string */
113 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
114 _itoa(rpnc[i].val, buffer, 10);
116 sprintf(buffer, "%d", rpnc[i].val);
118 add_op(OP_NUMBER, buffer)
121 if (rpnc[i].op == OP_VARIABLE) {
122 char *ds_name = ds_def[rpnc[i].val].ds_nam;
124 add_op(OP_VARIABLE, ds_name)
127 if (rpnc[i].op == OP_PREV_OTHER) {
128 char *ds_name = ds_def[rpnc[i].val].ds_nam;
130 add_op(OP_VARIABLE, ds_name)
134 #define add_op(VV,VVV) \
135 if (addop2str(rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
145 add_op(OP_FLOOR, FLOOR)
146 add_op(OP_CEIL, CEIL)
159 add_op(OP_LIMIT, LIMIT)
160 add_op(OP_UNKN, UNKN)
162 add_op(OP_NEGINF, NEGINF)
164 add_op(OP_PREV, PREV)
166 add_op(OP_ISINF, ISINF)
168 add_op(OP_LTIME, LTIME)
169 add_op(OP_TIME, TIME)
170 add_op(OP_ATAN2, ATAN2)
171 add_op(OP_ATAN, ATAN)
172 add_op(OP_SQRT, SQRT)
173 add_op(OP_SORT, SORT)
175 add_op(OP_TREND, TREND)
176 add_op(OP_TRENDNAN, TRENDNAN)
177 add_op(OP_PREDICT, PREDICT)
178 add_op(OP_PREDICTSIGMA, PREDICTSIGMA)
179 add_op(OP_RAD2DEG, RAD2DEG)
180 add_op(OP_DEG2RAD, DEG2RAD)
183 add_op(OP_ADDNAN, ADDNAN)
186 (*str)[offset] = '\0';
195 unsigned short *offset)
200 op_len = strlen(op_str);
201 *result_str = (char *) rrd_realloc(*result_str,
203 *offset) * sizeof(char));
204 if (*result_str == NULL) {
205 rrd_set_error("failed to alloc memory in addop2str");
208 strncpy(&((*result_str)[*offset]), op_str, op_len);
221 rpn_cdefds_t *rpnc = NULL;
224 rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
226 rrd_set_error("failed to parse computed data source");
229 /* Check for OP nodes not permitted in COMPUTE DS.
230 * Moved this check from within rpn_compact() because it really is
231 * COMPUTE DS specific. This is less efficient, but creation doesn't
232 * occur too often. */
233 for (i = 0; rpnp[i].op != OP_END; i++) {
234 if (rpnp[i].op == OP_TIME || rpnp[i].op == OP_LTIME ||
235 rpnp[i].op == OP_PREV || rpnp[i].op == OP_COUNT) {
237 ("operators time, ltime, prev and count not supported with DS COMPUTE");
242 if (rpn_compact(rpnp, &rpnc, &count) == -1) {
246 /* copy the compact rpn representation over the ds_def par array */
247 memcpy((void *) &(rrd->ds_def[ds_idx].par[DS_cdef]),
248 (void *) rpnc, count * sizeof(rpn_cdefds_t));
253 /* lookup a data source name in the rrd struct and return the index,
254 * should use ds_match() here except:
255 * (1) need a void * pointer to the rrd
256 * (2) error handling is left to the caller
265 rrd = (rrd_t *) rrd_vptr;
267 for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
268 if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
271 /* the caller handles a bad data source name in the rpn string */
275 /* rpn_parse : parse a string and generate a rpnp array; modified
276 * str2rpn() originally included in rrd_graph.c
278 * key_hash: a transparent argument passed to lookup(); conceptually this
279 * is a hash object for lookup of a numeric key given a variable name
280 * expr: the string RPN expression, including variable names
281 * lookup(): a function that retrieves a numeric key given a variable name
285 const char *const expr_const,
286 long (*lookup) (void *,
293 char vname[MAX_VNAME_LEN + 10];
296 old_locale = setlocale(LC_NUMERIC, "C");
299 expr = (char *) expr_const;
302 if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
303 sizeof(rpnp_t))) == NULL) {
304 setlocale(LC_NUMERIC, old_locale);
308 else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
309 && (expr[pos] == ',')) {
310 rpnp[steps].op = OP_NUMBER;
313 #define match_op(VV,VVV) \
314 else if (strncmp(expr, #VVV, strlen(#VVV))==0 && ( expr[strlen(#VVV)] == ',' || expr[strlen(#VVV)] == '\0' )){ \
315 rpnp[steps].op = VV; \
316 expr+=strlen(#VVV); \
319 #define match_op_param(VV,VVV) \
320 else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
322 if ((length = strlen(#VVV)+strlen(vname)+2, \
323 expr[length] == ',' || expr[length] == '\0') ) { \
324 rpnp[steps].op = VV; \
325 rpnp[steps].ptr = (*lookup)(key_hash,vname); \
326 if (rpnp[steps].ptr < 0) { \
329 } else expr+=length; \
338 match_op(OP_SIN, SIN)
339 match_op(OP_COS, COS)
340 match_op(OP_LOG, LOG)
341 match_op(OP_FLOOR, FLOOR)
342 match_op(OP_CEIL, CEIL)
343 match_op(OP_EXP, EXP)
344 match_op(OP_DUP, DUP)
345 match_op(OP_EXC, EXC)
346 match_op(OP_POP, POP)
347 match_op(OP_LTIME, LTIME)
354 match_op(OP_MIN, MIN)
355 match_op(OP_MAX, MAX)
356 match_op(OP_LIMIT, LIMIT)
357 /* order is important here ! .. match longest first */
358 match_op(OP_UNKN, UNKN)
360 match_op(OP_NEGINF, NEGINF)
362 match_op(OP_COUNT, COUNT)
363 match_op_param(OP_PREV_OTHER, PREV)
364 match_op(OP_PREV, PREV)
365 match_op(OP_INF, INF)
366 match_op(OP_ISINF, ISINF)
367 match_op(OP_NOW, NOW)
368 match_op(OP_TIME, TIME)
369 match_op(OP_ATAN2, ATAN2)
370 match_op(OP_ATAN, ATAN)
371 match_op(OP_SQRT, SQRT)
372 match_op(OP_SORT, SORT)
373 match_op(OP_REV, REV)
374 match_op(OP_TREND, TREND)
375 match_op(OP_TRENDNAN, TRENDNAN)
376 match_op(OP_PREDICT, PREDICT)
377 match_op(OP_PREDICTSIGMA, PREDICTSIGMA)
378 match_op(OP_RAD2DEG, RAD2DEG)
379 match_op(OP_DEG2RAD, DEG2RAD)
380 match_op(OP_AVG, AVG)
381 match_op(OP_ABS, ABS)
382 match_op(OP_ADDNAN, ADDNAN)
384 else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
385 && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
387 rpnp[steps].op = OP_VARIABLE;
392 setlocale(LC_NUMERIC, old_locale);
402 setlocale(LC_NUMERIC, old_locale);
407 rpnp[steps + 1].op = OP_END;
408 setlocale(LC_NUMERIC, old_locale);
413 rpnstack_t *rpnstack)
416 rpnstack->dc_stacksize = 0;
417 rpnstack->dc_stackblock = 100;
421 rpnstack_t *rpnstack)
423 if (rpnstack->s != NULL)
425 rpnstack->dc_stacksize = 0;
428 static int rpn_compare_double(
432 double diff = *((const double *) x) - *((const double *) y);
434 return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
437 /* rpn_calc: run the RPN calculator; also performs variable substitution;
438 * moved and modified from data_calc() originally included in rrd_graph.c
440 * rpnp : an array of RPN operators (including variable references)
441 * rpnstack : the initialized stack
442 * data_idx : when data_idx is a multiple of rpnp.step, the rpnp.data pointer
443 * is advanced by rpnp.ds_cnt; used only for variable substitution
444 * output : an array of output values; OP_PREV assumes this array contains
445 * the "previous" value at index position output_idx-1; the definition of
446 * "previous" depends on the calling environment
447 * output_idx : an index into the output array in which to store the output
448 * of the RPN calculator
449 * returns: -1 if the computation failed (also calls rrd_set_error)
454 rpnstack_t *rpnstack,
462 /* process each op from the rpn in turn */
463 for (rpi = 0; rpnp[rpi].op != OP_END; rpi++) {
464 /* allocate or grow the stack */
465 if (stptr + 5 > rpnstack->dc_stacksize) {
466 /* could move this to a separate function */
467 rpnstack->dc_stacksize += rpnstack->dc_stackblock;
468 rpnstack->s = rrd_realloc(rpnstack->s,
469 (rpnstack->dc_stacksize) *
470 sizeof(*(rpnstack->s)));
471 if (rpnstack->s == NULL) {
472 rrd_set_error("RPN stack overflow");
476 #define stackunderflow(MINSIZE) \
478 rrd_set_error("RPN stack underflow"); \
482 switch (rpnp[rpi].op) {
484 rpnstack->s[++stptr] = rpnp[rpi].val;
488 /* Sanity check: VDEFs shouldn't make it here */
489 if (rpnp[rpi].ds_cnt == 0) {
490 rrd_set_error("VDEF made it into rpn_calc... aborting");
493 /* make sure we pull the correct value from
494 * the *.data array. Adjust the pointer into
495 * the array acordingly. Advance the ptr one
496 * row in the rra (skip over non-relevant
499 if (rpnp[rpi].op == OP_VARIABLE) {
500 rpnstack->s[++stptr] = *(rpnp[rpi].data);
502 if ((output_idx) <= 0) {
503 rpnstack->s[++stptr] = DNAN;
505 rpnstack->s[++stptr] =
506 *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
510 if (data_idx % rpnp[rpi].step == 0) {
511 rpnp[rpi].data += rpnp[rpi].ds_cnt;
516 rpnstack->s[++stptr] = (output_idx + 1); /* Note: Counter starts at 1 */
519 if ((output_idx) <= 0) {
520 rpnstack->s[++stptr] = DNAN;
522 rpnstack->s[++stptr] = output[output_idx - 1];
526 rpnstack->s[++stptr] = DNAN;
529 rpnstack->s[++stptr] = DINF;
532 rpnstack->s[++stptr] = -DINF;
535 rpnstack->s[++stptr] = (double) time(NULL);
538 /* HACK: this relies on the data_idx being the time,
539 ** which the within-function scope is unaware of */
540 rpnstack->s[++stptr] = (double) data_idx;
543 rpnstack->s[++stptr] =
544 (double) tzoffset(data_idx) + (double) data_idx;
548 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
549 + rpnstack->s[stptr];
554 if (isnan(rpnstack->s[stptr - 1])) {
555 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
556 } else if (isnan(rpnstack->s[stptr])) {
558 /* rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]; */
560 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
561 + rpnstack->s[stptr];
568 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
569 - rpnstack->s[stptr];
574 rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
575 * (rpnstack->s[stptr]);
580 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
581 / rpnstack->s[stptr];
586 rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
587 , rpnstack->s[stptr]);
592 rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
596 rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
600 rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
604 rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
608 rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
614 rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
618 rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
622 rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
626 rpnstack->s[stptr] = log(rpnstack->s[stptr]);
630 rpnstack->s[stptr + 1] = rpnstack->s[stptr];
642 dummy = rpnstack->s[stptr];
643 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
644 rpnstack->s[stptr - 1] = dummy;
649 rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
653 if (isnan(rpnstack->s[stptr - 1]));
654 else if (isnan(rpnstack->s[stptr]))
655 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
657 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
658 rpnstack->s[stptr] ? 1.0 : 0.0;
663 if (isnan(rpnstack->s[stptr - 1]));
664 else if (isnan(rpnstack->s[stptr]))
665 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
667 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
668 rpnstack->s[stptr] ? 1.0 : 0.0;
673 if (isnan(rpnstack->s[stptr - 1]));
674 else if (isnan(rpnstack->s[stptr]))
675 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
677 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
678 rpnstack->s[stptr] ? 1.0 : 0.0;
683 if (isnan(rpnstack->s[stptr - 1]));
684 else if (isnan(rpnstack->s[stptr]))
685 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
687 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
688 rpnstack->s[stptr] ? 1.0 : 0.0;
693 if (isnan(rpnstack->s[stptr - 1]));
694 else if (isnan(rpnstack->s[stptr]))
695 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
697 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
698 rpnstack->s[stptr] ? 0.0 : 1.0;
703 if (isnan(rpnstack->s[stptr - 1]));
704 else if (isnan(rpnstack->s[stptr]))
705 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
707 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
708 rpnstack->s[stptr] ? 1.0 : 0.0;
713 rpnstack->s[stptr - 2] = (isnan(rpnstack->s[stptr - 2])
714 || rpnstack->s[stptr - 2] ==
715 0.0) ? rpnstack->s[stptr] : rpnstack->
722 if (isnan(rpnstack->s[stptr - 1]));
723 else if (isnan(rpnstack->s[stptr]))
724 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
725 else if (rpnstack->s[stptr - 1] > rpnstack->s[stptr])
726 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
731 if (isnan(rpnstack->s[stptr - 1]));
732 else if (isnan(rpnstack->s[stptr]))
733 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
734 else if (rpnstack->s[stptr - 1] < rpnstack->s[stptr])
735 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
740 if (isnan(rpnstack->s[stptr - 2]));
741 else if (isnan(rpnstack->s[stptr - 1]))
742 rpnstack->s[stptr - 2] = rpnstack->s[stptr - 1];
743 else if (isnan(rpnstack->s[stptr]))
744 rpnstack->s[stptr - 2] = rpnstack->s[stptr];
745 else if (rpnstack->s[stptr - 2] < rpnstack->s[stptr - 1])
746 rpnstack->s[stptr - 2] = DNAN;
747 else if (rpnstack->s[stptr - 2] > rpnstack->s[stptr])
748 rpnstack->s[stptr - 2] = DNAN;
753 rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
757 rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
761 rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
766 int spn = (int) rpnstack->s[stptr--];
768 stackunderflow(spn - 1);
769 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
776 int spn = (int) rpnstack->s[stptr--];
779 stackunderflow(spn - 1);
781 p = rpnstack->s + stptr - spn + 1;
782 q = rpnstack->s + stptr;
792 case OP_PREDICTSIGMA:
795 /* the local averaging window (similar to trend, but better here, as we get better statistics thru numbers)*/
796 int locstepsize = rpnstack->s[--stptr];
797 /* the number of shifts and range-checking*/
798 int shifts = rpnstack->s[--stptr];
799 stackunderflow(shifts);
800 // handle negative shifts special
806 /* the real calculation */
808 /* the info on the datasource */
809 time_t dsstep = (time_t) rpnp[rpi - 1].step;
810 int dscount = rpnp[rpi - 1].ds_cnt;
811 int locstep = (int)ceil((float)locstepsize/(float)dsstep);
817 /* now loop for each position */
819 if (shifts<0) { doshifts=-shifts; }
820 for(int loop=0;loop<doshifts;loop++) {
821 /* calculate shift step */
824 shiftstep = loop*rpnstack->s[stptr];
826 shiftstep = rpnstack->s[stptr+loop];
829 rrd_set_error("negative shift step not allowed: %i",shiftstep);
832 shiftstep=(int)ceil((float)shiftstep/(float)dsstep);
833 /* loop all local shifts */
834 for(int i=0;i<=locstep;i++) {
835 /* now calculate offset into data-array - relative to output_idx*/
836 int offset=shiftstep+i;
837 /* and process if we have index 0 of above */
838 if ((offset>=0)&&(offset<output_idx)) {
840 val =rpnp[rpi - 1].data[-dscount * offset];
841 /* and handle the non NAN case only*/
850 /* do the final calculations */
852 if (rpnp[rpi].op == OP_PREDICT) { /* the average */
854 val = sum/(double)count;
857 if (count>1) { /* the sigma case */
858 val=count*sum2-sum*sum;
862 val=sqrt(val/((float)count*((float)count-1.0)));
866 rpnstack->s[stptr] = val;
872 if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
873 rrd_set_error("malformed trend arguments");
876 time_t dur = (time_t) rpnstack->s[stptr];
877 time_t step = (time_t) rpnp[rpi - 2].step;
879 if (output_idx > (int) ceil((float) dur / (float) step)) {
880 int ignorenan = (rpnp[rpi].op == OP_TREND);
887 rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
888 if (ignorenan || !isnan(val)) {
896 rpnstack->s[--stptr] =
897 (count == 0) ? DNAN : (accum / count);
899 rpnstack->s[--stptr] = DNAN;
905 int i = (int) rpnstack->s[stptr--];
909 stackunderflow(i - 1);
911 double val = rpnstack->s[stptr--];
920 /* now push the result back on stack */
922 rpnstack->s[++stptr] = sum / count;
924 rpnstack->s[++stptr] = DNAN;
930 rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
935 #undef stackunderflow
938 rrd_set_error("RPN final stack size != 1");
942 output[output_idx] = rpnstack->s[0];
946 /* figure out what the local timezone offset for any point in
947 time was. Return it in seconds */
951 int gm_sec, gm_min, gm_hour, gm_yday, gm_year,
952 l_sec, l_min, l_hour, l_yday, l_year;
962 localtime_r(&now, &t);
969 (l_sec - gm_sec) + (l_min - gm_min) * 60 + (l_hour - gm_hour) * 3600;
970 if (l_yday > gm_yday || l_year > gm_year) {
972 } else if (l_yday < gm_yday || l_year < gm_year) {