/* Copyright 1996 ** by ** The Board of Trustees of the ** Leland Stanford Junior University. ** All rights reserved. ** ** ** Work supported by the U.S. Department of Energy under contract ** DE-AC03-76SF00515. ** ** Disclaimer Notice ** ** The items furnished herewith were developed under the sponsorship ** of the U.S. Government. Neither the U.S., nor the U.S. D.O.E., nor the ** Leland Stanford Junior University, nor their employees, makes any war- ** ranty, express or implied, or assumes any liability or responsibility ** for accuracy, completeness or usefulness of any information, apparatus, ** product or process disclosed, or represents that its use will not in- ** fringe privately-owned rights. Mention of any product, its manufactur- ** er, or suppliers shall not, nor is it intended to, imply approval, dis- ** approval, or fitness for any particular use. The U.S. and the Univer- ** sity at all times retain the right to use and disseminate the furnished ** items for any purpose whatsoever. Notice 91 02 01 */ /*============================================================================= Abs: Functions for system monitoring and control. Name: subSys.c subSysInit - Initialization subSysFitLSqInit - Initialization for linear square fit subSysLogDel - MDEL/ADEL Check for Exponential Signals (Vacuums) subSysExp - Calculate Value from Log of the Value subSysPoly - Calculate Value using a Polynomial subSysLog - Calculate Log of a Value subSysFitLSq - Calculate Proto: not required and not used. All functions called by the subroutine record get passed one argument: psub Pointer to the subroutine record data. Use: pointer In general, all functions read the Type: struct subRecord * input fields (a to l) and write to Acc: read/write the val field. Mech: reference All functions return a long integer. 0 = OK, -1 = ERROR. The subroutine record ignores the status returned by the Init routines. For the calculation routines, the record status (STAT) is set to SOFT_ALARM (unless it is already set to LINK_ALARM due to severity maximization) and the severity (SEVR) is set to psub->brsv (BRSV - set by the user in the database though it is expected to be invalid). Auth: 04-Oct-2001, Stephanie Allison Rev: DD-MMM-YYYY, Reviewer's Name (.NE. Author's Name) ------------------------------------------------------------------------------- Mod: 26-Nov-2012, K. Luchini (LUCHINI): add function subSysLinSqFit =============================================================================*/ #ifdef __vxworks #include /* ERROR, OK */ #else #ifndef ERORR #define ERROR -1 #endif #ifndef OK #define OK 0 #endif #endif #include #include /* for pow and sqrt prototypes */ #include /* for uint32_t */ #include /* for epicsMutexId */ #include /* for S_rec_outMem */ #include /* for struct subRecord */ #include /* for struct aSubRecord */ #include /* for recGblRecordError() */ #include /* for DBF_DOUBLE */ #include /* for callocMustSucceed prototype */ #include /* for S_db_badField */ #include /* for S_dev_badInit */ #include /* for epicsExport() */ #include /* for epicsRegisterFunction() */ #include /* Local macros and typedefs */ #define min(x, y) (((x) < (y)) ? (x) : (y)) typedef struct devicePvt_s { uint32_t npts; /* maximum number of points */ epicsMutexId mlock; /* mutex id */ }devicePvt_ts; long subSysInit(struct subRecord *psub) { /* * General purpose initialization required since all subroutine records * require a non-NULL init routine even if no initialization is required. * Note that most subroutines in this file use this routine as an init * routine. If init logic is needed for a specific subroutine, create a * new routine for it - don't modify this one. */ return(OK); } long subSysFitLSqInit(aSubRecord *psub) { /* * Initialize records for Linear Square Fit function * * Input: * -------- * A = Number of points to be fit (NPTS) * B = Array of X values * C = Array of Y values * * Output: * -------- * VALA = the constant term (Y-intercept) - i.e. (SUMX2*SUMY - SUMX*SUMXY)/DELTA * VALB = the X coefficient (slope) - i.e. (NPTS*SUMXY - SUMX*SUMY)/DELTA * VALC = the measure of goodness of fit * */ long status = ERROR; devicePvt_ts *pdpvt = NULL; /* Check that this pv has not already been initialized */ if (psub->dpvt) recGblRecordError(S_dev_badInit,(void *)psub,"subSysFitLSqInit: already initialized"); else if (psub->ftb!=DBF_DOUBLE) recGblRecordError(S_db_badField,(void *)psub,"subSysFitLSqInit: bad FTB field, expect DOUBLE"); else if (psub->ftc!=DBF_DOUBLE) recGblRecordError(S_db_badField,(void *)psub,"subSysFitLSqInit: bad FTC field, expect DOUBLE"); else status = OK; if (status) return(status); /* Allocate memory for private device information */ psub->dpvt = 0; pdpvt = callocMustSucceed(1,sizeof(devicePvt_ts),"calloc failed for subSysFitLSqInit" ); pdpvt->mlock = epicsMutexMustCreate(); /* * Get number of points in arrays. The arrays should contain the * same number of elemnts, but if not then use the smallest array */ pdpvt->npts = min(psub->nob,psub->noc); if (pdpvt->npts<0) pdpvt->npts = 0; psub->dpvt = pdpvt; return(status); } long subSysLogDel (struct subRecord *psub) { /* * Do ADEL/MDEL checks on the log of an input exponential value (vacuum). * Inputs: A = Exponential Value * C = Not First Time Flag (0 = First Time, 1 = Not First Time) * D = Spare * E = Monitor Delta for the Log * F = Archive Delta for the Log * I = Previous Non-Zero Monitor Delta * J = Previous Non-Zero Archive Delta * K = Previous Monitored Value of the Log * L = Previous Archived Value of the Log * MDEL = Monitor Delta * ADEL = Archive Delta * Outputs: VAL = Exponential Value (Same as A) * B = Log of the Value * G = B - K * H = B - L * I = Previous Non-Zero Monitor Delta * J = Previous Non-Zero Archive Delta * K = Previous Monitored Value of the Log * L = Previous Archived Value of the Log * MDEL = Monitor Delta * ADEL = Archive Delta */ /* * Set the value and find its log if its positive. */ psub->val = psub->a; if (psub->a <= 0.0) return (ERROR); psub->b = log10(psub->a); /* * Override positive mdel if the log's had a monitor change. * Note - if user has set mdel to a negative value, then they * specifically want a monitor every time the record processes. */ psub->g = psub->b - psub->k; if ((psub->c == 0) || (psub->g > psub->e) || ((-psub->g) > psub->e)) { psub->k = psub->b; if (psub->mdel >= 0) { psub->i = psub->mdel; psub->mdel = -1; } } /* * No monitor change - restore mdel if it was saved. */ else if (psub->i >= 0) { psub->mdel = psub->i; psub->i = -1; } /* * Override positive adel if the log's had an archive change. * Note - if user has set adel to a negative value, then they * specifically want an archive every time the record processes. */ psub->h = psub->b - psub->l; if ((psub->c == 0) || (psub->h > psub->f) || ((-psub->h) > psub->f)) { psub->l = psub->b; if (psub->adel >= 0) { psub->j = psub->adel; psub->adel = -1; } } /* * No archive change - restore adel if it was saved. */ else if (psub->j >= 0) { psub->adel = psub->j; psub->j = -1; } /* Set not-first-time flag. */ psub->c = 1; return(OK); } long subSysExp (struct subRecord *psub) { /* * Calculate value from the log of the value, as for power * from an ADC voltage reading: * * value = c0 + (c1 * 10**(c2+c3*input)) * * Inputs: A = c0 (default = 0) * B = c1 (default = 1) * C = c2 (offset applied to input, default = 0) * D = c3 (slope applied to input, default = 1) * E = Spare * F = Last Monitored Value of the Log (MLST) * G = Last Archived Value of the Log (ALST) * H = Previous Non-Zero Monitor Delta * I = Previous Non-Zero Archive Delta * J = Previous Monitored Value of the Log * K = Previous Archived Value of the Log * L = Input Log of the Value * MDEL = Monitor Delta * ADEL = Archive Delta * Outputs: VAL = Value from the Log * H = Previous Non-Zero Monitor Delta * I = Previous Non-Zero Archive Delta * J = Previous Monitored Value of the Log * K = Previous Archived Value of the Log * L = Adjusted Input Log of the Value * MDEL = Monitor Delta * ADEL = Archive Delta */ /* * Check for valid constants, adjust input, and calculate value. */ if (psub->b == 0.0) psub->b = 1.0; if (psub->d == 0.0) psub->d = 1.0; psub->l = (psub->l*psub->d) + psub->c; psub->val = psub->a + (psub->b * pow(10.0, psub->l)); /* * Force a monitor if the log of the value had one. */ if (psub->mdel != 0.0) psub->h = psub->mdel; if (psub->f == psub->j) psub->mdel = psub->h; else { psub->j = psub->f; psub->mdel = 0.0; } /* * Force an archive if the log of the value had one. */ if (psub->adel != 0.0) psub->i = psub->adel; if (psub->g == psub->k) psub->adel = psub->i; else { psub->k = psub->g; psub->adel = 0.0; } return(OK); } long subSysPoly (struct subRecord *psub) { /* * Calculate value using polynomial: * * value = c0 + (c1*input) + (c2*input**2) + (c3*input**3) + (c4*input**4) * * Inputs: A = c0 * B = c1 * C = c2 * D = c3 * E = c4 * F = Last Monitored Value of the Input (MLST) (Not Used) * G = Last Archived Value of the Input (ALST) (Not Used) * L = Input * Outputs: VAL = Value */ psub->val = psub->a + (psub->l * (psub->b + (psub->l * (psub->c + (psub->l * (psub->d + (psub->l * psub->e))))))); return(OK); } long subSysLog (struct subRecord *psub) { /* * Calculate log of a value as for DAC voltage control from a * desired power setpoint: * * value = (log10((input - c0) / c1) / c3) - c2 * * Inputs: A = c0 (default = 0) * B = c1 (default = 1) * C = c2 (offset applied to input, default = 0) * D = c3 (slope applied to input, default = 1) * E = Spare * L = Input Value * Outputs: VAL = Log of the Value * K = Adjusted Input */ /* * Check for valid constants, adjust input, and calculate value. */ if (psub->b == 0.0) psub->b = 1.0; if (psub->d == 0.0) psub->d = 1.0; psub->k = (psub->l - psub->a) / psub->b; if (psub->k <= 0.0) return (ERROR); psub->val = (log10(psub->k) / psub->d) - psub->c; return(OK); } long subSysFitLSq(aSubRecord *psub) { /* * Calculation to fit a line Y = C0 + C1*X to a collection of points * * Input: * -------- * A = Number of points to be fit (NPTS) * B = Array of X values * C = Array of Y values * F = debug flag (1=debug mode, 0=normal mode) * * Output: * -------- * VALA = the constant term (Y-intercept) * VALB = the X coefficient (slope) * VALC = coefficient of determination (r^2), which is referred * to as the measure of goodness of fit * */ long status = ERROR; uint32_t npts = *(uint32_t *)psub->a; devicePvt_ts *pdpvt = NULL; uint32_t dbgFlag = *(uint32_t *)psub->f; /* Initialize output values */ *(double *)psub->vala = 0.0; *(double *)psub->valb = 0.0; *(double *)psub->valc = 0.0; /* Check that this pv been initialized */ if (!psub->dpvt) { if (dbgFlag) printf("FitLSq: %s not not initialized\n",psub->name); return(status); } status = OK; pdpvt = (devicePvt_ts *)psub->dpvt; npts = min(npts,pdpvt->npts); /* * Accumulate the sums. Make sure to set the lock first * so that the data doesn't change out from under us. */ if (dbgFlag) printf("\nFitLSq: %s\n",psub->name); epicsMutexMustLock( pdpvt->mlock ); status = FitLSq( npts, (double *)psub->b, (double *)psub->c, (double *)psub->vala, (double *)psub->valb, (double *)psub->valc, dbgFlag ); epicsMutexUnlock( pdpvt->mlock ); return(status); } long subSysFitLSqResidual(aSubRecord *psub) { /* * Calculate to fit a line Y = C0 + C1*X to a collection of points * * Input: * -------- * A = Number of points to be fit (NPTS) * B = Array of X values * C = Array of Y values * D = Calibrated intercept * E = Calibrated slope * F = Slope used to convert from current to voltage * * Output: * -------- * VALA = the measure of goodness of fit * */ long status = ERROR; uint32_t npts; devicePvt_ts *pdpvt = NULL; /* Check that this pv been initialized */ *(double *)psub->vala = 0.0; if (!psub->dpvt) return(status); status = OK; pdpvt = (devicePvt_ts *)psub->dpvt; npts = min((*(uint32_t *)psub->a),pdpvt->npts); epicsMutexMustLock( pdpvt->mlock ); status = FitLSqResidual( npts, (double *)psub->b, (double *)psub->c, *(double *)psub->d, *(double *)psub->e, *(double *)psub->vala, *(double *)psub->valb, (double *)psub->vald, 0 ); epicsMutexUnlock(pdpvt->mlock); return(status); } long FitLSq( uint32_t npts, double *x_a, double *y_a, double *pintercept, double *pslope, double *presidual, uint32_t dbgFlag ) /* * Calculate to fit a line Y = A0 + A1*X to a collection of points * * Args: * -------- * npts - Number of points to be fit (NPTS) * x_a - Array of X values * y_a - Array of Y values * pintercept - pointer to y intercept (A0) * pslope - pointer to slope (A1) * presidual - measure of goodness of fit * dbgFlag - debug mode (1=debug mode, 0=normal mode) * */ { long status = OK; uint32_t i; double sum_x=0; /* sum of x */ double sum_y=0; /* sum of y */ double sum_xx=0; /* sum of x^2 */ double sum_xy=0; /* sum of x * y */ double sum_yy=0; double sum_res=0.0; /* sum of squared residue */ double res=0.0; /* residue squared */ double slope=0; /* slope of regression line */ double y_intercept=0.0; /* y intecept of regression line */ double sum_y_res=0.0; /* sum of squared of the discrepancies */ double avg_y=0.0; /* mean of y */ double avg_x=0.0; /* mean of x */ double y_res=0.0; /* squared of the discrepancies */ double r_sqr=0.0; /* coefficient of determination */ double j; #define MIN_DELTA 1.0E-10 /* Initialize output values */ *presidual = 0.0; *pintercept = 0.0; *pslope = 0.0; if (npts<=1) { if (dbgFlag) printf("FitLSq: Too few data points (%u)\n",npts); return(ERROR); } /* Accumulate the sums. */ for (i=0; iMIN_DELTA) slope = (npts*sum_xy - sum_x*sum_y)/j; else if (dbgFlag) printf("Warning slope is near 0"); /* calculate y-intercept or a0*/ y_intercept = avg_y-slope * avg_x; if (dbgFlag) { printf("x mean(avg_x) = %0.5E\n",avg_x); printf("y mean(avg_y) = %0.5E\n",avg_y); printf("\nThe linear equation that best fits the given data:\n"); printf(" y = %2.8lfx + %2.8f\n",slope,y_intercept); printf("---------------------------------------------\n"); printf(" Original (xy) (y_i - y_avg)^2 (y_i - a_0) - a_1*x_i)^2\n"); printf("---------------------------------------------\n"); } /* calculate squared residues, their sum etc. */ for (i=0; i1) j = sqrt(sum_res/(npts-1)); else j=0; if (dbgFlag) printf("Standard deviations(St) = %0.5E\n",j); if (sum_res) j= (sum_res - sum_y_res)/sum_res; else j=0; if (dbgFlag) { printf("Coefficient of determination(r^2) = %0.5E (goodfit)\n",j); if (r_sqr>0) printf("Correlation coefficient(r) = %0.5E\t\n",sqrt(r_sqr)); else printf("Correlation coefficient(r) not avail, since r_sqr=%0.5E\n",r_sqr); } /* return caluclated values */ *pslope = slope; *pintercept = y_intercept; *presidual = j; return(status); } long FitLSqResidual(uint32_t npts, double *iact_a, double *dac_a, double intercept, double slope, double intercept_dac, double slope_dac, double *presidual, uint32_t dbgFlag) { long status = OK; uint32_t i = 0; double calc_volt; double calc_dac; double diff_dac; /* difference between dac and calculated dac */ *presidual = 0.0; if (!npts) { if (dbgFlag) printf("FitLSqResidual: No data points\n"); return(ERROR); } else if (slope_dac==0.0) { if (dbgFlag) printf("FitLSqResidual: Error, due to zero slopes\n"); return(ERROR); } for (i=0; i