/*============================================================================= Filename: mgntSub.c Abs: This file contains all subroutine support for the device control and readback (magnet) subroutine records. Rem: All functions called by the subroutine record get passed one argument: Functions: Description ------------ ---------------------------- mgntInit General Initialization mgntInitPoly Init for Records using Poly Coeffs mgntNumPolyCoef Find Number of Polynomial Coefficients mgntPoly Polynomial Conversion from B to I mgntDbPoly Conversion from B to I mgntReversePoly Estimate Value doing Reverse Poly I to B (Newton) mgntPhyDeltas Calc Reverse Polynomial Epsilon and Deltas for Alarm and Warning Limits in Physical Units mgntLimits Set Alarm and Warning Limits for ACT and MON mgntConLimits 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) Side: Place all functions called by the subroutine records in the mgntSub.dbd file also Auth: dd-mmm-yyyy, Author's Name (USERNAME) Rev: dd-mmm-yyyy, Reviewer's Name (USERNAME -------------------------------------------------------------- Mod: 11-Dec-2008, K. Luchini (LUCHINI): modified for motion control 23-Aug-2007, K. Luchini (LUCHINI): chg mgntRiplOK subroutine 13-Jan-2007, K. Luchini (LUCHINI): changed filename to mgntSub.c and added standard headers some some functions. dd-mmm-2005, Stephanie Allison (SAA): ported magnet subroutines from slc micro job. ==============================================================*/ #include "copyright_SLAC.h" /* Header files */ #include "debugPrint.h" #ifdef DEBUG_PRINT #include int mgntSubFlag = DP_INFO; #endif #include /* for calloc */ #include /* for DBADDR */ #include /* for struct subRecord */ #include /* for epicsExport */ #include /* for epicsRegisterFunction */ #include /* NO_ALARM, INVALID_ALARM */ #include /* for S_rec_outMem */ #include /* for S_dev_noDeviceFound */ #include /* for recGblRecordError() */ #include /* for DBF_DOUBLE */ #include /* Local function prototypes */ static long mgntDbPoly(subRecord *psub); /*============================================================================= Name: mgntInit Abs: Magnet initialization subroutine record Rem: Side: None Ret: int 0 - Successful (always) ==============================================================================*/ int mgntInit(subRecord *psub) { int status=SUCCESS; /* * 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(status); } /*============================================================================= Name: mgntInitPoly Abs: Initialize records that use polynomial coefficients. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:$(RAW)REQ and PRIM:LOCA:UNIT:$(PHY)ACT Input: -------- INPB = Number of polynomial coefficients - used to access the coefficients themselves Output: -------- DPVT = Pointer to polynomial coefficients Rem: Init Subroutine for PRIM:LOCA:UNIT:$(RAW)REQ and PRIM:LOCA:UNIT:$(PHY)ACT Side: None Ret: int 0 - Successful -1 - for invalid INPB ==============================================================================*/ int mgntInitPoly(subRecord *psub) { int status = SUCCESS; /* * Get polynomial coeffs - assume INPB is from a subRecord and * A through L are contiguous. Assume A is the constant term * and B to L are the higher order terms. */ DBADDR *pdbAddr = dbGetPdbAddrFromLink(&psub->inpb); psub->dpvt = 0; if (!pdbAddr) return -1; psub->dpvt = &((subRecord *)pdbAddr->precord)->a; return(status); } /*============================================================================= Name: mgntNumPolyCoef Abs: Find Number of Polynomial Coefficients. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: ------- A to L - Polynomial Coefficients Output: ------- VAL = Number of Coefficients Rem: Subroutine for PRIM:LOCA:UNIT:POLYCOEF Side: Ret: long 0 - Successful (always) ==============================================================================*/ long mgntNumPolyCoef(subRecord *psub) { long status = SUCCESS; int idx; double *polyCoef_a; /* Countdown until the most significant non-zero coefficient is found. */ /* Note: * for (idx = MGNT_MAX_POLY_COEF, polyCoef_a = &psub->l; * (idx > 0) && (polyCoef_a[idx] == 0); idx--) { } doesn't work */ polyCoef_a = &psub->l; for (idx = MGNT_MAX_POLY_COEF;(idx > 0) && (*polyCoef_a== 0); idx--, polyCoef_a--) {} psub->val = (double)idx; #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntNumPolyCoef for %s = %d.\n", psub->name, idx)); #endif return(status); } /*============================================================================= Name: mgntDbPoly Abs: Convert Physical Units to Raw Units using polynomial conversion. Use same algorithm as ref_rmx_dbs:dbpoly.a38 - see PDL in header at top of module. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- VAL = Value in Physical Units A = Spare B = Number of polynomial coefficients C = Polynomial Coeff A (offset if linear) D = Polynomial Coeff B (slope if linear) DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: ------- K = Value in Raw Units L = Slope of the polynomial at the DES value Rem: Called by mgntPoly and mgntReversePoly. Side: None Ret: long 0 - Successful -1 - if B is invalid or invalid pointer to poly coeffs. ==============================================================================*/ static long mgntDbPoly(subRecord *psub) { long status = SUCCESS; int idx; /* Simple linear conversion */ if (psub->b == LINEAR_COEF_NUM) { psub->l = psub->d; psub->k = psub->c + (psub->val * psub->d); } else { /* * Must have a valid number of coefficients and a valid poly coeff array */ if ((psub->b < LINEAR_COEF_NUM) || (psub->b > MGNT_MAX_POLY_COEF) || (!psub->dpvt)){ if (!psub->dpvt) { DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid coef array.\n", psub->name)); } else { DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid poly coef.\n", psub->name)); } DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid coef array; b: %f dpvt: %p\n", psub->name,psub->b, psub->dpvt )); status = ERROR; } else { /* * Do polynomial conversion using algorithm from ref_rmx_dbs:dbpoly.a38. * Find first derivative of the polynomial at the input value - * it'll be used to find reasonable alarm limits later. */ psub->k = 0.0; /* idx =psub->b-1; psub->k = ((double *)psub->dpvt)[idx];*/ /* highest order coeff */ psub->l = 0.0; for (idx = psub->b-1; idx >=0; idx--) { psub->l = (psub->l * psub->val) + psub->k; /* was + val*/ psub->k = (psub->k * psub->val) + ((double *)psub->dpvt)[idx]; } #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntDbPoly for %s: after loop- l: %f k: %f val: %f\n", psub->name, psub->l,psub->k,psub->val )); #endif } } return(status); } /*============================================================================= Name: mgntPoly Abs: Convert Physical Units to Raw Units using polynomial conversion. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- VAL = Value in Physical Units A = spare B = Number of polynomial coefficients C = Polynomial Coeff A (offset if linear) D = Polynomial Coeff B (slope if linear) E = Drive High Limit F = Drive Low Limit G = Fast Feedback Desired Value H = Fast Feedback Disable (0), Enable (1) DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: -------- K = Value in Raw Units L = Slope of the polynomial at the DES value Rem: Subroutine for PRIM:LOCA:UNIT:$(PHY)DES. Side: None Ret: long 0 - Successful -1 - If bad return from mgntDbPoly. ==============================================================================*/ long mgntPoly(subRecord *psub) { long status = SUCCESS; /* Use feedback value if feedback is enabled */ if (psub->h > 0.5) psub->val = psub->g; /* Adjust VAL if it's outside of reasonable limits */ if (psub->val > psub->e) psub->val = psub->e; else if (psub->val < psub->f) psub->val = psub->f; /* Perform conversion */ if (mgntDbPoly(psub)) { #ifdef DEBUG DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntPoly returning -1 for %s:\n", psub->name)); #endif status = ERROR; } return(status); } /*============================================================================= Name: mgntReversePoly Abs: Estimate Physical Units Value from Raw Value. Use same algorithm as ref_rmx_reentrant:reverse_dbpoly.c.86. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: ------- VAL = Initial Guess of Physical Units Value A = spare B = Number of polynomial coefficients - must be between 2 and 12. C = Polynomial Coeff A (offset if linear) D = Polynomial Coeff B (slope if linear) E = Raw Value F = Epsilon - desired accuracy of the Estimated Value G = Maximum iteration count DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: ------- H = Previous Estimate of Value in Physical Units I = Number of iterations J = Convergence Status (see defines at the top of the file) K = Value in Raw Units corresponding to VAL L = Slope of the polynomial at the DES value VAL = Final Estimate of Value in Physical Units Rem: Subroutine for PRIM:LOCA:UNIT:$(PHY)ACT and MON Side: None Ret: long 0 - Successful 1 - Failure ==============================================================================*/ long mgntReversePoly(subRecord *psub) { long status = SUCCESS; /* Simple linear conversion */ psub->h = psub->val; psub->j = MGNT_CONVERGED; if (psub->b == 2) { psub->i = 0; psub->l = psub->d; psub->val = psub->a = (psub->e - psub->c)/psub->d; } else { double diff = psub->f + 1; double prev_diff = psub->f; /* * Iterate until we get close enough. */ for (psub->i = 0.0; (psub->i <= psub->g) && (psub->j == MGNT_CONVERGED);psub->i += 1.0) { if (mgntDbPoly(psub)==-1) { psub->j = MGNT_POLY_ERROR; } else if ((psub->l > -MGNT_MIN_SLOPE) && (psub->l < MGNT_MIN_SLOPE)) { psub->j = MGNT_ZERO_SLOPE; } else if (diff <= psub->f) { #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s completed in %f iterations!!!\n", psub->name,psub->i )); #endif break; } else { /* save previous difference for verifying convergence */ prev_diff = diff; diff = MGNT_CHICKEN_FACTOR * (psub->e - psub->k)/psub->l; /* need a new guess: slide on the slope towards answer */ psub->h = psub->val; psub->val += diff; if (diff < 0) diff *= -1; } } /* End of FOR loop */ /* * Are we here because we ran into an error or ran out of iterations? */ if (psub->j != MGNT_CONVERGED) { #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: No convergence; J= %f\n", psub->name, psub->j)); #endif status = ERROR; } else if (psub->i > psub->g) { /* * Were we still on our way towards an answer? */ if (diff <= prev_diff) { psub->j = MGNT_ALMOST_CONVERGED; #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: almost converged; J= %f\n" ,psub->name, psub->j)); #endif } else { psub->j = MGNT_NO_CONVERGENCE; #ifdef DEBUG DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: convergence; J= %f\n",psub->name, psub->j)); #endif } status = ERROR; } } return(status); } /*============================================================================= Name: mgntPhyDelta Abs: Calculate deltas used for alarm and warning limits Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Inputs: -------- A = Desired Value(KDES) B = Actual Value (KACT) C = Minimum Warning Limit Delta D = Minimum Alarm Limit Delta E = Divisor of alarm limit delta to find epsilon (set to 30) Outputs: --------- I = ACT warning delta J = ACT alarm delta K = Out of tolerance (for trim; ="1" if out-of-tol) VAL = Epsilon Rem: Calculate deltas used for alarm and warning limits for ACT. Calculate epsilon used in the reverse polynomial calculation. Side: Warning and alarm deltas for ACT are fractions of DES Also check that the deltas are not too small (for small values of DES). Ret: int 0 - Successful (always) ==============================================================================*/ long mgntPhyDeltas(struct subRecord *psub) { long status = SUCCESS; if (psub->c > 0.0 ) { psub->i = psub->c; } else { psub->i = 0.0; } if (psub->d > 0.0) { psub->j = psub->d; } else { psub->j = 0.0; } /* * Epsilon must be a fraction of the ACT alarm delta. */ psub->val = psub->j; if (psub->e > 1.0) { psub->val /= psub->e; } /* see if bdes-bact > tolmax (i) */ psub->k = psub->a - psub->b; if (psub->k < 0) psub->k *= -1; if ( (psub->k) > psub-> i ){ psub-> k = 1; /* set out of tol */ } else psub->k = 0; /* reset out of tol */ return(status); } /*============================================================================= Name: mgntRawDeltas Abs: Calculate deltas used for alarm and warning limits Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Inputs: -------- A = Desired Value B = Raw/Physical Slope from mgntPoly (BDES.L ) D = Physical ACT Warning Delta (BDELTAS.I) E = Physical ACT Alarm Delta (BDELTAS.J) Outputs: ----------- I = ACT warning delta J = ACT alarm delta Rem: Calculate deltas used for alarm and warning limits for primary (ACT) and raw readbacks based on physical deltas. . Side: None Ret: int 0 - Successful (always) ==============================================================================*/ long mgntRawDeltas(struct subRecord *psub) { long status = SUCCESS; /* * Check for zero input deltas. Otherwise, multiply by slope to * get approximate raw deltas corresponding to physical deltas. */ if (psub->d > 0.0) psub->i = psub->d * psub->a; else psub->i = 0.0; if (psub->e > 0.0) psub->j = psub->e * psub->a; else psub->j = 0.0; return(status); } /*============================================================================= Name: mgntLimits Abs: Calculate K alarm and warning limits from deltas. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- A = Desired Field / Current B = Maximum (DRVH) C = Minimum (DRVL) D = Warning Delta (0 = disable) E = Alarm Delta (0 = disable) F = Disable Alarm Checking (ie, setpoint currently changing) (0=no, 1=yes) (0=calc limits, 1=set limits to min/max) Outputs: --------- I = HIGH value J = LOW value K = HIHI value L = LOLO value Rem: Calculate K alarm and warning limits from deltas. If the disable alarms flag is set or the supply is off, then use max/min values to disable alarms. Side: None Ret: int 0 - Successful (always) ==============================================================================*/ long mgntLimits(struct subRecord *psub) { long status = SUCCESS; psub->i = psub->b+1; psub->j = psub->c-1; psub->k = psub->b+1; psub->l = psub->c-1; /* are we disabling alarm checking? */ if (psub->f < 0.01) { /* No, so calculate upper and lower limits. * First check to see if warnings are disabled. * Set warning limitd */ if (psub->d > 0.0) { psub->i = psub->a + psub->d; psub->j = psub->a - psub->d; } /* If alarms are not disabled, then set alarm limits */ if (psub->e > 0.0) { psub->k = psub->a + psub->e; psub->l = psub->a - psub->e; } } return(status); } /*============================================================================= Name: mgntConLimits Abs: Calculate alarm and warning limits for KCON from KDES Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- A = Desired Field / Current C = B field Warning Delta calculated (from KDELTAS.I) Output: --------- I = HIGH value J = LOW value K = HIHI value L = LOLO value VAL = BCON Rem: Side: If KDES does not equal KCON, it turns yellow. Use check tolerance (warning) for epsilon around bdes. Ret: int 0 - Successful (always) ==============================================================================*/ long mgntConLimits(struct subRecord *psub) { long status = SUCCESS; /* double epsilon = 5e-08;*/ /* display precision is 7 */ psub->high = psub->a + psub->c; psub->low = psub->a - psub->c; psub->hihi = psub->a + psub->c; psub->lolo = psub->a - psub->c; return(status); } epicsRegisterFunction(mgntInit); epicsRegisterFunction(mgntInitPoly); epicsRegisterFunction(mgntNumPolyCoef); epicsRegisterFunction(mgntPoly); epicsRegisterFunction(mgntReversePoly); epicsRegisterFunction(mgntPhyDeltas); epicsRegisterFunction(mgntRawDeltas); epicsRegisterFunction(mgntLimits); epicsRegisterFunction(mgntConLimits); /* Note - when adding a funciton, also add to mgntSub.dbd */