Changeset 1407
- Timestamp:
- Aug 6, 2004, 2:06:06 PM (22 years ago)
- Location:
- trunk/psLib/src
- Files:
-
- 110 edited
-
astro/psCoord.c (modified) (13 diffs)
-
astro/psCoord.h (modified) (12 diffs)
-
astro/psTime.c (modified) (27 diffs)
-
astro/psTime.h (modified) (18 diffs)
-
astronomy/psAstrometry.c (modified) (7 diffs)
-
astronomy/psAstrometry.h (modified) (10 diffs)
-
astronomy/psCoord.c (modified) (13 diffs)
-
astronomy/psCoord.h (modified) (12 diffs)
-
astronomy/psMetadata.c (modified) (27 diffs)
-
astronomy/psMetadata.h (modified) (19 diffs)
-
astronomy/psPhotometry.h (modified) (4 diffs)
-
astronomy/psTime.c (modified) (27 diffs)
-
astronomy/psTime.h (modified) (18 diffs)
-
collections/psArray.c (modified) (8 diffs)
-
collections/psArray.h (modified) (8 diffs)
-
collections/psBitSet.c (modified) (17 diffs)
-
collections/psBitSet.h (modified) (12 diffs)
-
collections/psCompare.c (modified) (2 diffs)
-
collections/psCompare.h (modified) (44 diffs)
-
collections/psList.c (modified) (29 diffs)
-
collections/psList.h (modified) (15 diffs)
-
collections/psMetadata.c (modified) (27 diffs)
-
collections/psMetadata.h (modified) (19 diffs)
-
collections/psScalar.c (modified) (13 diffs)
-
collections/psScalar.h (modified) (6 diffs)
-
collections/psVector.c (modified) (18 diffs)
-
collections/psVector.h (modified) (9 diffs)
-
dataManip/psFFT.c (modified) (24 diffs)
-
dataManip/psFFT.h (modified) (4 diffs)
-
dataManip/psFunctions.c (modified) (48 diffs)
-
dataManip/psFunctions.h (modified) (11 diffs)
-
dataManip/psMatrix.c (modified) (28 diffs)
-
dataManip/psMatrix.h (modified) (12 diffs)
-
dataManip/psMatrixVectorArithmetic.c (modified) (20 diffs)
-
dataManip/psMatrixVectorArithmetic.h (modified) (5 diffs)
-
dataManip/psMinimize.c (modified) (63 diffs)
-
dataManip/psMinimize.h (modified) (3 diffs)
-
dataManip/psStats.c (modified) (66 diffs)
-
dataManip/psStats.h (modified) (4 diffs)
-
dataManip/psVectorFFT.c (modified) (24 diffs)
-
dataManip/psVectorFFT.h (modified) (4 diffs)
-
fft/psVectorFFT.c (modified) (24 diffs)
-
fft/psVectorFFT.h (modified) (4 diffs)
-
image/psImage.c (modified) (15 diffs)
-
image/psImage.h (modified) (8 diffs)
-
image/psImageExtraction.c (modified) (10 diffs)
-
image/psImageExtraction.h (modified) (5 diffs)
-
image/psImageIO.c (modified) (19 diffs)
-
image/psImageIO.h (modified) (4 diffs)
-
image/psImageManip.c (modified) (34 diffs)
-
image/psImageManip.h (modified) (8 diffs)
-
image/psImageStats.c (modified) (21 diffs)
-
image/psImageStats.h (modified) (3 diffs)
-
imageops/psImageStats.c (modified) (21 diffs)
-
imageops/psImageStats.h (modified) (3 diffs)
-
math/psCompare.c (modified) (2 diffs)
-
math/psCompare.h (modified) (44 diffs)
-
math/psMatrix.c (modified) (28 diffs)
-
math/psMatrix.h (modified) (12 diffs)
-
math/psMinimize.c (modified) (63 diffs)
-
math/psMinimize.h (modified) (3 diffs)
-
math/psPolynomial.c (modified) (48 diffs)
-
math/psPolynomial.h (modified) (11 diffs)
-
math/psSpline.c (modified) (48 diffs)
-
math/psSpline.h (modified) (11 diffs)
-
math/psStats.c (modified) (66 diffs)
-
math/psStats.h (modified) (4 diffs)
-
mathtypes/psImage.c (modified) (15 diffs)
-
mathtypes/psImage.h (modified) (8 diffs)
-
mathtypes/psScalar.c (modified) (13 diffs)
-
mathtypes/psScalar.h (modified) (6 diffs)
-
mathtypes/psVector.c (modified) (18 diffs)
-
mathtypes/psVector.h (modified) (9 diffs)
-
pslib.h (modified) (8 diffs)
-
sys/psAbort.c (modified) (10 diffs)
-
sys/psAbort.h (modified) (4 diffs)
-
sys/psError.c (modified) (10 diffs)
-
sys/psError.h (modified) (4 diffs)
-
sys/psLogMsg.c (modified) (18 diffs)
-
sys/psLogMsg.h (modified) (8 diffs)
-
sys/psMemory.c (modified) (26 diffs)
-
sys/psMemory.h (modified) (20 diffs)
-
sys/psString.c (modified) (11 diffs)
-
sys/psString.h (modified) (6 diffs)
-
sys/psTrace.c (modified) (25 diffs)
-
sys/psTrace.h (modified) (3 diffs)
-
sys/psType.h (modified) (8 diffs)
-
sysUtils/psAbort.c (modified) (10 diffs)
-
sysUtils/psAbort.h (modified) (4 diffs)
-
sysUtils/psError.c (modified) (10 diffs)
-
sysUtils/psError.h (modified) (4 diffs)
-
sysUtils/psHash.c (modified) (20 diffs)
-
sysUtils/psHash.h (modified) (2 diffs)
-
sysUtils/psLogMsg.c (modified) (18 diffs)
-
sysUtils/psLogMsg.h (modified) (8 diffs)
-
sysUtils/psMemory.c (modified) (26 diffs)
-
sysUtils/psMemory.h (modified) (20 diffs)
-
sysUtils/psString.c (modified) (11 diffs)
-
sysUtils/psString.h (modified) (6 diffs)
-
sysUtils/psTrace.c (modified) (25 diffs)
-
sysUtils/psTrace.h (modified) (3 diffs)
-
sysUtils/psType.h (modified) (8 diffs)
-
types/psArray.c (modified) (8 diffs)
-
types/psArray.h (modified) (8 diffs)
-
types/psBitSet.c (modified) (17 diffs)
-
types/psBitSet.h (modified) (12 diffs)
-
types/psList.c (modified) (29 diffs)
-
types/psList.h (modified) (15 diffs)
-
types/psMetadata.c (modified) (27 diffs)
-
types/psMetadata.h (modified) (19 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/psLib/src/astro/psCoord.c
r1406 r1407 1 1 2 /** @file psCoord.c 2 3 * … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 #include <float.h> 28 29 29 static float cot( float x);30 static float arg( float x, float y);30 static float cot(float x); 31 static float arg(float x, float y); 31 32 32 33 // This is the only function in this file which I understand. 33 psPlane *psPlaneTransformApply( psPlane *out, 34 const psPlaneTransform *transform, 35 const psPlane *coords ) 36 { 37 if ( out == NULL ) { 38 out = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 39 } 40 out->x = transform->x->coeff[ 0 ][ 0 ] + 41 ( transform->x->coeff[ 1 ][ 0 ] * coords->x ) + 42 ( transform->x->coeff[ 0 ][ 1 ] * coords->y ); 43 44 out->y = transform->y->coeff[ 0 ][ 0 ] + 45 ( transform->y->coeff[ 1 ][ 0 ] * coords->x ) + 46 ( transform->y->coeff[ 0 ][ 1 ] * coords->y ); 47 48 return ( out ); 49 } 50 34 psPlane *psPlaneTransformApply(psPlane * out, const psPlaneTransform * transform, const psPlane * coords) 35 { 36 if (out == NULL) { 37 out = (psPlane *) psAlloc(sizeof(psPlane)); 38 } 39 out->x = transform->x->coeff[0][0] + 40 (transform->x->coeff[1][0] * coords->x) + (transform->x->coeff[0][1] * coords->y); 41 42 out->y = transform->y->coeff[0][0] + 43 (transform->y->coeff[1][0] * coords->x) + (transform->y->coeff[0][1] * coords->y); 44 45 return (out); 46 } 51 47 52 48 // This transformation takes into account parameters beyond an objects 53 49 // spatial coordinates: term3 and term4. 54 psPlane *psPlaneDistortApply( psPlane *out, 55 const psPlaneDistort *transform, 56 const psPlane *coords, 57 float term3, 58 float term4 ) 59 { 60 if ( out == NULL ) { 61 out = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 62 } 63 64 out->x = transform->x->coeff[ 0 ][ 0 ][ 0 ][ 0 ] + 65 ( transform->x->coeff[ 1 ][ 0 ][ 0 ][ 0 ] * coords->x ) + 66 ( transform->x->coeff[ 0 ][ 1 ][ 0 ][ 0 ] * coords->y ) + 67 ( transform->x->coeff[ 0 ][ 0 ][ 1 ][ 0 ] * term3 ) + 68 ( transform->x->coeff[ 0 ][ 0 ][ 0 ][ 1 ] * term4 ); 69 70 out->y = transform->y->coeff[ 0 ][ 0 ][ 0 ][ 0 ] + 71 ( transform->y->coeff[ 1 ][ 0 ][ 0 ][ 0 ] * coords->x ) + 72 ( transform->y->coeff[ 0 ][ 1 ][ 0 ][ 0 ] * coords->y ) + 73 ( transform->y->coeff[ 0 ][ 0 ][ 1 ][ 0 ] * term3 ) + 74 ( transform->y->coeff[ 0 ][ 0 ][ 0 ][ 1 ] * term4 ); 75 76 return ( out ); 77 } 78 50 psPlane *psPlaneDistortApply(psPlane * out, 51 const psPlaneDistort * transform, 52 const psPlane * coords, float term3, float term4) 53 { 54 if (out == NULL) { 55 out = (psPlane *) psAlloc(sizeof(psPlane)); 56 } 57 58 out->x = transform->x->coeff[0][0][0][0] + 59 (transform->x->coeff[1][0][0][0] * coords->x) + 60 (transform->x->coeff[0][1][0][0] * coords->y) + 61 (transform->x->coeff[0][0][1][0] * term3) + (transform->x->coeff[0][0][0][1] * term4); 62 63 out->y = transform->y->coeff[0][0][0][0] + 64 (transform->y->coeff[1][0][0][0] * coords->x) + 65 (transform->y->coeff[0][1][0][0] * coords->y) + 66 (transform->y->coeff[0][0][1][0] * term3) + (transform->y->coeff[0][0][0][1] * term4); 67 68 return (out); 69 } 79 70 80 71 // This function prototype has been modified since the SDRS. 81 psSphereTransform *psSphereTransformAlloc( double NPlat, 82 double Xo, 83 double xo ) 84 { 85 psSphereTransform * tmp = ( psSphereTransform * ) psAlloc( sizeof( psSphereTransform ) ); 86 87 tmp->sinPhi = sin( NPlat ); 88 tmp->cosPhi = cos( NPlat ); 72 psSphereTransform *psSphereTransformAlloc(double NPlat, double Xo, double xo) 73 { 74 psSphereTransform *tmp = (psSphereTransform *) psAlloc(sizeof(psSphereTransform)); 75 76 tmp->sinPhi = sin(NPlat); 77 tmp->cosPhi = cos(NPlat); 89 78 tmp->Xo = Xo; 90 79 tmp->xo = xo; 91 80 92 return ( tmp);81 return (tmp); 93 82 } 94 83 … … 100 89 // there are no typo's. 101 90 102 psSphere *psSphereTransformApply( psSphere *out, 103 const psSphereTransform *transform, 104 const psSphere *coord ) 91 psSphere *psSphereTransformApply(psSphere * out, const psSphereTransform * transform, const psSphere * coord) 105 92 { 106 93 double sinY = 0.0; … … 112 99 double dx = 0.0; 113 100 114 if ( out == NULL) {115 out = ( psSphere * ) psAlloc( sizeof( psSphere ));101 if (out == NULL) { 102 out = (psSphere *) psAlloc(sizeof(psSphere)); 116 103 } 117 104 … … 119 106 y = coord->d; 120 107 dx = x - transform->xo; 121 sinY = cos( y ) * sin( dx ) * transform->sinPhi + sin( y ) * transform->cosPhi; 122 cosY = sqrt( 1.0 - sinY * sinY ); 123 sinX = ( cos( y ) * sin( dx ) * transform->cosPhi - sin( y ) * transform->sinPhi ) / 124 cos( y ); 125 cosX = cos( y ) * cos( dx ) / cos( y ); 126 127 out->r = atan2( sinX, cosX ) + transform->Xo; 128 out->d = atan2( sinY, cosY ); 129 130 return ( out ); 131 } 132 133 psSphereTransform *psSphereTransformICRStoEcliptic( psTime time ) 134 { 135 struct tm * tmTime = psTimeToTM( time ); 136 double year = ( double ) ( 1900 + tmTime->tm_year ); 108 sinY = cos(y) * sin(dx) * transform->sinPhi + sin(y) * transform->cosPhi; 109 cosY = sqrt(1.0 - sinY * sinY); 110 sinX = (cos(y) * sin(dx) * transform->cosPhi - sin(y) * transform->sinPhi) / cos(y); 111 cosX = cos(y) * cos(dx) / cos(y); 112 113 out->r = atan2(sinX, cosX) + transform->Xo; 114 out->d = atan2(sinY, cosY); 115 116 return (out); 117 } 118 119 psSphereTransform *psSphereTransformICRStoEcliptic(psTime time) 120 { 121 struct tm *tmTime = psTimeToTM(time); 122 double year = (double)(1900 + tmTime->tm_year); 137 123 double T = year / 100.0; 138 124 double phi = -23.452294 + 0.013013 * T + 0.000001639 * T * T - 0.000000503 * T * T * T; … … 140 126 double xo = 0.0; 141 127 142 return ( psSphereTransformAlloc( phi, Xo, xo ));143 } 144 145 psSphereTransform *psSphereTransformEcliptictoICRS( psTime time)146 { 147 struct tm * tmTime = psTimeToTM( time);148 double year = ( double ) ( 1900 + tmTime->tm_year);128 return (psSphereTransformAlloc(phi, Xo, xo)); 129 } 130 131 psSphereTransform *psSphereTransformEcliptictoICRS(psTime time) 132 { 133 struct tm *tmTime = psTimeToTM(time); 134 double year = (double)(1900 + tmTime->tm_year); 149 135 double T = year / 100.0; 150 double phi = + 23.452294 - 0.013013 * T - 0.000001639 * T * T + 0.000000503 * T * T * T;136 double phi = +23.452294 - 0.013013 * T - 0.000001639 * T * T + 0.000000503 * T * T * T; 151 137 double Xo = 0.0; 152 138 double xo = 0.0; 153 139 154 return ( psSphereTransformAlloc( phi, Xo, xo ));155 } 156 157 psSphereTransform *psSphereTransformICRStoGalatic( void)158 { 159 return ( psSphereTransformAlloc( 62.6, 282.25, 33.0 ));160 } 161 162 psSphereTransform *psSphereTransformGalatictoICRS( void)163 { 164 return ( psSphereTransformAlloc( -62.6, 33.0, 282.25 ));140 return (psSphereTransformAlloc(phi, Xo, xo)); 141 } 142 143 psSphereTransform *psSphereTransformICRStoGalatic(void) 144 { 145 return (psSphereTransformAlloc(62.6, 282.25, 33.0)); 146 } 147 148 psSphereTransform *psSphereTransformGalatictoICRS(void) 149 { 150 return (psSphereTransformAlloc(-62.6, 33.0, 282.25)); 165 151 } 166 152 167 153 // XXX: Is this the correct way to calculate this? 168 float cot( float x)169 { 170 return ( 1.0 / atan( x ));154 float cot(float x) 155 { 156 return (1.0 / atan(x)); 171 157 } 172 158 173 159 // This is some kind of arc tan function. 174 float arg( float x, float y ) 175 { 176 if ( x > 0 ) { 177 return ( atan( y / x ) ); 178 } else 179 if ( ( x == 0 ) && ( y == 0 ) ) { 180 return ( 0.5 * M_PI ); 181 } else 182 if ( ( x == 0 ) && ( y == 0 ) ) { 183 return ( -0.5 * M_PI ); 184 } else 185 if ( ( x == 0 ) && ( y == 0 ) ) { 186 return ( M_PI + atan( y / x ) ); 187 } else 188 if ( ( x == 0 ) && ( y == 0 ) ) { 189 return ( -M_PI + atan( y / x ) ); 190 } 191 192 psAbort( __func__, "Unacceptable range for (arg(%f, %f).\n", x, y ); 193 return ( 0.0 ); 160 float arg(float x, float y) 161 { 162 if (x > 0) { 163 return (atan(y / x)); 164 } else if ((x == 0) && (y == 0)) { 165 return (0.5 * M_PI); 166 } else if ((x == 0) && (y == 0)) { 167 return (-0.5 * M_PI); 168 } else if ((x == 0) && (y == 0)) { 169 return (M_PI + atan(y / x)); 170 } else if ((x == 0) && (y == 0)) { 171 return (-M_PI + atan(y / x)); 172 } 173 174 psAbort(__func__, "Unacceptable range for (arg(%f, %f).\n", x, y); 175 return (0.0); 194 176 } 195 177 196 178 // XXX: Waiting for the definition of the PS_PROJ_PAR projection. 197 179 // XXX: Waiting for the definition of the PS_PROJ_GLS projection. 198 psPlane *psProject( const psSphere *coord, 199 const psProjection *projection ) 180 psPlane *psProject(const psSphere * coord, const psProjection * projection) 200 181 { 201 182 float R = 0.0; 202 183 float alpha = 0.0; 203 psPlane *tmp = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 204 205 if ( projection->type == PS_PROJ_TAN ) { 206 R = cot( coord->r ) * ( 180.0 / M_PI ); 207 tmp->x = R * sin( coord->d ); 208 tmp->y = R * cos( coord->d ); 209 210 } else 211 if ( projection->type == PS_PROJ_SIN ) { 212 R = cos( coord->r ) * ( 180.0 / M_PI ); 213 tmp->x = R * sin( coord->d ); 214 tmp->y = R * cos( coord->d ); 215 216 } else 217 if ( projection->type == PS_PROJ_CAR ) { 218 tmp->x = coord->d; 219 tmp->y = coord->r; 220 221 } else 222 if ( projection->type == PS_PROJ_MER ) { 223 tmp->x = coord->d; 224 tmp->y = log( tan( 45.0 + ( 0.5 * coord->r ) ) ) * 180.0 / M_PI; 225 226 } else 227 if ( projection->type == PS_PROJ_AIT ) { 228 alpha = 1.0 / ( ( 180.0 / M_PI ) * 229 sqrt( 1.0 + ( cos( coord->r ) * cos( 0.5 * coord->d ) * 0.5 ) ) ); 230 231 tmp->x = 2.0 * alpha * cos( coord->r ) * sin( 0.5 * coord->d ); 232 tmp->y = alpha * sin( coord->d ); 233 234 } else 235 if ( projection->type == PS_PROJ_PAR ) { 236 psAbort( __func__, "The projection type PS_PROJ_PAR is undefined.\n" ); 237 238 } else 239 if ( projection->type == PS_PROJ_GLS ) { 240 psAbort( __func__, "The projection type PS_PROJ_GLS is undefined.\n" ); 241 } 242 243 return ( tmp ); 184 psPlane *tmp = (psPlane *) psAlloc(sizeof(psPlane)); 185 186 if (projection->type == PS_PROJ_TAN) { 187 R = cot(coord->r) * (180.0 / M_PI); 188 tmp->x = R * sin(coord->d); 189 tmp->y = R * cos(coord->d); 190 191 } else if (projection->type == PS_PROJ_SIN) { 192 R = cos(coord->r) * (180.0 / M_PI); 193 tmp->x = R * sin(coord->d); 194 tmp->y = R * cos(coord->d); 195 196 } else if (projection->type == PS_PROJ_CAR) { 197 tmp->x = coord->d; 198 tmp->y = coord->r; 199 200 } else if (projection->type == PS_PROJ_MER) { 201 tmp->x = coord->d; 202 tmp->y = log(tan(45.0 + (0.5 * coord->r))) * 180.0 / M_PI; 203 204 } else if (projection->type == PS_PROJ_AIT) { 205 alpha = 1.0 / ((180.0 / M_PI) * sqrt(1.0 + (cos(coord->r) * cos(0.5 * coord->d) * 0.5))); 206 207 tmp->x = 2.0 * alpha * cos(coord->r) * sin(0.5 * coord->d); 208 tmp->y = alpha * sin(coord->d); 209 210 } else if (projection->type == PS_PROJ_PAR) { 211 psAbort(__func__, "The projection type PS_PROJ_PAR is undefined.\n"); 212 213 } else if (projection->type == PS_PROJ_GLS) { 214 psAbort(__func__, "The projection type PS_PROJ_GLS is undefined.\n"); 215 } 216 217 return (tmp); 244 218 } 245 219 246 220 // XXX: Waiting for the definition of the PS_PROJ_PAR projection. 247 221 // XXX: Waiting for the definition of the PS_PROJ_GLS projection. 248 psSphere *psDeproject( const psPlane *coord, 249 const psProjection *projection ) 222 psSphere *psDeproject(const psPlane * coord, const psProjection * projection) 250 223 { 251 224 float R = 0.0; … … 253 226 float chu1 = 0.0; 254 227 float chu2 = 0.0; 255 psSphere *tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 256 257 if ( projection->type == PS_PROJ_TAN ) { 258 R = sqrt( ( coord->x * coord->x ) + ( coord->y * coord->y ) ); 259 tmp->d = arg( -coord->y, coord->x ); 260 tmp->r = atan( 180.0 / ( R * M_PI ) ); 261 262 } else 263 if ( projection->type == PS_PROJ_SIN ) { 264 R = sqrt( ( coord->x * coord->x ) + ( coord->y * coord->y ) ); 265 tmp->d = arg( -coord->y, coord->x ); 266 tmp->r = acos( ( R * M_PI ) / 180.0 ); 267 268 } else 269 if ( projection->type == PS_PROJ_CAR ) { 270 tmp->d = coord->x; 271 tmp->r = coord->y; 272 273 } else 274 if ( projection->type == PS_PROJ_MER ) { 275 tmp->d = coord->x; 276 tmp->r = ( 2.0 * atan( exp( ( coord->y * M_PI / 180.0 ) ) ) ) - 180.0; 277 278 } else 279 if ( projection->type == PS_PROJ_AIT ) { 280 chu1 = ( coord->x * M_PI ) / 720.0; 281 chu1 *= chu1; 282 chu2 = ( coord->y * M_PI ) / 360.0; 283 chu2 *= chu2; 284 chu = sqrt( 1.0 - chu1 - chu2 ); 285 tmp->d = 2.0 * arg( ( 2.0 * chu * chu ) - 1.0, 286 ( coord->x * chu * M_PI ) / 360.0 ); 287 tmp->r = asin( ( coord->y * chu * M_PI ) / 180.0 ); 288 289 } else 290 if ( projection->type == PS_PROJ_PAR ) { 291 psAbort( __func__, "The projection type PS_PROJ_PAR is undefined.\n" ); 292 293 } else 294 if ( projection->type == PS_PROJ_GLS ) { 295 psAbort( __func__, "The projection type PS_PROJ_GLG is undefined.\n" ); 296 } 297 298 return ( tmp ); 228 psSphere *tmp = (psSphere *) psAlloc(sizeof(psSphere)); 229 230 if (projection->type == PS_PROJ_TAN) { 231 R = sqrt((coord->x * coord->x) + (coord->y * coord->y)); 232 tmp->d = arg(-coord->y, coord->x); 233 tmp->r = atan(180.0 / (R * M_PI)); 234 235 } else if (projection->type == PS_PROJ_SIN) { 236 R = sqrt((coord->x * coord->x) + (coord->y * coord->y)); 237 tmp->d = arg(-coord->y, coord->x); 238 tmp->r = acos((R * M_PI) / 180.0); 239 240 } else if (projection->type == PS_PROJ_CAR) { 241 tmp->d = coord->x; 242 tmp->r = coord->y; 243 244 } else if (projection->type == PS_PROJ_MER) { 245 tmp->d = coord->x; 246 tmp->r = (2.0 * atan(exp((coord->y * M_PI / 180.0)))) - 180.0; 247 248 } else if (projection->type == PS_PROJ_AIT) { 249 chu1 = (coord->x * M_PI) / 720.0; 250 chu1 *= chu1; 251 chu2 = (coord->y * M_PI) / 360.0; 252 chu2 *= chu2; 253 chu = sqrt(1.0 - chu1 - chu2); 254 tmp->d = 2.0 * arg((2.0 * chu * chu) - 1.0, (coord->x * chu * M_PI) / 360.0); 255 tmp->r = asin((coord->y * chu * M_PI) / 180.0); 256 257 } else if (projection->type == PS_PROJ_PAR) { 258 psAbort(__func__, "The projection type PS_PROJ_PAR is undefined.\n"); 259 260 } else if (projection->type == PS_PROJ_GLS) { 261 psAbort(__func__, "The projection type PS_PROJ_GLG is undefined.\n"); 262 } 263 264 return (tmp); 299 265 } 300 266 301 267 // XXX: Do I need to check for unacceptable transformation parameters? 302 268 // Maybe, if the points are on the North/South Pole, etc? 303 psSphere *psSphereGetOffset( const psSphere *restrict position1, 304 const psSphere *restrict position2, 305 psSphereOffsetMode mode, 306 psSphereOffsetUnit unit ) 307 { 308 // psPlane *lin; 269 psSphere *psSphereGetOffset(const psSphere * restrict position1, 270 const psSphere * restrict position2, 271 psSphereOffsetMode mode, psSphereOffsetUnit unit) 272 { 273 // psPlane *lin; 309 274 psProjection proj; 310 275 psSphere *tmp; … … 312 277 double tmpD = 0.0; 313 278 314 if ( mode == PS_LINEAR) {279 if (mode == PS_LINEAR) { 315 280 // XXX: I have no idea how to construct this. Maybe project both 316 281 // sperical positions onto the plane, set the origin at one of the … … 318 283 319 284 // XXX: Do I need to somehow scale this projection? 320 // project position1? Will it project to (0.0, 0.0)?285 // project position1? Will it project to (0.0, 0.0)? 321 286 proj.R = position1->r; 322 287 proj.D = position1->d; … … 325 290 proj.type = PS_PROJ_TAN; 326 291 327 // lin = psProject(position2, proj);328 // tmp = psDeproject(lin, proj);292 // lin = psProject(position2, proj); 293 // tmp = psDeproject(lin, proj); 329 294 330 295 // XXX: Do we need to convert units in tmp? 331 return ( tmp ); 332 } else 333 if ( mode == PS_SPHERICAL ) { 334 tmpR = position2->r - position1->r; 335 tmpD = position2->d - position1->d; 336 337 if ( unit == PS_ARCSEC ) { 338 tmpR = ( tmpR * 180.0 * 60.0 * 60.0 ) / M_PI; 339 tmpD = ( tmpR * 180.0 * 60.0 * 60.0 ) / M_PI; 340 } else 341 if ( unit == PS_ARCMIN ) { 342 tmpR = ( tmpR * 180.0 * 60.0 ) / M_PI; 343 tmpD = ( tmpR * 180.0 * 60.0 ) / M_PI; 344 } else 345 if ( unit == PS_DEGREE ) { 346 tmpR = ( tmpR * 180.0 ) / M_PI; 347 tmpD = ( tmpR * 180.0 ) / M_PI; 348 } else 349 if ( unit == PS_RADIAN ) {} 350 else { 351 psAbort( __func__, "Unknown offset unit: 0x%x\n", unit ); 352 } 353 354 tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 355 tmp->r = tmpR; 356 tmp->d = tmpD; 357 tmp->rErr = 0.0; 358 tmp->dErr = 0.0; 359 // XXX: Do we need to wrap these to an acceptable range? 360 return ( tmp ); 296 return (tmp); 297 } else if (mode == PS_SPHERICAL) { 298 tmpR = position2->r - position1->r; 299 tmpD = position2->d - position1->d; 300 301 if (unit == PS_ARCSEC) { 302 tmpR = (tmpR * 180.0 * 60.0 * 60.0) / M_PI; 303 tmpD = (tmpR * 180.0 * 60.0 * 60.0) / M_PI; 304 } else if (unit == PS_ARCMIN) { 305 tmpR = (tmpR * 180.0 * 60.0) / M_PI; 306 tmpD = (tmpR * 180.0 * 60.0) / M_PI; 307 } else if (unit == PS_DEGREE) { 308 tmpR = (tmpR * 180.0) / M_PI; 309 tmpD = (tmpR * 180.0) / M_PI; 310 } else if (unit == PS_RADIAN) {} 311 else { 312 psAbort(__func__, "Unknown offset unit: 0x%x\n", unit); 361 313 } 362 psAbort( __func__, "Unrecognized offset mode\n" ); 363 return ( NULL ); 364 } 365 314 315 tmp = (psSphere *) psAlloc(sizeof(psSphere)); 316 tmp->r = tmpR; 317 tmp->d = tmpD; 318 tmp->rErr = 0.0; 319 tmp->dErr = 0.0; 320 // XXX: Do we need to wrap these to an acceptable range? 321 return (tmp); 322 } 323 psAbort(__func__, "Unrecognized offset mode\n"); 324 return (NULL); 325 } 366 326 367 327 // XXX: Do I need to check for unacceptable transformation parameters? 368 328 // Maybe, if the points are on the North/South Pole, etc? 369 329 // XXX: I copied the algorithm from the ADD exactly. 370 psSphere *psSphereSetOffset( const psSphere *restrict position, 371 const psSphere *restrict offset, 372 psSphereOffsetMode mode, 373 psSphereOffsetUnit unit ) 330 psSphere *psSphereSetOffset(const psSphere * restrict position, 331 const psSphere * restrict offset, 332 psSphereOffsetMode mode, psSphereOffsetUnit unit) 374 333 { 375 334 psPlane lin; … … 379 338 double tmpD = 0.0; 380 339 381 if ( mode == PS_LINEAR) {340 if (mode == PS_LINEAR) { 382 341 proj.R = position->r; 383 342 proj.D = position->d; … … 389 348 lin.y = offset->d; 390 349 391 tmp = psDeproject( &lin, &proj ); 392 return ( tmp ); 393 394 } else 395 if ( mode == PS_SPHERICAL ) { 396 if ( unit == PS_ARCSEC ) { 397 tmpR = ( M_PI * offset->r ) / ( 180.0 * 60.0 * 60.0 ); 398 tmpD = ( M_PI * offset->d ) / ( 180.0 * 60.0 * 60.0 ); 399 } else 400 if ( unit == PS_ARCMIN ) { 401 tmpR = ( M_PI * offset->r ) / ( 180.0 * 60.0 ); 402 tmpD = ( M_PI * offset->d ) / ( 180.0 * 60.0 ); 403 } else 404 if ( unit == PS_DEGREE ) { 405 tmpR = ( M_PI * offset->r ) / ( 180.0 ); 406 tmpD = ( M_PI * offset->d ) / ( 180.0 ); 407 } else 408 if ( unit == PS_RADIAN ) { 409 tmpR = offset->r; 410 tmpD = offset->d; 411 } else { 412 psAbort( __func__, "Unknown offset unit: 0x%x\n", unit ); 413 } 414 415 tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 416 tmp->r = position->r + tmpR; 417 tmp->r = position->d + tmpD; 418 tmp->rErr = 0.0; 419 tmp->dErr = 0.0; 420 421 // XXX: wrap tmp->r and tmp->d to the allowed range (-PI to PI) 422 // and (0 to 2*PI). 423 return ( tmp ); 350 tmp = psDeproject(&lin, &proj); 351 return (tmp); 352 353 } else if (mode == PS_SPHERICAL) { 354 if (unit == PS_ARCSEC) { 355 tmpR = (M_PI * offset->r) / (180.0 * 60.0 * 60.0); 356 tmpD = (M_PI * offset->d) / (180.0 * 60.0 * 60.0); 357 } else if (unit == PS_ARCMIN) { 358 tmpR = (M_PI * offset->r) / (180.0 * 60.0); 359 tmpD = (M_PI * offset->d) / (180.0 * 60.0); 360 } else if (unit == PS_DEGREE) { 361 tmpR = (M_PI * offset->r) / (180.0); 362 tmpD = (M_PI * offset->d) / (180.0); 363 } else if (unit == PS_RADIAN) { 364 tmpR = offset->r; 365 tmpD = offset->d; 366 } else { 367 psAbort(__func__, "Unknown offset unit: 0x%x\n", unit); 424 368 } 425 psAbort( __func__, "Unrecognized offset mode\n" ); 426 return ( NULL ); 427 } 369 370 tmp = (psSphere *) psAlloc(sizeof(psSphere)); 371 tmp->r = position->r + tmpR; 372 tmp->r = position->d + tmpD; 373 tmp->rErr = 0.0; 374 tmp->dErr = 0.0; 375 376 // XXX: wrap tmp->r and tmp->d to the allowed range (-PI to PI) 377 // and (0 to 2*PI). 378 return (tmp); 379 } 380 psAbort(__func__, "Unrecognized offset mode\n"); 381 return (NULL); 382 } -
trunk/psLib/src/astro/psCoord.h
r1393 r1407 1 1 2 /** @file psCoord.h 2 3 * … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 5 19:38:51$13 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 18 # ifndef PS_COORD_H19 # define PS_COORD_H20 21 # include "psType.h"22 # include "psImage.h"23 # include "psArray.h"24 # include "psList.h"25 # include "psFunctions.h"26 # include "psTime.h"19 #ifndef PS_COORD_H 20 # define PS_COORD_H 21 22 # include "psType.h" 23 # include "psImage.h" 24 # include "psArray.h" 25 # include "psList.h" 26 # include "psFunctions.h" 27 # include "psTime.h" 27 28 28 29 /// @addtogroup CoordinateTransform … … 38 39 typedef struct 39 40 { 40 double x; ///< x position41 double y; ///< y position42 double xErr; ///< Error in x position43 double yErr; ///< Error in y position41 double x; // /< x position 42 double y; // /< y position 43 double xErr; // /< Error in x position 44 double yErr; // /< Error in y position 44 45 } 45 46 psPlane; … … 54 55 typedef struct 55 56 { 56 double r; ///< RA57 double d; ///< Dec58 double rErr; ///< Error in RA59 double dErr; ///< Error in Dec57 double r; // /< RA 58 double d; // /< Dec 59 double rErr; // /< Error in RA 60 double dErr; // /< Error in Dec 60 61 } 61 62 psSphere; … … 71 72 typedef struct 72 73 { 73 psDPolynomial2D *x; ///< 2D polynomial transform of X coordinates74 psDPolynomial2D *y; ///< 2D polynomial transform of Y coordinates74 psDPolynomial2D *x; // /< 2D polynomial transform of X coordinates 75 psDPolynomial2D *y; // /< 2D polynomial transform of Y coordinates 75 76 } 76 77 psPlaneTransform; … … 90 91 typedef struct 91 92 { 92 psDPolynomial4D *x; ///< 4D polynomial transform of X coordinates93 psDPolynomial4D *y; ///< 4D polynomial transform of Y coordinates93 psDPolynomial4D *x; // /< 4D polynomial transform of X coordinates 94 psDPolynomial4D *y; // /< 4D polynomial transform of Y coordinates 94 95 } 95 96 psPlaneDistort; … … 107 108 typedef struct 108 109 { 109 double sinPhi; ///< sin of North Pole lattitude110 double cosPhi; ///< cos of North Pole lattitude111 double Xo; ///< First PT of Ares lon112 double xo; ///< First PT of Ares equiv lon110 double sinPhi; // /< sin of North Pole lattitude 111 double cosPhi; // /< cos of North Pole lattitude 112 double Xo; // /< First PT of Ares lon 113 double xo; // /< First PT of Ares equiv lon 113 114 } 114 115 psSphereTransform; … … 120 121 */ 121 122 typedef enum { 122 PS_PROJ_TAN, ///< Tangent projection123 PS_PROJ_SIN, ///< Sine projection124 PS_PROJ_AIT, ///< Aitoff projection125 PS_PROJ_PAR, ///< Par projection126 PS_PROJ_GLS, ///< GLS projection127 PS_PROJ_CAR, ///< CAR projection128 PS_PROJ_MER, ///< MER projection129 PS_PROJ_NTYPE ///< Number of types; must be last.123 PS_PROJ_TAN, // /< Tangent projection 124 PS_PROJ_SIN, // /< Sine projection 125 PS_PROJ_AIT, // /< Aitoff projection 126 PS_PROJ_PAR, // /< Par projection 127 PS_PROJ_GLS, // /< GLS projection 128 PS_PROJ_CAR, // /< CAR projection 129 PS_PROJ_MER, // /< MER projection 130 PS_PROJ_NTYPE // /< Number of types; must be last. 130 131 } psProjectionType; 131 132 … … 137 138 typedef struct 138 139 { 139 double R; ///< Coordinates of projection center140 double D; ///< Coordinates of projection center141 double Xs; ///< plate-scale in X direction142 double Ys; ///< plate-scale in Y direction143 psProjectionType type; ///< Projection type140 double R; // /< Coordinates of projection center 141 double D; // /< Coordinates of projection center 142 double Xs; // /< plate-scale in X direction 143 double Ys; // /< plate-scale in Y direction 144 psProjectionType type; // /< Projection type 144 145 } 145 146 psProjection; … … 151 152 */ 152 153 typedef enum { 153 PS_SPHERICAL, ///< offset corresponds to an angular offset154 PS_LINEAR ///< offset corresponds to a linear offset154 PS_SPHERICAL, // /< offset corresponds to an angular offset 155 PS_LINEAR // /< offset corresponds to a linear offset 155 156 } psSphereOffsetMode; 156 157 … … 161 162 */ 162 163 typedef enum { 163 PS_ARCSEC, ///< Arcseconds164 PS_ARCMIN, ///< Arcminutes165 PS_DEGREE, ///< Degrees166 PS_RADIAN ///< Radians164 PS_ARCSEC, // /< Arcseconds 165 PS_ARCMIN, // /< Arcminutes 166 PS_DEGREE, // /< Degrees 167 PS_RADIAN // /< Radians 167 168 } psSphereOffsetUnit; 168 169 … … 170 171 * 171 172 */ 172 psPlane *psPlaneTransformApply( 173 psPlane *out, ///< a psPlane to recycle. If NULL, a new one is generated. 174 const psPlaneTransform *transform, ///< the transform to apply 175 const psPlane *coords ///< the coordinate to apply the transform above. 176 ); 173 psPlane *psPlaneTransformApply(psPlane * out, // /< a psPlane to recycle. If NULL, a new one is generated. 174 const psPlaneTransform * transform, // /< the transform to apply 175 const psPlane * coords // /< the coordinate to apply the transform above. 176 ); 177 177 178 178 /** Applies the psPlaneDistort transform to a specified coordinate 179 179 * 180 180 */ 181 psPlane *psPlaneDistortApply( 182 psPlane *out, ///< a psPlane to recycle. If NULL, a new one is generated. 183 const psPlaneDistort *transform, ///< the transform to apply 184 const psPlane *coords, ///< the coordinate to apply the transform above. 185 float term3, ///< third term -- maybe magnitude 186 float term4 ///< forth term -- maybe color 187 ); 181 psPlane *psPlaneDistortApply(psPlane * out, // /< a psPlane to recycle. If NULL, a new one is generated. 182 const psPlaneDistort * transform, // /< the transform to apply 183 const psPlane * coords, // /< the coordinate to apply the transform above. 184 float term3, // /< third term -- maybe magnitude 185 float term4 // /< forth term -- maybe color 186 ); 188 187 189 188 /** Allocator for psSphereTransform 190 189 * 191 190 */ 192 psSphereTransform *psSphereTransformAlloc( 193 double NPlat, ///< north pole latitude 194 double Xo, ///< First PT of Ares lon 195 double xo ///< First PT of Ares equiv lon 196 ); 197 191 psSphereTransform *psSphereTransformAlloc(double NPlat, // /< north pole latitude 192 double Xo, // /< First PT of Ares lon 193 double xo // /< First PT of Ares equiv lon 194 ); 198 195 199 196 /** Applies the psSphereTransform transform for a specified coordinate 200 197 * 201 198 */ 202 psSphere *psSphereTransformApply( 203 psSphere *out, ///< a psSphere to recycle. If NULL, a new one is generated. 204 const psSphereTransform *transform,///< the transform to apply 205 const psSphere *coord ///< the coordinate to apply the transform above.x 206 ); 207 208 psSphereTransform *psSphereTransformICRStoEcliptic( 209 psTime time 210 ); 211 212 psSphereTransform *psSphereTransformEcliptictoICRS( 213 psTime time 214 ); 215 216 psSphereTransform *psSphereTransformICRStoGalatic( void ); 217 218 psSphereTransform *psSphereTransformGalatictoICRS( void ); 219 220 psPlane *psProject( 221 const psSphere *coord, 222 const psProjection *projection 223 ); 224 225 psSphere *psDeproject( 226 const psPlane *coord, 227 const psProjection *projection 228 ); 229 230 psSphere *psSphereGetOffset( 231 const psSphere *restrict position1, 232 const psSphere *restrict position2, 233 psSphereOffsetMode mode, 234 psSphereOffsetUnit unit 235 ); 236 237 psSphere *psSphereSetOffset( 238 const psSphere *restrict position, 239 const psSphere *restrict offset, 240 psSphereOffsetMode mode, 241 psSphereOffsetUnit unit 242 ); 199 psSphere *psSphereTransformApply(psSphere * out, // /< a psSphere to recycle. If NULL, a new one is 200 // generated. 201 const psSphereTransform * transform, // /< the transform to apply 202 const psSphere * coord // /< the coordinate to apply the transform above.x 203 ); 204 205 psSphereTransform *psSphereTransformICRStoEcliptic(psTime time); 206 207 psSphereTransform *psSphereTransformEcliptictoICRS(psTime time); 208 209 psSphereTransform *psSphereTransformICRStoGalatic(void); 210 211 psSphereTransform *psSphereTransformGalatictoICRS(void); 212 213 psPlane *psProject(const psSphere * coord, const psProjection * projection); 214 215 psSphere *psDeproject(const psPlane * coord, const psProjection * projection); 216 217 psSphere *psSphereGetOffset(const psSphere * restrict position1, 218 const psSphere * restrict position2, 219 psSphereOffsetMode mode, psSphereOffsetUnit unit); 220 221 psSphere *psSphereSetOffset(const psSphere * restrict position, 222 const psSphere * restrict offset, 223 psSphereOffsetMode mode, psSphereOffsetUnit unit); 243 224 244 225 /// @} -
trunk/psLib/src/astro/psTime.c
r1406 r1407 1 1 2 /** @file psTime.c 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1.1 3$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.14 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 18 19 */ 19 20 20 21 21 /******************************************************************************/ 22 22 23 /* INCLUDE FILES */ 24 23 25 /******************************************************************************/ 24 26 … … 32 34 33 35 /******************************************************************************/ 36 34 37 /* DEFINE STATEMENTS */ 38 35 39 /******************************************************************************/ 36 40 … … 73 77 } \ 74 78 79 75 80 /******************************************************************************/ 81 76 82 /* TYPE DEFINITIONS */ 83 77 84 /******************************************************************************/ 78 85 … … 80 87 81 88 /*****************************************************************************/ 89 82 90 /* GLOBAL VARIABLES */ 91 83 92 /*****************************************************************************/ 84 93 … … 86 95 87 96 /*****************************************************************************/ 97 88 98 /* FILE STATIC VARIABLES */ 99 89 100 /*****************************************************************************/ 90 101 … … 119 130 120 131 // Table for Julian date of leapsecond update and current total number of leapseconds at that date 121 static double leapseconds[NUM_LEAPSECOND_UPDATES][2] = 122 { 123 { 124 2441317.5, 10.0 125 }, 126 { 127 2441499.5, 11.0 128 }, 129 { 130 2441683.5, 12.0 131 }, 132 { 133 2442048.5, 13.0 134 }, 135 { 136 2442413.5, 14.0 137 }, 138 { 139 2442778.5, 15.0 140 }, 141 { 142 2443144.5, 16.0 143 }, 144 { 145 2443509.5, 17.0 146 }, 147 { 148 2443874.5, 18.0 149 }, 150 { 151 2444239.5, 19.0 152 }, 153 { 154 2444786.5, 20.0 155 }, 156 { 157 2445151.5, 21.0 158 }, 159 { 160 2445516.5, 22.0 161 }, 162 { 163 2446247.5, 23.0 164 }, 165 { 166 2447161.5, 24.0 167 }, 168 { 169 2447892.5, 25.0 170 }, 171 { 172 2448257.5, 26.0 173 }, 174 { 175 2448804.5, 27.0 176 }, 177 { 178 2449169.5, 28.0 179 }, 180 { 181 2449534.5, 29.0 182 }, 183 { 184 2450083.5, 30.0 185 }, 186 { 187 2450630.5, 31.0 188 }, 189 { 190 2451179.5, 32.0 191 } 192 }; 193 194 /*****************************************************************************/ 132 static double leapseconds[NUM_LEAPSECOND_UPDATES][2] = { 133 { 134 2441317.5, 10.0}, 135 { 136 2441499.5, 11.0}, 137 { 138 2441683.5, 12.0}, 139 { 140 2442048.5, 13.0}, 141 { 142 2442413.5, 14.0}, 143 { 144 2442778.5, 15.0}, 145 { 146 2443144.5, 16.0}, 147 { 148 2443509.5, 17.0}, 149 { 150 2443874.5, 18.0}, 151 { 152 2444239.5, 19.0}, 153 { 154 2444786.5, 20.0}, 155 { 156 2445151.5, 21.0}, 157 { 158 2445516.5, 22.0}, 159 { 160 2446247.5, 23.0}, 161 { 162 2447161.5, 24.0}, 163 { 164 2447892.5, 25.0}, 165 { 166 2448257.5, 26.0}, 167 { 168 2448804.5, 27.0}, 169 { 170 2449169.5, 28.0}, 171 { 172 2449534.5, 29.0}, 173 { 174 2450083.5, 30.0}, 175 { 176 2450630.5, 31.0}, 177 { 178 2451179.5, 32.0} 179 }; 180 181 /*****************************************************************************/ 182 195 183 /* FUNCTION IMPLEMENTATION - LOCAL */ 184 196 185 /*****************************************************************************/ 197 186 … … 199 188 200 189 /*****************************************************************************/ 190 201 191 /* FUNCTION IMPLEMENTATION - PUBLIC */ 192 202 193 /*****************************************************************************/ 203 194 … … 210 201 time.tv_usec = 0; 211 202 212 if (gettimeofday(&now,(struct timezone *)0) == -1) {203 if (gettimeofday(&now, (struct timezone *)0) == -1) { 213 204 psError(__func__, " : Line %d - Failed to get time", __LINE__); 214 205 return time; 215 206 } 216 217 207 // Convert timeval time to psTime 218 208 time.tv_sec = now.tv_sec; … … 220 210 221 211 // Add most current leapseconds value to UTC time to get TAI time 222 time.tv_sec += leapseconds[NUM_LEAPSECOND_UPDATES -1][1];212 time.tv_sec += leapseconds[NUM_LEAPSECOND_UPDATES - 1][1]; 223 213 224 214 return time; 225 215 } 226 216 227 char *psTimeToISO(psTime time)217 char *psTimeToISO(psTime time) 228 218 { 229 219 int ms = 0; … … 232 222 struct tm *tmTime = NULL; 233 223 234 CHECK_NEGATIVE_TIME_STRUCT(time, NULL);224 CHECK_NEGATIVE_TIME_STRUCT(time, NULL); 235 225 236 226 tempString = psAlloc(MAX_TIME_STRING_LENGTH); … … 238 228 239 229 // Converts psTime to YYYY/MM/DD,HH:MM:SS.SSS in string form 240 ms = time.tv_usec /1000;230 ms = time.tv_usec / 1000; 241 231 242 232 // tmTime variable is statically allocated, no need to free 243 233 tmTime = gmtime(&time.tv_sec); 244 if (!strftime(tempString, MAX_TIME_STRING_LENGTH, "%Y/%m/%d,%H:%M:%S", tmTime)) {234 if (!strftime(tempString, MAX_TIME_STRING_LENGTH, "%Y/%m/%d,%H:%M:%S", tmTime)) { 245 235 psError(__func__, " : Line %d - Failed strftime conversion", __LINE__); 246 236 } 247 237 248 if (snprintf(timeString,MAX_TIME_STRING_LENGTH,"%s.%3.3d", tempString, ms) < 0) {238 if (snprintf(timeString, MAX_TIME_STRING_LENGTH, "%s.%3.3d", tempString, ms) < 0) { 249 239 psError(__func__, " : Line %d - Failed snprintf conversion", __LINE__); 250 240 } … … 262 252 psTime outTime; 263 253 264 CHECK_NEGATIVE_TIME_STRUCT(time, outTime);254 CHECK_NEGATIVE_TIME_STRUCT(time, outTime); 265 255 266 256 // Find leapseconds to subtract from psTime to get UTC time 267 257 jd = psTimeToJD(time); 268 258 jdTable = leapseconds[0]; 269 for (i=0; i<NUM_LEAPSECOND_UPDATES; i++, jdTable+=2) {270 if (jd > *jdTable) {259 for (i = 0; i < NUM_LEAPSECOND_UPDATES; i++, jdTable += 2) { 260 if (jd > *jdTable) { 271 261 ls = *(jdTable + 1); 272 262 } … … 276 266 outTime.tv_usec = time.tv_usec; 277 267 278 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);268 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 279 269 280 270 return outTime; … … 285 275 double mjd = 0.0; 286 276 287 CHECK_NEGATIVE_TIME_STRUCT(time, mjd);277 CHECK_NEGATIVE_TIME_STRUCT(time, mjd); 288 278 289 279 // Modified Julian date conversion courtesy of Eugene Magnier 290 mjd = time.tv_sec /SEC_PER_DAY + time.tv_usec/USEC_PER_DAY + 40587.0;280 mjd = time.tv_sec / SEC_PER_DAY + time.tv_usec / USEC_PER_DAY + 40587.0; 291 281 292 282 return mjd; … … 297 287 double jd = 0.0; 298 288 299 CHECK_NEGATIVE_TIME_STRUCT(time, jd);289 CHECK_NEGATIVE_TIME_STRUCT(time, jd); 300 290 301 291 // Julian date conversion courtesy of Eugene Magnier 302 jd = time.tv_sec /SEC_PER_DAY + time.tv_usec/USEC_PER_DAY + 2440587.5;292 jd = time.tv_sec / SEC_PER_DAY + time.tv_usec / USEC_PER_DAY + 2440587.5; 303 293 304 294 return jd; … … 309 299 struct timeval timevalTime; 310 300 311 CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime);301 CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime); 312 302 timevalTime.tv_sec = time.tv_sec; 313 303 timevalTime.tv_usec = time.tv_usec; … … 316 306 } 317 307 318 struct tm *psTimeToTM(psTime time)308 struct tm *psTimeToTM(psTime time) 319 309 { 320 310 struct tm *tmTime = NULL; 321 311 322 CHECK_NEGATIVE_TIME_STRUCT(time, tmTime);312 CHECK_NEGATIVE_TIME_STRUCT(time, tmTime); 323 313 tmTime = gmtime(&time.tv_sec); 324 314 … … 343 333 // Convert YYYY/MM/DD,HH:MM:SS.SSS in string form to tm time 344 334 year = atoi(strtok(tempString, "/")); 345 if (year < 1900) {346 psError(__func__, "Years less than 1900 not allowed. Value: %d", year);335 if (year < 1900) { 336 psError(__func__, "Years less than 1900 not allowed. Value: %d", year); 347 337 return outTime; 348 338 } 349 339 350 340 month = atoi(strtok(NULL, "/")); 351 if (month<1 || month>12) {352 psError(__func__, "Month must have a value from 1 to 12. Value: %d", month);341 if (month < 1 || month > 12) { 342 psError(__func__, "Month must have a value from 1 to 12. Value: %d", month); 353 343 return outTime; 354 344 } 355 345 356 346 day = atoi(strtok(NULL, ",")); 357 if (day<1 || day>31) {358 psError(__func__, "Day must have a value from 1 to 31. Value: %d", day);347 if (day < 1 || day > 31) { 348 psError(__func__, "Day must have a value from 1 to 31. Value: %d", day); 359 349 return outTime; 360 350 } 361 351 362 352 hour = atoi(strtok(NULL, ":")); 363 if (hour<0 || hour>23) {364 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", hour);353 if (hour < 0 || hour > 23) { 354 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", hour); 365 355 return outTime; 366 356 } 367 357 368 358 minute = atoi(strtok(NULL, ":")); 369 if (minute<0 || minute>59) {370 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", minute);359 if (minute < 0 || minute > 59) { 360 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", minute); 371 361 return outTime; 372 362 } 373 363 374 364 second = atoi(strtok(NULL, ".")); 375 if (second<0 || second>59) {376 psError(__func__, "Second must have a value from 0 to 59. Value: %d", second);365 if (second < 0 || second > 59) { 366 psError(__func__, "Second must have a value from 0 to 59. Value: %d", second); 377 367 return outTime; 378 368 } 379 369 380 370 millisecond = atoi(strtok(NULL, "X")); 381 if (millisecond<0 || millisecond>1000) {382 psError(__func__, "Millisecond must have a value from 0 to 999. Value: %d", millisecond);371 if (millisecond < 0 || millisecond > 1000) { 372 psError(__func__, "Millisecond must have a value from 0 to 999. Value: %d", millisecond); 383 373 return outTime; 384 374 } … … 394 384 // Convert tm time to psTime 395 385 outTime = psTMToTime(&tmTime); 396 outTime.tv_usec = millisecond *1000;386 outTime.tv_usec = millisecond * 1000; 397 387 398 388 return outTime; … … 403 393 psTime outTime; 404 394 405 CHECK_NEGATIVE_TIME_STRUCT(time, outTime);395 CHECK_NEGATIVE_TIME_STRUCT(time, outTime); 406 396 407 397 // Convert UTC time to psTime/TAI 408 outTime.tv_sec = time.tv_sec + leapseconds[NUM_LEAPSECOND_UPDATES -1][1];398 outTime.tv_sec = time.tv_sec + leapseconds[NUM_LEAPSECOND_UPDATES - 1][1]; 409 399 outTime.tv_usec = time.tv_usec; 410 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);400 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 411 401 412 402 return outTime; … … 419 409 double seconds = 0.0; 420 410 421 CHECK_NEGATIVE_TIME(time, outTime);411 CHECK_NEGATIVE_TIME(time, outTime); 422 412 423 413 // Modified Julian date conversion courtesy of Eugene Magnier … … 425 415 426 416 // Convert to psTime/TAI 427 seconds = days *SEC_PER_DAY;428 outTime.tv_usec = (seconds - (long)seconds)*1000000.0;417 seconds = days * SEC_PER_DAY; 418 outTime.tv_usec = (seconds - (long)seconds) * 1000000.0; 429 419 outTime.tv_sec = seconds; 430 420 431 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);421 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 432 422 433 423 return outTime; … … 440 430 psTime outTime; 441 431 442 CHECK_NEGATIVE_TIME(time, outTime);432 CHECK_NEGATIVE_TIME(time, outTime); 443 433 444 434 // Julian date conversion courtesy of Eugene Magnier … … 446 436 447 437 // Convert to psTime/TAI 448 seconds = days *SEC_PER_DAY;438 seconds = days * SEC_PER_DAY; 449 439 outTime.tv_sec = seconds; 450 outTime.tv_usec = (seconds -(long)seconds)*1000000.0; 451 452 CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime); 453 454 return outTime; 455 } 456 457 psTime psTimevalToTime(struct timeval *time) 458 { 459 psTime outTime; 460 if(time == NULL) 461 { 462 psError(__func__,"Null value for timeval arg not allowed"); 463 return outTime; 464 } else 465 if(time->tv_sec < 0) 466 { 467 psError(__func__,"Negative seconds are not allowed: %ld", time->tv_sec); 468 return outTime; 469 } else 470 if(time->tv_usec<0) 471 { 472 psError(__func__,"Negative microseconds are not allowed: %ld", time->tv_usec); 473 return outTime; 474 } 475 440 outTime.tv_usec = (seconds - (long)seconds) * 1000000.0; 441 442 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 443 444 return outTime; 445 } 446 447 psTime psTimevalToTime(struct timeval * time) 448 { 449 psTime outTime; 450 451 if (time == NULL) 452 { 453 psError(__func__, "Null value for timeval arg not allowed"); 454 return outTime; 455 } else if (time->tv_sec < 0) 456 { 457 psError(__func__, "Negative seconds are not allowed: %ld", time->tv_sec); 458 return outTime; 459 } else if (time->tv_usec < 0) 460 { 461 psError(__func__, "Negative microseconds are not allowed: %ld", time->tv_usec); 462 return outTime; 463 } 476 464 // Convert to psTime/TAI 477 465 outTime.tv_sec = time->tv_sec; 478 466 outTime.tv_usec = time->tv_usec; 479 467 480 CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime); 481 482 return outTime; 483 } 484 485 486 psTime psTMToTime(struct tm *time) 468 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 469 470 return outTime; 471 } 472 473 psTime psTMToTime(struct tm * time) 487 474 { 488 475 int i; 489 476 int n; 490 477 int y; 491 int mon [] = 492 { 493 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 494 }; 478 int mon[] = { 479 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 480 }; 495 481 long epoch; 496 482 psTime outTime; 497 483 498 i = 0;484 i = 0; 499 485 n = 0; 500 486 y = 0; 501 487 epoch = 0; 502 488 503 if(time == NULL) 504 { 505 psError(__func__,"Null value for tm arg not allowed"); 506 return outTime; 507 } else 508 if(time->tm_year < 70) 509 { 510 psError(__func__,"Input times earlier than 1970 not allowed. Value: %d", time->tm_year+1900); 511 return outTime; 512 } else 513 if(time->tm_mon<0 || time->tm_mon>11) 514 { 515 psError(__func__,"Month must have a value from 0 to 11. Value: %d", time->tm_mon); 516 return outTime; 517 } else 518 if(time->tm_mday<1 || time->tm_mday>31) 519 { 520 psError(__func__,"Day must have a value from 1 to 31. Value: %d", time->tm_mday); 521 return outTime; 522 } else 523 if(time->tm_hour<0 || time->tm_hour>23) 524 { 525 psError(__func__,"Hour must have a value from 0 to 23. Value: %d", time->tm_hour); 526 return outTime; 527 } else 528 if(time->tm_min<0 || time->tm_min>59) 529 { 530 psError(__func__,"Minute must have a value from 0 to 59. Value: %d", time->tm_min); 531 return outTime; 532 } else 533 if(time->tm_sec<0 || time->tm_sec>59) 534 { 535 psError(__func__,"Second must have a value from 0 to 59. Value: %d", time->tm_sec); 536 return outTime; 537 } 489 if (time == NULL) 490 { 491 psError(__func__, "Null value for tm arg not allowed"); 492 return outTime; 493 } else if (time->tm_year < 70) 494 { 495 psError(__func__, "Input times earlier than 1970 not allowed. Value: %d", time->tm_year + 1900); 496 return outTime; 497 } else if (time->tm_mon < 0 || time->tm_mon > 11) 498 { 499 psError(__func__, "Month must have a value from 0 to 11. Value: %d", time->tm_mon); 500 return outTime; 501 } else if (time->tm_mday < 1 || time->tm_mday > 31) 502 { 503 psError(__func__, "Day must have a value from 1 to 31. Value: %d", time->tm_mday); 504 return outTime; 505 } else if (time->tm_hour < 0 || time->tm_hour > 23) 506 { 507 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", time->tm_hour); 508 return outTime; 509 } else if (time->tm_min < 0 || time->tm_min > 59) 510 { 511 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", time->tm_min); 512 return outTime; 513 } else if (time->tm_sec < 0 || time->tm_sec > 59) 514 { 515 psError(__func__, "Second must have a value from 0 to 59. Value: %d", time->tm_sec); 516 return outTime; 517 } 538 518 539 519 n = time->tm_year + 1900 - 1; 540 epoch = (time->tm_year - 70) * SEC_PER_YEAR + ((n /4 - n/100 + n/400) -541 (1969 /4 - 1969/100 + 1969/400)) * SEC_PER_DAY;520 epoch = (time->tm_year - 70) * SEC_PER_YEAR + ((n / 4 - n / 100 + n / 400) - 521 (1969 / 4 - 1969 / 100 + 1969 / 400)) * SEC_PER_DAY; 542 522 543 523 y = time->tm_year + 1900; 544 524 545 525 // Adjust for leap years 546 for (i = 0; i<time->tm_mon; i++)547 { 548 epoch += mon [i] * SEC_PER_DAY;549 if (i == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) {526 for (i = 0; i < time->tm_mon; i++) 527 { 528 epoch += mon[i] * SEC_PER_DAY; 529 if (i == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) { 550 530 epoch += SEC_PER_DAY; 551 531 } … … 554 534 // Add everything 555 535 epoch += (time->tm_mday - 1) * SEC_PER_DAY; 556 epoch += time->tm_hour * SEC_PER_HOUR + time->tm_min * SEC_PER_MINUTE + time->tm_sec;536 epoch += time->tm_hour * SEC_PER_HOUR + time->tm_min * SEC_PER_MINUTE + time->tm_sec; 557 537 558 538 // Create psTime … … 560 540 outTime.tv_sec = epoch; 561 541 562 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);563 564 return outTime; 565 } 542 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 543 544 return outTime; 545 } -
trunk/psLib/src/astro/psTime.h
r1406 r1407 1 1 2 /** @file psTime.h 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PSTIME_H 21 # define PSTIME_H22 23 # include <time.h>24 # include <sys/types.h>25 # include <sys/time.h>26 27 # include "psType.h"22 # define PSTIME_H 23 24 # include <time.h> 25 # include <sys/types.h> 26 # include <sys/time.h> 27 28 # include "psType.h" 28 29 29 30 /// @addtogroup Time … … 31 32 32 33 /******************************************************************************/ 34 33 35 /* TYPE DEFINITIONS */ 36 34 37 /******************************************************************************/ 35 38 … … 42 45 typedef struct 43 46 { 44 time_t tv_sec; /**< Seconds since epoch, Jan 1, 1970. */ 45 suseconds_t tv_usec; /**< Microseconds since last second. */ 47 48 time_t tv_sec; /**< Seconds since epoch, Jan 1, 1970. */ 49 50 suseconds_t tv_usec; /**< Microseconds since last second. */ 46 51 } 47 52 psTime; 48 53 49 54 /*****************************************************************************/ 55 50 56 /* FUNCTION PROTOTYPES */ 57 51 58 /*****************************************************************************/ 52 59 … … 57 64 * @return psTime: Struct with current time. 58 65 */ 59 psTime psTimeGetTime( 60 void /** No argument. */ 61 ); 66 67 psTime psTimeGetTime(void 68 /** No argument. */ 69 ); 62 70 63 71 /** Convert psTime to ISO time in TAI units. … … 68 76 * @return char*: Pointer null terminated array of chars in ISO time. 69 77 */ 70 char* psTimeToISO( 71 psTime time /** Input time to be converted. */ 72 ); 78 79 char *psTimeToISO(psTime time 80 /** Input time to be converted. */ 81 ); 73 82 74 83 /** Convert psTime to UTC time. … … 80 89 * @return psTime: UTC time psTime format. 81 90 */ 82 psTime psTimeToUTC( 83 psTime time /** Input time to be converted. */ 84 ); 91 92 psTime psTimeToUTC(psTime time 93 /** Input time to be converted. */ 94 ); 85 95 86 96 /** Convert psTime to modified Julian date time. … … 91 101 * @return double: Modified Julian Days (MJD) time. 92 102 */ 93 double psTimeToMJD( 94 psTime time /** Input time to be converted. */ 95 ); 103 104 double psTimeToMJD(psTime time 105 /** Input time to be converted. */ 106 ); 96 107 97 108 /** Convert psTime to Julian date time. … … 102 113 * @return double: Julian Date (JD) time. 103 114 */ 104 double psTimeToJD( 105 psTime time /** Input time to be converted. */ 106 ); 115 116 double psTimeToJD(psTime time 117 /** Input time to be converted. */ 118 ); 107 119 108 120 /** Convert psTime to timeval time. … … 113 125 * @return timeval: timeval struct time. 114 126 */ 115 struct timeval psTimeToTimeval( 116 psTime time /** Input time to be converted. */ 117 ); 127 128 struct timeval psTimeToTimeval(psTime time 129 /** Input time to be converted. */ 130 ); 118 131 119 132 /** Convert psTime to tm time. … … 124 137 * @return tm: tm struct time. 125 138 */ 126 struct tm* psTimeToTM( 127 psTime time /** Input time to be converted. */ 128 ); 139 140 struct tm *psTimeToTM(psTime time 141 /** Input time to be converted. */ 142 ); 129 143 130 144 /** Convert ISO to psTime. … … 135 149 * @return psTime: time 136 150 */ 137 psTime psISOToTime( 138 char *time /** Input time to be converted. */ 139 ); 151 152 psTime psISOToTime(char *time 153 /** Input time to be converted. */ 154 ); 140 155 141 156 /** Convert UTC to psTime. … … 146 161 * @return psTime: time in TAI units. 147 162 */ 148 psTime psUTCToTime( 149 psTime time /** Input time to be converted. */ 150 ); 163 164 psTime psUTCToTime(psTime time 165 /** Input time to be converted. */ 166 ); 151 167 152 168 /** Convert MJD to psTime. … … 157 173 * @return psTime: time. 158 174 */ 159 psTime psMJDToTime( 160 double time /** Input time to be converted. */ 161 ); 175 176 psTime psMJDToTime(double time 177 /** Input time to be converted. */ 178 ); 162 179 163 180 /** Convert JD to psTime. … … 168 185 * @return psTime: time. 169 186 */ 170 psTime psJDToTime( 171 double time /** Input time to be converted. */ 172 ); 187 188 psTime psJDToTime(double time 189 /** Input time to be converted. */ 190 ); 173 191 174 192 /** Convert timeval to psTime. … … 179 197 * @return psTime: time. 180 198 */ 181 psTime psTimevalToTime( 182 struct timeval *time /** Input time to be converted. */ 183 ); 199 200 psTime psTimevalToTime(struct timeval *time 201 /** Input time to be converted. */ 202 ); 184 203 185 204 /** Convert tm time to psTime. … … 190 209 * @return psTime: time. 191 210 */ 192 psTime psTMToTime( 193 struct tm *time /** Input time to be converted. */ 194 ); 211 212 psTime psTMToTime(struct tm *time 213 /** Input time to be converted. */ 214 ); 215 195 216 /// @} 196 217 -
trunk/psLib/src/astronomy/psAstrometry.c
r1406 r1407 1 1 2 /** @file psAstrometry.c 2 3 * … … 8 9 * @author George Gusciora, MHPCC 9 10 * 10 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 20 21 #include "psMemory.h" 21 22 22 static void grommitFree( psGrommit *grommit);23 static int checkValidChipCoords( double x, double y, psChip *tmpChip);24 static int checkValidImageCoords( double x, double y, psImage *tmpImage);25 26 psExposure * psExposureAlloc(double ra, double dec, double hourAngle,27 double zenith, double azimuth, double localTime, float date,28 float rotAngle, float temperature, float pressure, float humidity,29 float exposureTime)30 { 31 psExposure * exp = psAlloc( sizeof( psExposure ));32 33 *( double* ) &exp->ra = ra;34 *( double* ) &exp->dec = dec;35 *( double* ) &exp->hourAngle = hourAngle;36 *( double* ) &exp->zenith = zenith;37 *( double* ) &exp->azimuth = azimuth;38 *( double* ) &exp->localTime = localTime;39 *( float* ) &exp->date = date;40 *( float* ) &exp->rotAngle = rotAngle;41 *( float* ) &exp->temperature = temperature;42 *( float* ) &exp->pressure = pressure;43 *( float* ) &exp->humidity = humidity;44 *( float* ) &exp->exposureTime = exposureTime;23 static void grommitFree(psGrommit * grommit); 24 static int checkValidChipCoords(double x, double y, psChip * tmpChip); 25 static int checkValidImageCoords(double x, double y, psImage * tmpImage); 26 27 psExposure *psExposureAlloc(double ra, double dec, double hourAngle, 28 double zenith, double azimuth, double localTime, float date, 29 float rotAngle, float temperature, float pressure, float humidity, 30 float exposureTime) 31 { 32 psExposure *exp = psAlloc(sizeof(psExposure)); 33 34 *(double *)&exp->ra = ra; 35 *(double *)&exp->dec = dec; 36 *(double *)&exp->hourAngle = hourAngle; 37 *(double *)&exp->zenith = zenith; 38 *(double *)&exp->azimuth = azimuth; 39 *(double *)&exp->localTime = localTime; 40 *(float *)&exp->date = date; 41 *(float *)&exp->rotAngle = rotAngle; 42 *(float *)&exp->temperature = temperature; 43 *(float *)&exp->pressure = pressure; 44 *(float *)&exp->humidity = humidity; 45 *(float *)&exp->exposureTime = exposureTime; 45 46 46 47 return exp; … … 48 49 } 49 50 50 psGrommit* psGrommitAlloc( const psExposure *exp ) 51 { 52 double * slaGrommit = ( double * ) psAlloc( 14 * sizeof( double ) ); 53 psGrommit *grommit = ( psGrommit * ) psAlloc( sizeof( psGrommit ) ); 51 psGrommit *psGrommitAlloc(const psExposure * exp) 52 { 53 double *slaGrommit = (double *)psAlloc(14 * sizeof(double)); 54 psGrommit *grommit = (psGrommit *) psAlloc(sizeof(psGrommit)); 55 54 56 /* 55 extern void sla_aoppa(double date, 56 double dut, 57 double elongm, 58 double phim, 59 double him, 60 double xp, 61 double yp, 62 double tdk, 63 double pmb, 64 double rh, 65 double wl, 66 double tlr, 67 double *AOPRMS); 68 69 sla_aoppa(date, deltaUT, meanLongitude, meanLatitude, height, xp, yp, 70 exp->temperature, exp->pressure, exp->humidity, wavelength, 71 tlr); 72 */ 73 *( double* ) & grommit->latitude = exp->dec; // XXX Is this correct? 74 *( double* ) & grommit->sinLat = sin( grommit->latitude ); 75 *( double* ) & grommit->cosLat = cos( grommit->latitude ); 76 *( double* ) & grommit->abberationMag = 0.0; 77 *( double* ) & grommit->height = 0.0; 78 *( double* ) & grommit->temperature = exp->temperature; 79 *( double* ) & grommit->pressure = exp->pressure; 80 *( double* ) & grommit->humidity = exp->humidity; 81 *( double* ) & grommit->wavelength = 0.0; 82 *( double* ) & grommit->lapseRate = 0.0; 83 *( double* ) & grommit->refractA = 0.0; 84 *( double* ) & grommit->refractB = 0.0; 85 *( double* ) & grommit->longitudeOffset = exp->ra; // XXX Is this correct? 86 *( double* ) & grommit->siderealTime = 0.0; 87 88 psFree( slaGrommit ); 89 return ( grommit ); 90 } 91 92 void p_psGrommitFree( psGrommit *grommit ) 93 { 94 psFree( grommit ); 95 } 96 97 psCell *psCellinFPA( psCell *out, 98 const psPlane *coord, 99 const psFPA *FPA ) 100 { 101 psChip * tmpChip = NULL; 57 * extern void sla_aoppa(double date, double dut, double elongm, double phim, double him, double xp, 58 * double yp, double tdk, double pmb, double rh, double wl, double tlr, double *AOPRMS); 59 * 60 * sla_aoppa(date, deltaUT, meanLongitude, meanLatitude, height, xp, yp, exp->temperature, exp->pressure, 61 * exp->humidity, wavelength, tlr); */ 62 *(double *)&grommit->latitude = exp->dec; // XXX Is this correct? 63 *(double *)&grommit->sinLat = sin(grommit->latitude); 64 *(double *)&grommit->cosLat = cos(grommit->latitude); 65 *(double *)&grommit->abberationMag = 0.0; 66 *(double *)&grommit->height = 0.0; 67 *(double *)&grommit->temperature = exp->temperature; 68 *(double *)&grommit->pressure = exp->pressure; 69 *(double *)&grommit->humidity = exp->humidity; 70 *(double *)&grommit->wavelength = 0.0; 71 *(double *)&grommit->lapseRate = 0.0; 72 *(double *)&grommit->refractA = 0.0; 73 *(double *)&grommit->refractB = 0.0; 74 *(double *)&grommit->longitudeOffset = exp->ra; // XXX Is this correct? 75 *(double *)&grommit->siderealTime = 0.0; 76 77 psFree(slaGrommit); 78 return (grommit); 79 } 80 81 void p_psGrommitFree(psGrommit * grommit) 82 { 83 psFree(grommit); 84 } 85 86 psCell *psCellinFPA(psCell * out, const psPlane * coord, const psFPA * FPA) 87 { 88 psChip *tmpChip = NULL; 102 89 psCell *tmpCell = NULL; 103 90 104 tmpChip = psChipinFPA( tmpChip, coord, FPA ); 105 tmpCell = psCellinChip( tmpCell, coord, tmpChip ); 106 return ( tmpCell ); 107 } 108 109 110 int checkValidChipCoords( double x, double y, psChip *tmpChip ) 111 { 112 return ( 0 ); 113 } 114 115 psChip *psChipinFPA( psChip *out, 116 const psPlane *coord, 117 const psFPA *FPA ) 118 { 119 psArray * chips = FPA->chips; 91 tmpChip = psChipinFPA(tmpChip, coord, FPA); 92 tmpCell = psCellinChip(tmpCell, coord, tmpChip); 93 return (tmpCell); 94 } 95 96 int checkValidChipCoords(double x, double y, psChip * tmpChip) 97 { 98 return (0); 99 } 100 101 psChip *psChipinFPA(psChip * out, const psPlane * coord, const psFPA * FPA) 102 { 103 psArray *chips = FPA->chips; 120 104 int nChips = chips->n; 121 psPlane *tmpCoord = NULL;122 123 for ( int i = 0; i < nChips; i++) {124 psChip * tmpChip = chips->data[ i];125 tmpCoord = psPlaneTransformApply( tmpCoord, tmpChip->fromFPA, coord ); 126 if ( checkValidChipCoords( tmpCoord->x, tmpCoord->y,127 tmpChip )) {128 psFree( tmpCoord);105 psPlane *tmpCoord = NULL; 106 107 for (int i = 0; i < nChips; i++) { 108 psChip *tmpChip = chips->data[i]; 109 110 tmpCoord = psPlaneTransformApply(tmpCoord, tmpChip->fromFPA, coord); 111 if (checkValidChipCoords(tmpCoord->x, tmpCoord->y, tmpChip)) { 112 psFree(tmpCoord); 129 113 // XXX: George, you didn't use the out parameter! 130 return ( tmpChip);114 return (tmpChip); 131 115 } 132 psFree( tmpCoord ); 133 } 134 psFree( tmpCoord ); 135 return ( NULL ); 136 } 137 138 int checkValidImageCoords( double x, double y, psImage *tmpImage ) 139 { 140 if ( ( x < 0.0 ) || 141 ( x > ( double ) tmpImage->numCols ) || 142 ( y < 0.0 ) || 143 ( y > ( double ) tmpImage->numRows ) ) { 144 return ( 0 ); 145 } 146 return ( 1 ); 147 } 148 116 psFree(tmpCoord); 117 } 118 psFree(tmpCoord); 119 return (NULL); 120 } 121 122 int checkValidImageCoords(double x, double y, psImage * tmpImage) 123 { 124 if ((x < 0.0) || (x > (double)tmpImage->numCols) || (y < 0.0) || (y > (double)tmpImage->numRows)) { 125 return (0); 126 } 127 return (1); 128 } 149 129 150 130 /***************************************************************************** … … 160 140 XXX: must deallocate memory. 161 141 *****************************************************************************/ 162 psCell *psCellinChip( psCell *out, 163 const psPlane *coord, 164 const psChip *chip ) 165 { 166 psPlane * tmpCoord = NULL; 167 psArray* cells; 168 169 if ( chip == NULL ) { 142 psCell *psCellinChip(psCell * out, const psPlane * coord, const psChip * chip) 143 { 144 psPlane *tmpCoord = NULL; 145 psArray *cells; 146 147 if (chip == NULL) { 170 148 return NULL; 171 149 } … … 173 151 cells = chip->cells; 174 152 175 if ( cells == NULL) {153 if (cells == NULL) { 176 154 return NULL; 177 155 } 178 156 179 for ( int i = 0; i < cells->n; i++ ) { 180 psCell* tmpCell = ( psCell* ) cells->data[ i ]; 181 psArray* readouts = tmpCell->readouts; 182 if ( readouts != NULL ) { 183 for ( int j = 0; j < readouts->n; j++ ) { 184 psReadout* tmpReadout = readouts->data[ j ]; 185 tmpCoord = psPlaneTransformApply( tmpCoord, tmpCell->fromChip, coord ); 186 if ( checkValidImageCoords( tmpCoord->x, tmpCoord->y, 187 tmpReadout->image ) ) { 188 return ( tmpCell ); 157 for (int i = 0; i < cells->n; i++) { 158 psCell *tmpCell = (psCell *) cells->data[i]; 159 psArray *readouts = tmpCell->readouts; 160 161 if (readouts != NULL) { 162 for (int j = 0; j < readouts->n; j++) { 163 psReadout *tmpReadout = readouts->data[j]; 164 165 tmpCoord = psPlaneTransformApply(tmpCoord, tmpCell->fromChip, coord); 166 if (checkValidImageCoords(tmpCoord->x, tmpCoord->y, tmpReadout->image)) { 167 return (tmpCell); 189 168 } 190 169 } 191 170 } 192 171 } 193 return ( NULL ); 194 } 195 196 psPlane *psCoordCelltoChip( psPlane *out, 197 const psPlane *in, 198 const psCell *cell ) 199 { 200 return ( psPlaneTransformApply( out, cell->toChip, in ) ); 201 } 202 203 psPlane *psCoordChipToFPA( psPlane *out, 204 const psPlane *in, 205 const psChip *chip ) 206 { 207 return ( psPlaneTransformApply( out, chip->toFPA, in ) ); 208 } 209 210 psPlane *psCoordFPAtoTP( psPlane *out, 211 const psPlane *in, 212 const psFPA *fpa ) 172 return (NULL); 173 } 174 175 psPlane *psCoordCelltoChip(psPlane * out, const psPlane * in, const psCell * cell) 176 { 177 return (psPlaneTransformApply(out, cell->toChip, in)); 178 } 179 180 psPlane *psCoordChipToFPA(psPlane * out, const psPlane * in, const psChip * chip) 181 { 182 return (psPlaneTransformApply(out, chip->toFPA, in)); 183 } 184 185 psPlane *psCoordFPAtoTP(psPlane * out, const psPlane * in, const psFPA * fpa) 213 186 { 214 187 // XXX: This code doesn't work; fpa->toTangentPlane is of the wrong type. 215 188 // return(psPlaneTransformApply(out, fpa->toTangentPlane, in)); 216 return ( NULL);189 return (NULL); 217 190 } 218 191 219 192 // XXX: must wrap SLA_QAPQK here. 220 psSphere *psCoordTPtoSky( psSphere *out, 221 const psPlane *in, 222 const psGrommit *grommit ) 193 psSphere *psCoordTPtoSky(psSphere * out, const psPlane * in, const psGrommit * grommit) 223 194 { 224 195 /* 225 double RAP; 226 double DAP; 227 228 extern void sla_OAPQK(TYPE, OB1, OB2, AOPRMS, RAP, DAP); 229 sla_OAPQK(TYPE, OB1, OB2, *grommit, &RAP, &DAP); 230 */ 231 232 return ( out ); 233 } 234 235 236 psPlane *psCoordCellToFPA( psPlane *out, 237 const psPlane *in, 238 const psCell *cell ) 239 { 240 return ( psPlaneTransformApply( out, cell->toFPA, in ) ); 241 } 242 196 * double RAP; double DAP; 197 * 198 * extern void sla_OAPQK(TYPE, OB1, OB2, AOPRMS, RAP, DAP); sla_OAPQK(TYPE, OB1, OB2, *grommit, &RAP, 199 * &DAP); */ 200 201 return (out); 202 } 203 204 psPlane *psCoordCellToFPA(psPlane * out, const psPlane * in, const psCell * cell) 205 { 206 return (psPlaneTransformApply(out, cell->toFPA, in)); 207 } 243 208 244 209 // XXX: This implementation requires a new psGrommit be created for each 245 210 // transformation, as well as a few psPlane structs. Can this be implemented 246 211 // better? 247 psSphere *psCoordCelltoSky( psSphere *out, 248 const psPlane *in, 249 const psCell *cell ) 250 { 251 psPlane * tmp1 = NULL; 212 psSphere *psCoordCelltoSky(psSphere * out, const psPlane * in, const psCell * cell) 213 { 214 psPlane *tmp1 = NULL; 252 215 psPlane *tmp2 = NULL; 253 psFPA *parFPA = ( cell->parent )->parent;216 psFPA *parFPA = (cell->parent)->parent; 254 217 psGrommit *tmpGrommit = NULL; 255 218 256 tmp1 = psPlaneTransformApply( tmp1, cell->toFPA, in ); 257 tmp2 = psPlaneTransformApply( tmp2, parFPA->toTangentPlane, tmp1 ); 258 tmpGrommit = psGrommitAlloc( parFPA->exposure ); 259 tmp3 = psCoordTPtoSky( out, tmp2, psGrommit ); 260 261 psFree( tmp1 ); 262 psFree( tmp2 ); 263 psFree( tmpGrommit ); 264 265 return ( psCoordTPtoSky( out, tmp2, psGrommit ) ); 266 267 } 268 269 psSphere *psCoordCelltoSkyQuick( psSphere *out, 270 const psPlane *in, 271 const psCell *cell ) 272 { 273 psPlane * tmp1 = NULL; 274 275 tmp1 = psPlaneTransformApply( tmp1, cell->toSky, in ); 276 277 //XXX: Do something to convert the linear coords in tmp1 to spherical 219 tmp1 = psPlaneTransformApply(tmp1, cell->toFPA, in); 220 tmp2 = psPlaneTransformApply(tmp2, parFPA->toTangentPlane, tmp1); 221 tmpGrommit = psGrommitAlloc(parFPA->exposure); 222 tmp3 = psCoordTPtoSky(out, tmp2, psGrommit); 223 224 psFree(tmp1); 225 psFree(tmp2); 226 psFree(tmpGrommit); 227 228 return (psCoordTPtoSky(out, tmp2, psGrommit)); 229 230 } 231 232 psSphere *psCoordCelltoSkyQuick(psSphere * out, const psPlane * in, const psCell * cell) 233 { 234 psPlane *tmp1 = NULL; 235 236 tmp1 = psPlaneTransformApply(tmp1, cell->toSky, in); 237 238 // XXX: Do something to convert the linear coords in tmp1 to spherical 278 239 // coords in out. 279 240 280 psFree( tmp1);281 282 return ( out);241 psFree(tmp1); 242 243 return (out); 283 244 } 284 245 285 246 // XXX: must wrap SLA_AOPQK here. 286 psPlane *psCoordSkytoTP( psPlane *out, 287 const psSphere *in, 288 const psGrommit *grommit ) 289 { 290 extern void sla_AOPQK ( RAP, DAP, AOPRMS, AOB, ZOB, HOB, DOB, ROB ); 247 psPlane *psCoordSkytoTP(psPlane * out, const psSphere * in, const psGrommit * grommit) 248 { 249 extern void sla_AOPQK(RAP, DAP, AOPRMS, AOB, ZOB, HOB, DOB, ROB); 291 250 double AOB; 292 251 double ZOB; … … 295 254 double ROB; 296 255 297 if ( out == NULL) {298 out = ( psPlane * ) psAlloc( sizeof( psPlane ));299 } 300 301 sla_AOPQK( psSphere->r, psSphere->d, *grommit, &AOB, &ZOB, &HOB, &DOB, &ROB);256 if (out == NULL) { 257 out = (psPlane *) psAlloc(sizeof(psPlane)); 258 } 259 260 sla_AOPQK(psSphere->r, psSphere->d, *grommit, &AOB, &ZOB, &HOB, &DOB, &ROB); 302 261 out->x = XXX; 303 262 out->y = XXX; 304 return ( out ); 305 } 306 307 psPlane *psCoordTPtoFPA( psPlane *out, 308 const psPlane *in, 309 const psFPA *fpa ) 310 { 311 return ( psPlaneTransformApply( out, fpa->fromTangentPlane, in ) ); 312 } 313 314 psPlane *psCoordFPAtoChip( psPlane *out, 315 const psPlane *in, 316 const psChip *chip ) 317 { 318 return ( psPlaneTransformApply( out, chip->fromFPA, in ) ); 319 } 320 321 322 psPlane *psCoordChiptoCell( psPlane *out, 323 const psPlane *in, 324 const psCell *cell ) 325 { 326 return ( psPlaneTransformApply( out, cell->fromChip, in ) ); 327 } 328 329 psPlane *psCoordSkytoCell( psPlane *out, 330 const psSphere *in, 331 const psCell *cell ) 332 { 333 out = psCoordSkytoTP( out, in, tmpGrommit ); 334 out = psCoordTPtoFPA( out, out, whichFPA ); 335 out = psCoordFPAtoChip( out, out, whichChip ); 336 out = psCoordChiptoCell( out, out, whichCell ); 337 338 return ( out ); 339 } 340 341 psPlane *psCoordSkytoCellQuick( psPlane *out, 342 const psSphere *in, 343 const psCell *cell ) 344 { 345 if ( out == NULL ) { 346 out = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 347 } 348 349 return ( out ); 350 } 351 352 353 354 263 return (out); 264 } 265 266 psPlane *psCoordTPtoFPA(psPlane * out, const psPlane * in, const psFPA * fpa) 267 { 268 return (psPlaneTransformApply(out, fpa->fromTangentPlane, in)); 269 } 270 271 psPlane *psCoordFPAtoChip(psPlane * out, const psPlane * in, const psChip * chip) 272 { 273 return (psPlaneTransformApply(out, chip->fromFPA, in)); 274 } 275 276 psPlane *psCoordChiptoCell(psPlane * out, const psPlane * in, const psCell * cell) 277 { 278 return (psPlaneTransformApply(out, cell->fromChip, in)); 279 } 280 281 psPlane *psCoordSkytoCell(psPlane * out, const psSphere * in, const psCell * cell) 282 { 283 out = psCoordSkytoTP(out, in, tmpGrommit); 284 out = psCoordTPtoFPA(out, out, whichFPA); 285 out = psCoordFPAtoChip(out, out, whichChip); 286 out = psCoordChiptoCell(out, out, whichCell); 287 288 return (out); 289 } 290 291 psPlane *psCoordSkytoCellQuick(psPlane * out, const psSphere * in, const psCell * cell) 292 { 293 if (out == NULL) { 294 out = (psPlane *) psAlloc(sizeof(psPlane)); 295 } 296 297 return (out); 298 } -
trunk/psLib/src/astronomy/psAstrometry.h
r1406 r1407 1 1 2 /** @file psAstrometry.h 2 3 * … … 8 9 * @author George Gusciora, MHPCC 9 10 * 10 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 14 15 */ 15 16 16 # ifndef PS_ASTROMETRY_H17 # define PS_ASTROMETRY_H18 19 # include "psType.h"20 # include "psImage.h"21 # include "psArray.h"22 # include "psList.h"23 # include "psFunctions.h"24 # include "psMetadata.h"25 # include "psCoord.h"26 # include "psPhotometry.h"17 #ifndef PS_ASTROMETRY_H 18 # define PS_ASTROMETRY_H 19 20 # include "psType.h" 21 # include "psImage.h" 22 # include "psArray.h" 23 # include "psList.h" 24 # include "psFunctions.h" 25 # include "psMetadata.h" 26 # include "psCoord.h" 27 # include "psPhotometry.h" 27 28 28 29 struct psCell; … … 44 45 typedef struct 45 46 { 46 const double latitude; ///< geodetic latitude (radians)47 const double sinLat; ///< sine of geodetic latitude48 const double cosLat; ///< cosine of geodetic latitude49 const double abberationMag; ///< magnitude of diurnal aberration vector50 const double height; ///< height (HM)51 const double temperature; ///< ambient temperature (TDK)52 const double pressure; ///< pressure (PMB)53 const double humidity; ///< relative humidity (RH)54 const double wavelength; ///< wavelength (WL)55 const double lapseRate; ///< lapse rate (TLR)56 const double refractA; ///< refraction constant A (radians)57 const double refractB; ///< refraction constant B (radians)58 const double longitudeOffset; ///< longitude + ... (radians)59 const double siderealTime; ///< local apparent sidereal time (radians)47 const double latitude; // /< geodetic latitude (radians) 48 const double sinLat; // /< sine of geodetic latitude 49 const double cosLat; // /< cosine of geodetic latitude 50 const double abberationMag; // /< magnitude of diurnal aberration vector 51 const double height; // /< height (HM) 52 const double temperature; // /< ambient temperature (TDK) 53 const double pressure; // /< pressure (PMB) 54 const double humidity; // /< relative humidity (RH) 55 const double wavelength; // /< wavelength (WL) 56 const double lapseRate; // /< lapse rate (TLR) 57 const double refractA; // /< refraction constant A (radians) 58 const double refractB; // /< refraction constant B (radians) 59 const double longitudeOffset; // /< longitude + ... (radians) 60 const double siderealTime; // /< local apparent sidereal time (radians) 60 61 } 61 62 psGrommit; … … 72 73 typedef struct 73 74 { 74 int nX; ///< Number of elements in x direction75 int nY; ///< Number of elements in y direction76 double x0; ///< X Position of 0,0 corner on focal plane77 double y0; ///< Y Position of 0,0 corner on focal plane78 double xScale; ///< Scale of the grid in x direction79 double yScale; ///< Scale of the grid in x direction80 double **x; ///< The grid of offsets in x81 double **y; ///< The grid of offsets in y75 int nX; // /< Number of elements in x direction 76 int nY; // /< Number of elements in y direction 77 double x0; // /< X Position of 0,0 corner on focal plane 78 double y0; // /< Y Position of 0,0 corner on focal plane 79 double xScale; // /< Scale of the grid in x direction 80 double yScale; // /< Scale of the grid in x direction 81 double **x; // /< The grid of offsets in x 82 double **y; // /< The grid of offsets in y 82 83 } 83 84 psFixedPattern; … … 94 95 typedef struct 95 96 { 96 const unsigned int colBins; ///< Amount of binning in x-dimension97 const unsigned int rowBins; ///< Amount of binning in y-dimension98 const int col0; ///< Offset from the left of chip.99 const int row0; ///< Offset from the bottom of chip.100 101 psImage * image; ///< imaging area of Readout102 psList * objects; ///< objects derived from Readout103 psMetadata * metadata; ///< readout-level metadata97 const unsigned int colBins; // /< Amount of binning in x-dimension 98 const unsigned int rowBins; // /< Amount of binning in y-dimension 99 const int col0; // /< Offset from the left of chip. 100 const int row0; // /< Offset from the bottom of chip. 101 102 psImage *image; // /< imaging area of Readout 103 psList *objects; // /< objects derived from Readout 104 psMetadata *metadata; // /< readout-level metadata 104 105 } 105 106 psReadout; … … 116 117 typedef struct psCell 117 118 { 118 psArray * readouts; ///< readouts from the cell119 psMetadata * metadata; ///< cell-level metadata120 121 psPlaneTransform * toChip; ///< transformations from cell to chip coordinates122 psPlaneTransform * fromChip; ///< transformations from chip to cell coordinates123 psPlaneTransform * toFPA; ///< transformations from cell to FPA coordinates124 psPlaneTransform * toSky; ///< transformations from cell to sky coordinates125 126 struct psChip * parent; ///< chip in which contains this cell119 psArray *readouts; // /< readouts from the cell 120 psMetadata *metadata; // /< cell-level metadata 121 122 psPlaneTransform *toChip; // /< transformations from cell to chip coordinates 123 psPlaneTransform *fromChip; // /< transformations from chip to cell coordinates 124 psPlaneTransform *toFPA; // /< transformations from cell to FPA coordinates 125 psPlaneTransform *toSky; // /< transformations from cell to sky coordinates 126 127 struct psChip *parent; // /< chip in which contains this cell 127 128 } 128 129 psCell; … … 138 139 typedef struct psChip 139 140 { 140 psArray * cells; ///< cells in the chip141 psMetadata * metadata; ///< chip-level metadata142 143 psPlaneTransform * toFPA; ///< transformation from chip to FPA coordinates144 psPlaneTransform * fromFPA; ///< transformation from FPA to chip coordinates145 146 struct psFPA * parent; ///< FPA which contains this chip141 psArray *cells; // /< cells in the chip 142 psMetadata *metadata; // /< chip-level metadata 143 144 psPlaneTransform *toFPA; // /< transformation from chip to FPA coordinates 145 psPlaneTransform *fromFPA; // /< transformation from FPA to chip coordinates 146 147 struct psFPA *parent; // /< FPA which contains this chip 147 148 } 148 149 psChip; … … 163 164 typedef struct psFPA 164 165 { 165 psArray * chips; ///< chips in the focal plane array166 psMetadata * metadata; ///< focal-plane's metadata167 168 psPlaneDistort * fromTangentPlane; ///< transformation from tangent plane to focal plane169 psPlaneDistort * toTangentPlane; ///< transformation from focal plane to tangent plane170 psFixedPattern * pattern; ///< fixed pattern residual offsets171 172 const struct psExposure * exposure; ///< information about this exposure173 174 psPhotSystem * colorPlus; ///< Color reference175 psPhotSystem * colorMinus; ///< Color reference176 177 float rmsX; ///< RMS for x transformation fits178 float rmsY; ///< RMS for y transformation fits179 float chi2; ///< chi^2 of astrometric solution166 psArray *chips; // /< chips in the focal plane array 167 psMetadata *metadata; // /< focal-plane's metadata 168 169 psPlaneDistort *fromTangentPlane; // /< transformation from tangent plane to focal plane 170 psPlaneDistort *toTangentPlane; // /< transformation from focal plane to tangent plane 171 psFixedPattern *pattern; // /< fixed pattern residual offsets 172 173 const struct psExposure *exposure; // /< information about this exposure 174 175 psPhotSystem *colorPlus; // /< Color reference 176 psPhotSystem *colorMinus; // /< Color reference 177 178 float rmsX; // /< RMS for x transformation fits 179 float rmsY; // /< RMS for y transformation fits 180 float chi2; // /< chi^2 of astrometric solution 180 181 } 181 182 psFPA; … … 190 191 typedef struct psExposure 191 192 { 192 const double ra; ///< Telescope boresight, right ascention193 const double dec; ///< Telescope boresight, declination194 const double hourAngle; ///< Hour angle195 const double zenith; ///< Zenith distance196 const double azimuth; ///< Azimuth197 const double localTime; ///< Local Sidereal Time198 const float date; ///< Modified Jullian Date of observation199 const float rotAngle; ///< Rotator position angle200 const float temperature; ///< Air temperature, for estimating refraction201 const float pressure; ///< Air pressure, for calculating refraction202 const float humidity; ///< Relative humidity, for refraction203 const float exposureTime; ///< Exposure time193 const double ra; // /< Telescope boresight, right ascention 194 const double dec; // /< Telescope boresight, declination 195 const double hourAngle; // /< Hour angle 196 const double zenith; // /< Zenith distance 197 const double azimuth; // /< Azimuth 198 const double localTime; // /< Local Sidereal Time 199 const float date; // /< Modified Jullian Date of observation 200 const float rotAngle; // /< Rotator position angle 201 const float temperature; // /< Air temperature, for estimating refraction 202 const float pressure; // /< Air pressure, for calculating refraction 203 const float humidity; // /< Relative humidity, for refraction 204 const float exposureTime; // /< Exposure time 204 205 205 206 /* Derived quantities */ 206 const float positionAngle; ///< Position angle207 const float parallacticAngle; ///< Parallactic angle208 const float airmass; ///< Airmass, calculated from zenith distance209 const float parallacticFactor; ///< Parallactic factor210 const char *cameraName; ///< name of camera which provided exposure211 const char *telescopeName; ///< name of telescope which provided exposure207 const float positionAngle; // /< Position angle 208 const float parallacticAngle; // /< Parallactic angle 209 const float airmass; // /< Airmass, calculated from zenith distance 210 const float parallacticFactor; // /< Parallactic factor 211 const char *cameraName; // /< name of camera which provided exposure 212 const char *telescopeName; // /< name of telescope which provided exposure 212 213 } 213 214 psExposure; 214 215 215 psExposure* psExposureAlloc( 216 double ra, ///< Telescope boresight, right ascention 217 double dec, ///< Telescope boresight, declination 218 double hourAngle, ///< Hour angle 219 double zenith, ///< Zenith distance 220 double azimuth, ///< Azimuth 221 double localTime, ///< Local Sidereal Time 222 float date, ///< MJD 223 float rotAngle, ///< Rotator position angle 224 float temperature, ///< Temperature 225 float pressure, ///< Pressure 226 float humidity, ///< Relative humidity 227 float exposureTime ///< Exposure time 228 ); 216 psExposure *psExposureAlloc(double ra, // /< Telescope boresight, right ascention 217 double dec, // /< Telescope boresight, declination 218 double hourAngle, // /< Hour angle 219 double zenith, // /< Zenith distance 220 double azimuth, // /< Azimuth 221 double localTime, // /< Local Sidereal Time 222 float date, // /< MJD 223 float rotAngle, // /< Rotator position angle 224 float temperature, // /< Temperature 225 float pressure, // /< Pressure 226 float humidity, // /< Relative humidity 227 float exposureTime // /< Exposure time 228 ); 229 229 230 230 /** Allocates a Wallace's Grommit structure. … … 235 235 * @return psGrommit* New grommit structure. 236 236 */ 237 psGrommit* psGrommitAlloc( 238 const psExposure* exp ///< the cooresponding exposure structure. 239 ); 240 241 psCell *psCellinFPA( 242 psCell *out, 243 const psPlane *coord, 244 const psFPA *FPA 245 ); 246 247 psChip *psChipinFPA( 248 psChip *out, 249 const psPlane *coord, 250 const psFPA *FPA 251 ); 252 253 psCell *psCellinChip( 254 psCell *out, 255 const psPlane *coord, 256 const psChip *chip 257 ); 258 259 psPlane *psCoordCelltoChip( 260 psPlane *out, 261 const psPlane *in, 262 const psCell *cell 263 ); 264 265 psPlane *psCoordChipToFPA( 266 psPlane *out, 267 const psPlane *in, 268 const psChip *chip 269 ); 270 271 psPlane *psCoordFPAtoTP( 272 psPlane *out, 273 const psPlane *in, 274 const psFPA *fpa 275 ); 276 277 psSphere *psCoordTPtoSky( 278 psSphere *out, 279 const psPlane *in, 280 const psGrommit *grommit 281 ); 282 283 psPlane *psCoordCellToFPA( 284 psPlane *out, 285 const psPlane *in, 286 const psCell *cell 287 ); 288 289 psSphere *psCoordCelltoSky( 290 psSphere *out, 291 const psPlane *in, 292 const psCell *cell 293 ); 294 295 psSphere *psCoordCelltoSkyQuick( 296 psSphere *out, 297 const psPlane *in, 298 const psCell *cell 299 ); 300 301 psPlane *psCoordSkytoTP( 302 psPlane *out, 303 const psSphere *in, 304 const psGrommit *grommit 305 ); 306 307 psPlane *psCoordTPtoFPA( 308 psPlane *out, 309 const psPlane *in, 310 const psFPA *fpa 311 ); 312 313 psPlane *psCoordFPAtoChip( 314 psPlane *out, 315 const psPlane *in, 316 const psChip *chip 317 ); 318 319 psPlane *psCoordChiptoCell( 320 psPlane *out, 321 const psPlane *in, 322 const psCell *cell 323 ); 324 325 psPlane *psCoordSkytoCell( 326 psPlane *out, 327 const psSphere *in, 328 const psCell *cell 329 ); 330 331 psPlane *psCoordSkytoCellQuick( 332 psPlane *out, 333 const psSphere *in, 334 const psCell *cell 335 ); 237 psGrommit *psGrommitAlloc(const psExposure * exp // /< the cooresponding exposure structure. 238 ); 239 240 psCell *psCellinFPA(psCell * out, const psPlane * coord, const psFPA * FPA); 241 242 psChip *psChipinFPA(psChip * out, const psPlane * coord, const psFPA * FPA); 243 244 psCell *psCellinChip(psCell * out, const psPlane * coord, const psChip * chip); 245 246 psPlane *psCoordCelltoChip(psPlane * out, const psPlane * in, const psCell * cell); 247 248 psPlane *psCoordChipToFPA(psPlane * out, const psPlane * in, const psChip * chip); 249 250 psPlane *psCoordFPAtoTP(psPlane * out, const psPlane * in, const psFPA * fpa); 251 252 psSphere *psCoordTPtoSky(psSphere * out, const psPlane * in, const psGrommit * grommit); 253 254 psPlane *psCoordCellToFPA(psPlane * out, const psPlane * in, const psCell * cell); 255 256 psSphere *psCoordCelltoSky(psSphere * out, const psPlane * in, const psCell * cell); 257 258 psSphere *psCoordCelltoSkyQuick(psSphere * out, const psPlane * in, const psCell * cell); 259 260 psPlane *psCoordSkytoTP(psPlane * out, const psSphere * in, const psGrommit * grommit); 261 262 psPlane *psCoordTPtoFPA(psPlane * out, const psPlane * in, const psFPA * fpa); 263 264 psPlane *psCoordFPAtoChip(psPlane * out, const psPlane * in, const psChip * chip); 265 266 psPlane *psCoordChiptoCell(psPlane * out, const psPlane * in, const psCell * cell); 267 268 psPlane *psCoordSkytoCell(psPlane * out, const psSphere * in, const psCell * cell); 269 270 psPlane *psCoordSkytoCellQuick(psPlane * out, const psSphere * in, const psCell * cell); 336 271 337 272 #endif -
trunk/psLib/src/astronomy/psCoord.c
r1406 r1407 1 1 2 /** @file psCoord.c 2 3 * … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 #include <float.h> 28 29 29 static float cot( float x);30 static float arg( float x, float y);30 static float cot(float x); 31 static float arg(float x, float y); 31 32 32 33 // This is the only function in this file which I understand. 33 psPlane *psPlaneTransformApply( psPlane *out, 34 const psPlaneTransform *transform, 35 const psPlane *coords ) 36 { 37 if ( out == NULL ) { 38 out = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 39 } 40 out->x = transform->x->coeff[ 0 ][ 0 ] + 41 ( transform->x->coeff[ 1 ][ 0 ] * coords->x ) + 42 ( transform->x->coeff[ 0 ][ 1 ] * coords->y ); 43 44 out->y = transform->y->coeff[ 0 ][ 0 ] + 45 ( transform->y->coeff[ 1 ][ 0 ] * coords->x ) + 46 ( transform->y->coeff[ 0 ][ 1 ] * coords->y ); 47 48 return ( out ); 49 } 50 34 psPlane *psPlaneTransformApply(psPlane * out, const psPlaneTransform * transform, const psPlane * coords) 35 { 36 if (out == NULL) { 37 out = (psPlane *) psAlloc(sizeof(psPlane)); 38 } 39 out->x = transform->x->coeff[0][0] + 40 (transform->x->coeff[1][0] * coords->x) + (transform->x->coeff[0][1] * coords->y); 41 42 out->y = transform->y->coeff[0][0] + 43 (transform->y->coeff[1][0] * coords->x) + (transform->y->coeff[0][1] * coords->y); 44 45 return (out); 46 } 51 47 52 48 // This transformation takes into account parameters beyond an objects 53 49 // spatial coordinates: term3 and term4. 54 psPlane *psPlaneDistortApply( psPlane *out, 55 const psPlaneDistort *transform, 56 const psPlane *coords, 57 float term3, 58 float term4 ) 59 { 60 if ( out == NULL ) { 61 out = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 62 } 63 64 out->x = transform->x->coeff[ 0 ][ 0 ][ 0 ][ 0 ] + 65 ( transform->x->coeff[ 1 ][ 0 ][ 0 ][ 0 ] * coords->x ) + 66 ( transform->x->coeff[ 0 ][ 1 ][ 0 ][ 0 ] * coords->y ) + 67 ( transform->x->coeff[ 0 ][ 0 ][ 1 ][ 0 ] * term3 ) + 68 ( transform->x->coeff[ 0 ][ 0 ][ 0 ][ 1 ] * term4 ); 69 70 out->y = transform->y->coeff[ 0 ][ 0 ][ 0 ][ 0 ] + 71 ( transform->y->coeff[ 1 ][ 0 ][ 0 ][ 0 ] * coords->x ) + 72 ( transform->y->coeff[ 0 ][ 1 ][ 0 ][ 0 ] * coords->y ) + 73 ( transform->y->coeff[ 0 ][ 0 ][ 1 ][ 0 ] * term3 ) + 74 ( transform->y->coeff[ 0 ][ 0 ][ 0 ][ 1 ] * term4 ); 75 76 return ( out ); 77 } 78 50 psPlane *psPlaneDistortApply(psPlane * out, 51 const psPlaneDistort * transform, 52 const psPlane * coords, float term3, float term4) 53 { 54 if (out == NULL) { 55 out = (psPlane *) psAlloc(sizeof(psPlane)); 56 } 57 58 out->x = transform->x->coeff[0][0][0][0] + 59 (transform->x->coeff[1][0][0][0] * coords->x) + 60 (transform->x->coeff[0][1][0][0] * coords->y) + 61 (transform->x->coeff[0][0][1][0] * term3) + (transform->x->coeff[0][0][0][1] * term4); 62 63 out->y = transform->y->coeff[0][0][0][0] + 64 (transform->y->coeff[1][0][0][0] * coords->x) + 65 (transform->y->coeff[0][1][0][0] * coords->y) + 66 (transform->y->coeff[0][0][1][0] * term3) + (transform->y->coeff[0][0][0][1] * term4); 67 68 return (out); 69 } 79 70 80 71 // This function prototype has been modified since the SDRS. 81 psSphereTransform *psSphereTransformAlloc( double NPlat, 82 double Xo, 83 double xo ) 84 { 85 psSphereTransform * tmp = ( psSphereTransform * ) psAlloc( sizeof( psSphereTransform ) ); 86 87 tmp->sinPhi = sin( NPlat ); 88 tmp->cosPhi = cos( NPlat ); 72 psSphereTransform *psSphereTransformAlloc(double NPlat, double Xo, double xo) 73 { 74 psSphereTransform *tmp = (psSphereTransform *) psAlloc(sizeof(psSphereTransform)); 75 76 tmp->sinPhi = sin(NPlat); 77 tmp->cosPhi = cos(NPlat); 89 78 tmp->Xo = Xo; 90 79 tmp->xo = xo; 91 80 92 return ( tmp);81 return (tmp); 93 82 } 94 83 … … 100 89 // there are no typo's. 101 90 102 psSphere *psSphereTransformApply( psSphere *out, 103 const psSphereTransform *transform, 104 const psSphere *coord ) 91 psSphere *psSphereTransformApply(psSphere * out, const psSphereTransform * transform, const psSphere * coord) 105 92 { 106 93 double sinY = 0.0; … … 112 99 double dx = 0.0; 113 100 114 if ( out == NULL) {115 out = ( psSphere * ) psAlloc( sizeof( psSphere ));101 if (out == NULL) { 102 out = (psSphere *) psAlloc(sizeof(psSphere)); 116 103 } 117 104 … … 119 106 y = coord->d; 120 107 dx = x - transform->xo; 121 sinY = cos( y ) * sin( dx ) * transform->sinPhi + sin( y ) * transform->cosPhi; 122 cosY = sqrt( 1.0 - sinY * sinY ); 123 sinX = ( cos( y ) * sin( dx ) * transform->cosPhi - sin( y ) * transform->sinPhi ) / 124 cos( y ); 125 cosX = cos( y ) * cos( dx ) / cos( y ); 126 127 out->r = atan2( sinX, cosX ) + transform->Xo; 128 out->d = atan2( sinY, cosY ); 129 130 return ( out ); 131 } 132 133 psSphereTransform *psSphereTransformICRStoEcliptic( psTime time ) 134 { 135 struct tm * tmTime = psTimeToTM( time ); 136 double year = ( double ) ( 1900 + tmTime->tm_year ); 108 sinY = cos(y) * sin(dx) * transform->sinPhi + sin(y) * transform->cosPhi; 109 cosY = sqrt(1.0 - sinY * sinY); 110 sinX = (cos(y) * sin(dx) * transform->cosPhi - sin(y) * transform->sinPhi) / cos(y); 111 cosX = cos(y) * cos(dx) / cos(y); 112 113 out->r = atan2(sinX, cosX) + transform->Xo; 114 out->d = atan2(sinY, cosY); 115 116 return (out); 117 } 118 119 psSphereTransform *psSphereTransformICRStoEcliptic(psTime time) 120 { 121 struct tm *tmTime = psTimeToTM(time); 122 double year = (double)(1900 + tmTime->tm_year); 137 123 double T = year / 100.0; 138 124 double phi = -23.452294 + 0.013013 * T + 0.000001639 * T * T - 0.000000503 * T * T * T; … … 140 126 double xo = 0.0; 141 127 142 return ( psSphereTransformAlloc( phi, Xo, xo ));143 } 144 145 psSphereTransform *psSphereTransformEcliptictoICRS( psTime time)146 { 147 struct tm * tmTime = psTimeToTM( time);148 double year = ( double ) ( 1900 + tmTime->tm_year);128 return (psSphereTransformAlloc(phi, Xo, xo)); 129 } 130 131 psSphereTransform *psSphereTransformEcliptictoICRS(psTime time) 132 { 133 struct tm *tmTime = psTimeToTM(time); 134 double year = (double)(1900 + tmTime->tm_year); 149 135 double T = year / 100.0; 150 double phi = + 23.452294 - 0.013013 * T - 0.000001639 * T * T + 0.000000503 * T * T * T;136 double phi = +23.452294 - 0.013013 * T - 0.000001639 * T * T + 0.000000503 * T * T * T; 151 137 double Xo = 0.0; 152 138 double xo = 0.0; 153 139 154 return ( psSphereTransformAlloc( phi, Xo, xo ));155 } 156 157 psSphereTransform *psSphereTransformICRStoGalatic( void)158 { 159 return ( psSphereTransformAlloc( 62.6, 282.25, 33.0 ));160 } 161 162 psSphereTransform *psSphereTransformGalatictoICRS( void)163 { 164 return ( psSphereTransformAlloc( -62.6, 33.0, 282.25 ));140 return (psSphereTransformAlloc(phi, Xo, xo)); 141 } 142 143 psSphereTransform *psSphereTransformICRStoGalatic(void) 144 { 145 return (psSphereTransformAlloc(62.6, 282.25, 33.0)); 146 } 147 148 psSphereTransform *psSphereTransformGalatictoICRS(void) 149 { 150 return (psSphereTransformAlloc(-62.6, 33.0, 282.25)); 165 151 } 166 152 167 153 // XXX: Is this the correct way to calculate this? 168 float cot( float x)169 { 170 return ( 1.0 / atan( x ));154 float cot(float x) 155 { 156 return (1.0 / atan(x)); 171 157 } 172 158 173 159 // This is some kind of arc tan function. 174 float arg( float x, float y ) 175 { 176 if ( x > 0 ) { 177 return ( atan( y / x ) ); 178 } else 179 if ( ( x == 0 ) && ( y == 0 ) ) { 180 return ( 0.5 * M_PI ); 181 } else 182 if ( ( x == 0 ) && ( y == 0 ) ) { 183 return ( -0.5 * M_PI ); 184 } else 185 if ( ( x == 0 ) && ( y == 0 ) ) { 186 return ( M_PI + atan( y / x ) ); 187 } else 188 if ( ( x == 0 ) && ( y == 0 ) ) { 189 return ( -M_PI + atan( y / x ) ); 190 } 191 192 psAbort( __func__, "Unacceptable range for (arg(%f, %f).\n", x, y ); 193 return ( 0.0 ); 160 float arg(float x, float y) 161 { 162 if (x > 0) { 163 return (atan(y / x)); 164 } else if ((x == 0) && (y == 0)) { 165 return (0.5 * M_PI); 166 } else if ((x == 0) && (y == 0)) { 167 return (-0.5 * M_PI); 168 } else if ((x == 0) && (y == 0)) { 169 return (M_PI + atan(y / x)); 170 } else if ((x == 0) && (y == 0)) { 171 return (-M_PI + atan(y / x)); 172 } 173 174 psAbort(__func__, "Unacceptable range for (arg(%f, %f).\n", x, y); 175 return (0.0); 194 176 } 195 177 196 178 // XXX: Waiting for the definition of the PS_PROJ_PAR projection. 197 179 // XXX: Waiting for the definition of the PS_PROJ_GLS projection. 198 psPlane *psProject( const psSphere *coord, 199 const psProjection *projection ) 180 psPlane *psProject(const psSphere * coord, const psProjection * projection) 200 181 { 201 182 float R = 0.0; 202 183 float alpha = 0.0; 203 psPlane *tmp = ( psPlane * ) psAlloc( sizeof( psPlane ) ); 204 205 if ( projection->type == PS_PROJ_TAN ) { 206 R = cot( coord->r ) * ( 180.0 / M_PI ); 207 tmp->x = R * sin( coord->d ); 208 tmp->y = R * cos( coord->d ); 209 210 } else 211 if ( projection->type == PS_PROJ_SIN ) { 212 R = cos( coord->r ) * ( 180.0 / M_PI ); 213 tmp->x = R * sin( coord->d ); 214 tmp->y = R * cos( coord->d ); 215 216 } else 217 if ( projection->type == PS_PROJ_CAR ) { 218 tmp->x = coord->d; 219 tmp->y = coord->r; 220 221 } else 222 if ( projection->type == PS_PROJ_MER ) { 223 tmp->x = coord->d; 224 tmp->y = log( tan( 45.0 + ( 0.5 * coord->r ) ) ) * 180.0 / M_PI; 225 226 } else 227 if ( projection->type == PS_PROJ_AIT ) { 228 alpha = 1.0 / ( ( 180.0 / M_PI ) * 229 sqrt( 1.0 + ( cos( coord->r ) * cos( 0.5 * coord->d ) * 0.5 ) ) ); 230 231 tmp->x = 2.0 * alpha * cos( coord->r ) * sin( 0.5 * coord->d ); 232 tmp->y = alpha * sin( coord->d ); 233 234 } else 235 if ( projection->type == PS_PROJ_PAR ) { 236 psAbort( __func__, "The projection type PS_PROJ_PAR is undefined.\n" ); 237 238 } else 239 if ( projection->type == PS_PROJ_GLS ) { 240 psAbort( __func__, "The projection type PS_PROJ_GLS is undefined.\n" ); 241 } 242 243 return ( tmp ); 184 psPlane *tmp = (psPlane *) psAlloc(sizeof(psPlane)); 185 186 if (projection->type == PS_PROJ_TAN) { 187 R = cot(coord->r) * (180.0 / M_PI); 188 tmp->x = R * sin(coord->d); 189 tmp->y = R * cos(coord->d); 190 191 } else if (projection->type == PS_PROJ_SIN) { 192 R = cos(coord->r) * (180.0 / M_PI); 193 tmp->x = R * sin(coord->d); 194 tmp->y = R * cos(coord->d); 195 196 } else if (projection->type == PS_PROJ_CAR) { 197 tmp->x = coord->d; 198 tmp->y = coord->r; 199 200 } else if (projection->type == PS_PROJ_MER) { 201 tmp->x = coord->d; 202 tmp->y = log(tan(45.0 + (0.5 * coord->r))) * 180.0 / M_PI; 203 204 } else if (projection->type == PS_PROJ_AIT) { 205 alpha = 1.0 / ((180.0 / M_PI) * sqrt(1.0 + (cos(coord->r) * cos(0.5 * coord->d) * 0.5))); 206 207 tmp->x = 2.0 * alpha * cos(coord->r) * sin(0.5 * coord->d); 208 tmp->y = alpha * sin(coord->d); 209 210 } else if (projection->type == PS_PROJ_PAR) { 211 psAbort(__func__, "The projection type PS_PROJ_PAR is undefined.\n"); 212 213 } else if (projection->type == PS_PROJ_GLS) { 214 psAbort(__func__, "The projection type PS_PROJ_GLS is undefined.\n"); 215 } 216 217 return (tmp); 244 218 } 245 219 246 220 // XXX: Waiting for the definition of the PS_PROJ_PAR projection. 247 221 // XXX: Waiting for the definition of the PS_PROJ_GLS projection. 248 psSphere *psDeproject( const psPlane *coord, 249 const psProjection *projection ) 222 psSphere *psDeproject(const psPlane * coord, const psProjection * projection) 250 223 { 251 224 float R = 0.0; … … 253 226 float chu1 = 0.0; 254 227 float chu2 = 0.0; 255 psSphere *tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 256 257 if ( projection->type == PS_PROJ_TAN ) { 258 R = sqrt( ( coord->x * coord->x ) + ( coord->y * coord->y ) ); 259 tmp->d = arg( -coord->y, coord->x ); 260 tmp->r = atan( 180.0 / ( R * M_PI ) ); 261 262 } else 263 if ( projection->type == PS_PROJ_SIN ) { 264 R = sqrt( ( coord->x * coord->x ) + ( coord->y * coord->y ) ); 265 tmp->d = arg( -coord->y, coord->x ); 266 tmp->r = acos( ( R * M_PI ) / 180.0 ); 267 268 } else 269 if ( projection->type == PS_PROJ_CAR ) { 270 tmp->d = coord->x; 271 tmp->r = coord->y; 272 273 } else 274 if ( projection->type == PS_PROJ_MER ) { 275 tmp->d = coord->x; 276 tmp->r = ( 2.0 * atan( exp( ( coord->y * M_PI / 180.0 ) ) ) ) - 180.0; 277 278 } else 279 if ( projection->type == PS_PROJ_AIT ) { 280 chu1 = ( coord->x * M_PI ) / 720.0; 281 chu1 *= chu1; 282 chu2 = ( coord->y * M_PI ) / 360.0; 283 chu2 *= chu2; 284 chu = sqrt( 1.0 - chu1 - chu2 ); 285 tmp->d = 2.0 * arg( ( 2.0 * chu * chu ) - 1.0, 286 ( coord->x * chu * M_PI ) / 360.0 ); 287 tmp->r = asin( ( coord->y * chu * M_PI ) / 180.0 ); 288 289 } else 290 if ( projection->type == PS_PROJ_PAR ) { 291 psAbort( __func__, "The projection type PS_PROJ_PAR is undefined.\n" ); 292 293 } else 294 if ( projection->type == PS_PROJ_GLS ) { 295 psAbort( __func__, "The projection type PS_PROJ_GLG is undefined.\n" ); 296 } 297 298 return ( tmp ); 228 psSphere *tmp = (psSphere *) psAlloc(sizeof(psSphere)); 229 230 if (projection->type == PS_PROJ_TAN) { 231 R = sqrt((coord->x * coord->x) + (coord->y * coord->y)); 232 tmp->d = arg(-coord->y, coord->x); 233 tmp->r = atan(180.0 / (R * M_PI)); 234 235 } else if (projection->type == PS_PROJ_SIN) { 236 R = sqrt((coord->x * coord->x) + (coord->y * coord->y)); 237 tmp->d = arg(-coord->y, coord->x); 238 tmp->r = acos((R * M_PI) / 180.0); 239 240 } else if (projection->type == PS_PROJ_CAR) { 241 tmp->d = coord->x; 242 tmp->r = coord->y; 243 244 } else if (projection->type == PS_PROJ_MER) { 245 tmp->d = coord->x; 246 tmp->r = (2.0 * atan(exp((coord->y * M_PI / 180.0)))) - 180.0; 247 248 } else if (projection->type == PS_PROJ_AIT) { 249 chu1 = (coord->x * M_PI) / 720.0; 250 chu1 *= chu1; 251 chu2 = (coord->y * M_PI) / 360.0; 252 chu2 *= chu2; 253 chu = sqrt(1.0 - chu1 - chu2); 254 tmp->d = 2.0 * arg((2.0 * chu * chu) - 1.0, (coord->x * chu * M_PI) / 360.0); 255 tmp->r = asin((coord->y * chu * M_PI) / 180.0); 256 257 } else if (projection->type == PS_PROJ_PAR) { 258 psAbort(__func__, "The projection type PS_PROJ_PAR is undefined.\n"); 259 260 } else if (projection->type == PS_PROJ_GLS) { 261 psAbort(__func__, "The projection type PS_PROJ_GLG is undefined.\n"); 262 } 263 264 return (tmp); 299 265 } 300 266 301 267 // XXX: Do I need to check for unacceptable transformation parameters? 302 268 // Maybe, if the points are on the North/South Pole, etc? 303 psSphere *psSphereGetOffset( const psSphere *restrict position1, 304 const psSphere *restrict position2, 305 psSphereOffsetMode mode, 306 psSphereOffsetUnit unit ) 307 { 308 // psPlane *lin; 269 psSphere *psSphereGetOffset(const psSphere * restrict position1, 270 const psSphere * restrict position2, 271 psSphereOffsetMode mode, psSphereOffsetUnit unit) 272 { 273 // psPlane *lin; 309 274 psProjection proj; 310 275 psSphere *tmp; … … 312 277 double tmpD = 0.0; 313 278 314 if ( mode == PS_LINEAR) {279 if (mode == PS_LINEAR) { 315 280 // XXX: I have no idea how to construct this. Maybe project both 316 281 // sperical positions onto the plane, set the origin at one of the … … 318 283 319 284 // XXX: Do I need to somehow scale this projection? 320 // project position1? Will it project to (0.0, 0.0)?285 // project position1? Will it project to (0.0, 0.0)? 321 286 proj.R = position1->r; 322 287 proj.D = position1->d; … … 325 290 proj.type = PS_PROJ_TAN; 326 291 327 // lin = psProject(position2, proj);328 // tmp = psDeproject(lin, proj);292 // lin = psProject(position2, proj); 293 // tmp = psDeproject(lin, proj); 329 294 330 295 // XXX: Do we need to convert units in tmp? 331 return ( tmp ); 332 } else 333 if ( mode == PS_SPHERICAL ) { 334 tmpR = position2->r - position1->r; 335 tmpD = position2->d - position1->d; 336 337 if ( unit == PS_ARCSEC ) { 338 tmpR = ( tmpR * 180.0 * 60.0 * 60.0 ) / M_PI; 339 tmpD = ( tmpR * 180.0 * 60.0 * 60.0 ) / M_PI; 340 } else 341 if ( unit == PS_ARCMIN ) { 342 tmpR = ( tmpR * 180.0 * 60.0 ) / M_PI; 343 tmpD = ( tmpR * 180.0 * 60.0 ) / M_PI; 344 } else 345 if ( unit == PS_DEGREE ) { 346 tmpR = ( tmpR * 180.0 ) / M_PI; 347 tmpD = ( tmpR * 180.0 ) / M_PI; 348 } else 349 if ( unit == PS_RADIAN ) {} 350 else { 351 psAbort( __func__, "Unknown offset unit: 0x%x\n", unit ); 352 } 353 354 tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 355 tmp->r = tmpR; 356 tmp->d = tmpD; 357 tmp->rErr = 0.0; 358 tmp->dErr = 0.0; 359 // XXX: Do we need to wrap these to an acceptable range? 360 return ( tmp ); 296 return (tmp); 297 } else if (mode == PS_SPHERICAL) { 298 tmpR = position2->r - position1->r; 299 tmpD = position2->d - position1->d; 300 301 if (unit == PS_ARCSEC) { 302 tmpR = (tmpR * 180.0 * 60.0 * 60.0) / M_PI; 303 tmpD = (tmpR * 180.0 * 60.0 * 60.0) / M_PI; 304 } else if (unit == PS_ARCMIN) { 305 tmpR = (tmpR * 180.0 * 60.0) / M_PI; 306 tmpD = (tmpR * 180.0 * 60.0) / M_PI; 307 } else if (unit == PS_DEGREE) { 308 tmpR = (tmpR * 180.0) / M_PI; 309 tmpD = (tmpR * 180.0) / M_PI; 310 } else if (unit == PS_RADIAN) {} 311 else { 312 psAbort(__func__, "Unknown offset unit: 0x%x\n", unit); 361 313 } 362 psAbort( __func__, "Unrecognized offset mode\n" ); 363 return ( NULL ); 364 } 365 314 315 tmp = (psSphere *) psAlloc(sizeof(psSphere)); 316 tmp->r = tmpR; 317 tmp->d = tmpD; 318 tmp->rErr = 0.0; 319 tmp->dErr = 0.0; 320 // XXX: Do we need to wrap these to an acceptable range? 321 return (tmp); 322 } 323 psAbort(__func__, "Unrecognized offset mode\n"); 324 return (NULL); 325 } 366 326 367 327 // XXX: Do I need to check for unacceptable transformation parameters? 368 328 // Maybe, if the points are on the North/South Pole, etc? 369 329 // XXX: I copied the algorithm from the ADD exactly. 370 psSphere *psSphereSetOffset( const psSphere *restrict position, 371 const psSphere *restrict offset, 372 psSphereOffsetMode mode, 373 psSphereOffsetUnit unit ) 330 psSphere *psSphereSetOffset(const psSphere * restrict position, 331 const psSphere * restrict offset, 332 psSphereOffsetMode mode, psSphereOffsetUnit unit) 374 333 { 375 334 psPlane lin; … … 379 338 double tmpD = 0.0; 380 339 381 if ( mode == PS_LINEAR) {340 if (mode == PS_LINEAR) { 382 341 proj.R = position->r; 383 342 proj.D = position->d; … … 389 348 lin.y = offset->d; 390 349 391 tmp = psDeproject( &lin, &proj ); 392 return ( tmp ); 393 394 } else 395 if ( mode == PS_SPHERICAL ) { 396 if ( unit == PS_ARCSEC ) { 397 tmpR = ( M_PI * offset->r ) / ( 180.0 * 60.0 * 60.0 ); 398 tmpD = ( M_PI * offset->d ) / ( 180.0 * 60.0 * 60.0 ); 399 } else 400 if ( unit == PS_ARCMIN ) { 401 tmpR = ( M_PI * offset->r ) / ( 180.0 * 60.0 ); 402 tmpD = ( M_PI * offset->d ) / ( 180.0 * 60.0 ); 403 } else 404 if ( unit == PS_DEGREE ) { 405 tmpR = ( M_PI * offset->r ) / ( 180.0 ); 406 tmpD = ( M_PI * offset->d ) / ( 180.0 ); 407 } else 408 if ( unit == PS_RADIAN ) { 409 tmpR = offset->r; 410 tmpD = offset->d; 411 } else { 412 psAbort( __func__, "Unknown offset unit: 0x%x\n", unit ); 413 } 414 415 tmp = ( psSphere * ) psAlloc( sizeof( psSphere ) ); 416 tmp->r = position->r + tmpR; 417 tmp->r = position->d + tmpD; 418 tmp->rErr = 0.0; 419 tmp->dErr = 0.0; 420 421 // XXX: wrap tmp->r and tmp->d to the allowed range (-PI to PI) 422 // and (0 to 2*PI). 423 return ( tmp ); 350 tmp = psDeproject(&lin, &proj); 351 return (tmp); 352 353 } else if (mode == PS_SPHERICAL) { 354 if (unit == PS_ARCSEC) { 355 tmpR = (M_PI * offset->r) / (180.0 * 60.0 * 60.0); 356 tmpD = (M_PI * offset->d) / (180.0 * 60.0 * 60.0); 357 } else if (unit == PS_ARCMIN) { 358 tmpR = (M_PI * offset->r) / (180.0 * 60.0); 359 tmpD = (M_PI * offset->d) / (180.0 * 60.0); 360 } else if (unit == PS_DEGREE) { 361 tmpR = (M_PI * offset->r) / (180.0); 362 tmpD = (M_PI * offset->d) / (180.0); 363 } else if (unit == PS_RADIAN) { 364 tmpR = offset->r; 365 tmpD = offset->d; 366 } else { 367 psAbort(__func__, "Unknown offset unit: 0x%x\n", unit); 424 368 } 425 psAbort( __func__, "Unrecognized offset mode\n" ); 426 return ( NULL ); 427 } 369 370 tmp = (psSphere *) psAlloc(sizeof(psSphere)); 371 tmp->r = position->r + tmpR; 372 tmp->r = position->d + tmpD; 373 tmp->rErr = 0.0; 374 tmp->dErr = 0.0; 375 376 // XXX: wrap tmp->r and tmp->d to the allowed range (-PI to PI) 377 // and (0 to 2*PI). 378 return (tmp); 379 } 380 psAbort(__func__, "Unrecognized offset mode\n"); 381 return (NULL); 382 } -
trunk/psLib/src/astronomy/psCoord.h
r1393 r1407 1 1 2 /** @file psCoord.h 2 3 * … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 5 19:38:51$13 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 18 # ifndef PS_COORD_H19 # define PS_COORD_H20 21 # include "psType.h"22 # include "psImage.h"23 # include "psArray.h"24 # include "psList.h"25 # include "psFunctions.h"26 # include "psTime.h"19 #ifndef PS_COORD_H 20 # define PS_COORD_H 21 22 # include "psType.h" 23 # include "psImage.h" 24 # include "psArray.h" 25 # include "psList.h" 26 # include "psFunctions.h" 27 # include "psTime.h" 27 28 28 29 /// @addtogroup CoordinateTransform … … 38 39 typedef struct 39 40 { 40 double x; ///< x position41 double y; ///< y position42 double xErr; ///< Error in x position43 double yErr; ///< Error in y position41 double x; // /< x position 42 double y; // /< y position 43 double xErr; // /< Error in x position 44 double yErr; // /< Error in y position 44 45 } 45 46 psPlane; … … 54 55 typedef struct 55 56 { 56 double r; ///< RA57 double d; ///< Dec58 double rErr; ///< Error in RA59 double dErr; ///< Error in Dec57 double r; // /< RA 58 double d; // /< Dec 59 double rErr; // /< Error in RA 60 double dErr; // /< Error in Dec 60 61 } 61 62 psSphere; … … 71 72 typedef struct 72 73 { 73 psDPolynomial2D *x; ///< 2D polynomial transform of X coordinates74 psDPolynomial2D *y; ///< 2D polynomial transform of Y coordinates74 psDPolynomial2D *x; // /< 2D polynomial transform of X coordinates 75 psDPolynomial2D *y; // /< 2D polynomial transform of Y coordinates 75 76 } 76 77 psPlaneTransform; … … 90 91 typedef struct 91 92 { 92 psDPolynomial4D *x; ///< 4D polynomial transform of X coordinates93 psDPolynomial4D *y; ///< 4D polynomial transform of Y coordinates93 psDPolynomial4D *x; // /< 4D polynomial transform of X coordinates 94 psDPolynomial4D *y; // /< 4D polynomial transform of Y coordinates 94 95 } 95 96 psPlaneDistort; … … 107 108 typedef struct 108 109 { 109 double sinPhi; ///< sin of North Pole lattitude110 double cosPhi; ///< cos of North Pole lattitude111 double Xo; ///< First PT of Ares lon112 double xo; ///< First PT of Ares equiv lon110 double sinPhi; // /< sin of North Pole lattitude 111 double cosPhi; // /< cos of North Pole lattitude 112 double Xo; // /< First PT of Ares lon 113 double xo; // /< First PT of Ares equiv lon 113 114 } 114 115 psSphereTransform; … … 120 121 */ 121 122 typedef enum { 122 PS_PROJ_TAN, ///< Tangent projection123 PS_PROJ_SIN, ///< Sine projection124 PS_PROJ_AIT, ///< Aitoff projection125 PS_PROJ_PAR, ///< Par projection126 PS_PROJ_GLS, ///< GLS projection127 PS_PROJ_CAR, ///< CAR projection128 PS_PROJ_MER, ///< MER projection129 PS_PROJ_NTYPE ///< Number of types; must be last.123 PS_PROJ_TAN, // /< Tangent projection 124 PS_PROJ_SIN, // /< Sine projection 125 PS_PROJ_AIT, // /< Aitoff projection 126 PS_PROJ_PAR, // /< Par projection 127 PS_PROJ_GLS, // /< GLS projection 128 PS_PROJ_CAR, // /< CAR projection 129 PS_PROJ_MER, // /< MER projection 130 PS_PROJ_NTYPE // /< Number of types; must be last. 130 131 } psProjectionType; 131 132 … … 137 138 typedef struct 138 139 { 139 double R; ///< Coordinates of projection center140 double D; ///< Coordinates of projection center141 double Xs; ///< plate-scale in X direction142 double Ys; ///< plate-scale in Y direction143 psProjectionType type; ///< Projection type140 double R; // /< Coordinates of projection center 141 double D; // /< Coordinates of projection center 142 double Xs; // /< plate-scale in X direction 143 double Ys; // /< plate-scale in Y direction 144 psProjectionType type; // /< Projection type 144 145 } 145 146 psProjection; … … 151 152 */ 152 153 typedef enum { 153 PS_SPHERICAL, ///< offset corresponds to an angular offset154 PS_LINEAR ///< offset corresponds to a linear offset154 PS_SPHERICAL, // /< offset corresponds to an angular offset 155 PS_LINEAR // /< offset corresponds to a linear offset 155 156 } psSphereOffsetMode; 156 157 … … 161 162 */ 162 163 typedef enum { 163 PS_ARCSEC, ///< Arcseconds164 PS_ARCMIN, ///< Arcminutes165 PS_DEGREE, ///< Degrees166 PS_RADIAN ///< Radians164 PS_ARCSEC, // /< Arcseconds 165 PS_ARCMIN, // /< Arcminutes 166 PS_DEGREE, // /< Degrees 167 PS_RADIAN // /< Radians 167 168 } psSphereOffsetUnit; 168 169 … … 170 171 * 171 172 */ 172 psPlane *psPlaneTransformApply( 173 psPlane *out, ///< a psPlane to recycle. If NULL, a new one is generated. 174 const psPlaneTransform *transform, ///< the transform to apply 175 const psPlane *coords ///< the coordinate to apply the transform above. 176 ); 173 psPlane *psPlaneTransformApply(psPlane * out, // /< a psPlane to recycle. If NULL, a new one is generated. 174 const psPlaneTransform * transform, // /< the transform to apply 175 const psPlane * coords // /< the coordinate to apply the transform above. 176 ); 177 177 178 178 /** Applies the psPlaneDistort transform to a specified coordinate 179 179 * 180 180 */ 181 psPlane *psPlaneDistortApply( 182 psPlane *out, ///< a psPlane to recycle. If NULL, a new one is generated. 183 const psPlaneDistort *transform, ///< the transform to apply 184 const psPlane *coords, ///< the coordinate to apply the transform above. 185 float term3, ///< third term -- maybe magnitude 186 float term4 ///< forth term -- maybe color 187 ); 181 psPlane *psPlaneDistortApply(psPlane * out, // /< a psPlane to recycle. If NULL, a new one is generated. 182 const psPlaneDistort * transform, // /< the transform to apply 183 const psPlane * coords, // /< the coordinate to apply the transform above. 184 float term3, // /< third term -- maybe magnitude 185 float term4 // /< forth term -- maybe color 186 ); 188 187 189 188 /** Allocator for psSphereTransform 190 189 * 191 190 */ 192 psSphereTransform *psSphereTransformAlloc( 193 double NPlat, ///< north pole latitude 194 double Xo, ///< First PT of Ares lon 195 double xo ///< First PT of Ares equiv lon 196 ); 197 191 psSphereTransform *psSphereTransformAlloc(double NPlat, // /< north pole latitude 192 double Xo, // /< First PT of Ares lon 193 double xo // /< First PT of Ares equiv lon 194 ); 198 195 199 196 /** Applies the psSphereTransform transform for a specified coordinate 200 197 * 201 198 */ 202 psSphere *psSphereTransformApply( 203 psSphere *out, ///< a psSphere to recycle. If NULL, a new one is generated. 204 const psSphereTransform *transform,///< the transform to apply 205 const psSphere *coord ///< the coordinate to apply the transform above.x 206 ); 207 208 psSphereTransform *psSphereTransformICRStoEcliptic( 209 psTime time 210 ); 211 212 psSphereTransform *psSphereTransformEcliptictoICRS( 213 psTime time 214 ); 215 216 psSphereTransform *psSphereTransformICRStoGalatic( void ); 217 218 psSphereTransform *psSphereTransformGalatictoICRS( void ); 219 220 psPlane *psProject( 221 const psSphere *coord, 222 const psProjection *projection 223 ); 224 225 psSphere *psDeproject( 226 const psPlane *coord, 227 const psProjection *projection 228 ); 229 230 psSphere *psSphereGetOffset( 231 const psSphere *restrict position1, 232 const psSphere *restrict position2, 233 psSphereOffsetMode mode, 234 psSphereOffsetUnit unit 235 ); 236 237 psSphere *psSphereSetOffset( 238 const psSphere *restrict position, 239 const psSphere *restrict offset, 240 psSphereOffsetMode mode, 241 psSphereOffsetUnit unit 242 ); 199 psSphere *psSphereTransformApply(psSphere * out, // /< a psSphere to recycle. If NULL, a new one is 200 // generated. 201 const psSphereTransform * transform, // /< the transform to apply 202 const psSphere * coord // /< the coordinate to apply the transform above.x 203 ); 204 205 psSphereTransform *psSphereTransformICRStoEcliptic(psTime time); 206 207 psSphereTransform *psSphereTransformEcliptictoICRS(psTime time); 208 209 psSphereTransform *psSphereTransformICRStoGalatic(void); 210 211 psSphereTransform *psSphereTransformGalatictoICRS(void); 212 213 psPlane *psProject(const psSphere * coord, const psProjection * projection); 214 215 psSphere *psDeproject(const psPlane * coord, const psProjection * projection); 216 217 psSphere *psSphereGetOffset(const psSphere * restrict position1, 218 const psSphere * restrict position2, 219 psSphereOffsetMode mode, psSphereOffsetUnit unit); 220 221 psSphere *psSphereSetOffset(const psSphere * restrict position, 222 const psSphere * restrict offset, 223 psSphereOffsetMode mode, psSphereOffsetUnit unit); 243 224 244 225 /// @} -
trunk/psLib/src/astronomy/psMetadata.c
r1406 r1407 1 1 2 /** @file psMetadata.c 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 #include<stdio.h> … … 34 37 #include "psString.h" 35 38 36 37 39 /******************************************************************************/ 40 38 41 /* DEFINE STATEMENTS */ 42 39 43 /******************************************************************************/ 40 44 … … 56 60 57 61 /******************************************************************************/ 62 58 63 /* TYPE DEFINITIONS */ 64 59 65 /******************************************************************************/ 60 66 … … 62 68 63 69 /*****************************************************************************/ 70 64 71 /* GLOBAL VARIABLES */ 72 65 73 /*****************************************************************************/ 66 74 … … 68 76 69 77 /*****************************************************************************/ 78 70 79 /* FILE STATIC VARIABLES */ 80 71 81 /*****************************************************************************/ 72 82 … … 74 84 75 85 /*****************************************************************************/ 86 76 87 /* FUNCTION IMPLEMENTATION - LOCAL */ 77 /*****************************************************************************/ 78 static void metadataItemFree( psMetadataItem *metadataItem ) 88 89 /*****************************************************************************/ 90 static void metadataItemFree(psMetadataItem * metadataItem) 79 91 { 80 92 psMetadataType type; … … 82 94 type = metadataItem->type; 83 95 84 if (metadataItem == NULL) {85 return ;86 } 87 88 psFree( metadataItem->name);89 psFree( metadataItem->comment);90 psFree( metadataItem->items);91 92 if (type == PS_META_STR ||96 if (metadataItem == NULL) { 97 return; 98 } 99 100 psFree(metadataItem->name); 101 psFree(metadataItem->comment); 102 psFree(metadataItem->items); 103 104 if (type == PS_META_STR || 93 105 type == PS_META_IMG || 94 type == PS_META_JPEG || 95 type == PS_META_PNG || 96 type == PS_META_ASTROM || 97 type == PS_META_UNKNOWN) { 98 psFree( metadataItem->data.V ); 99 } 100 } 101 102 static void metadataFree( psMetadata *metadata ) 103 { 104 if(metadata == NULL) { 105 return ; 106 } 107 psFree( metadata->list ); 108 psFree( metadata->table ); 109 } 110 111 /*****************************************************************************/ 106 type == PS_META_JPEG || type == PS_META_PNG || type == PS_META_ASTROM || type == PS_META_UNKNOWN) { 107 psFree(metadataItem->data.V); 108 } 109 } 110 111 static void metadataFree(psMetadata * metadata) 112 { 113 if (metadata == NULL) { 114 return; 115 } 116 psFree(metadata->list); 117 psFree(metadata->table); 118 } 119 120 /*****************************************************************************/ 121 112 122 /* FUNCTION IMPLEMENTATION - PUBLIC */ 113 /*****************************************************************************/ 114 115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... ) 123 124 /*****************************************************************************/ 125 126 psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...) 116 127 { 117 128 va_list argPtr; … … 119 130 120 131 // Get the variable list parameters to pass to allocation function 121 va_start( argPtr, comment);132 va_start(argPtr, comment); 122 133 123 134 // Call metadata item allocation 124 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);135 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 125 136 126 137 // Clean up stack after variable arguement has been used 127 va_end( argPtr);138 va_end(argPtr); 128 139 129 140 return metadataItem; 130 141 } 131 142 132 psMetadataItem *psMetadataItemAllocV( const char *name, psMetadataType type, const char *comment, va_list argPtr )133 { 134 psMetadataItem * metadataItem = NULL; 135 136 if(name == NULL) { 137 psError( __func__, "Null value for name not allowed" );138 return NULL;139 }140 143 psMetadataItem *psMetadataItemAllocV(const char *name, psMetadataType type, const char *comment, 144 va_list argPtr) 145 { 146 psMetadataItem *metadataItem = NULL; 147 148 if (name == NULL) { 149 psError(__func__, "Null value for name not allowed"); 150 return NULL; 151 } 141 152 // Allocate metadata item 142 metadataItem = ( psMetadataItem * ) psAlloc( sizeof( psMetadataItem ) ); 143 if(metadataItem == NULL) { 144 psAbort( __func__, "Failed to allocate memory" ); 145 } 146 153 metadataItem = (psMetadataItem *) psAlloc(sizeof(psMetadataItem)); 154 if (metadataItem == NULL) { 155 psAbort(__func__, "Failed to allocate memory"); 156 } 147 157 // Set deallocator 148 p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree);158 p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree); 149 159 150 160 // Allocate and set metadata item comment 151 metadataItem->comment = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);152 if (comment == NULL) {161 metadataItem->comment = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 162 if (comment == NULL) { 153 163 // Per SDRS, null isn't allowed, must use "" instead 154 strncpy( metadataItem->comment, "", MAX_STRING_LENGTH);164 strncpy(metadataItem->comment, "", MAX_STRING_LENGTH); 155 165 } else { 156 strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH);166 strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH); 157 167 } 158 168 159 169 // Set metadata item unique id 160 *( int* ) ( &metadataItem->id) = ++metadataId;170 *(int *)(&metadataItem->id) = ++metadataId; 161 171 162 172 // Set metadata item type … … 164 174 165 175 // Set metadata item value 166 switch (type) {176 switch (type) { 167 177 case PS_META_BOOL: 168 metadataItem->data.B = ( bool ) va_arg( argPtr, int ); 178 metadataItem->data.B = (bool) va_arg(argPtr, int); 179 169 180 break; 170 181 case PS_META_S32: 171 metadataItem->data.S32 = va_arg( argPtr, psS32);182 metadataItem->data.S32 = va_arg(argPtr, psS32); 172 183 break; 173 184 case PS_META_F32: 174 metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64);185 metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64); 175 186 break; 176 187 case PS_META_F64: 177 metadataItem->data.F64 = va_arg( argPtr, psF64);188 metadataItem->data.F64 = va_arg(argPtr, psF64); 178 189 break; 179 190 case PS_META_STR: 180 metadataItem->data.V = psStringNCopy( va_arg( argPtr, char* ), MAX_STRING_LENGTH ); 191 metadataItem->data.V = psStringNCopy(va_arg(argPtr, char *), MAX_STRING_LENGTH); 192 181 193 break; 182 194 case PS_META_IMG: … … 186 198 case PS_META_UNKNOWN: 187 199 default: 188 psError( __func__, "Invalid psMetadataType: %d", type);200 psError(__func__, "Invalid psMetadataType: %d", type); 189 201 } 190 202 191 203 // Allocate and set metadata item name 192 metadataItem->name = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);193 vsprintf( metadataItem->name, name, argPtr);204 metadataItem->name = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 205 vsprintf(metadataItem->name, name, argPtr); 194 206 195 207 // Allocate metadata items with same name. 196 metadataItem->items = psListAlloc( NULL);208 metadataItem->items = psListAlloc(NULL); 197 209 198 210 return metadataItem; 199 211 } 200 212 201 psMetadata *psMetadataAlloc( void)202 { 203 psList * list = NULL;213 psMetadata *psMetadataAlloc(void) 214 { 215 psList *list = NULL; 204 216 psHash *table = NULL; 205 217 psMetadata *metadata = NULL; 206 218 207 219 // Allocate metadata 208 metadata = ( psMetadata * ) psAlloc( sizeof( psMetadata ) ); 209 if(metadata == NULL) { 210 psAbort( __func__, "Failed to allocate metadata" ); 211 } 212 220 metadata = (psMetadata *) psAlloc(sizeof(psMetadata)); 221 if (metadata == NULL) { 222 psAbort(__func__, "Failed to allocate metadata"); 223 } 213 224 // Set deallocator 214 p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree);225 p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree); 215 226 216 227 // Allocate metadata's internal containers 217 list = ( psList * ) psListAlloc( NULL);218 if (list == NULL) {219 psAbort( __func__, "Failed to allocate list");220 } 221 222 table = ( psHash * ) psHashAlloc( 10);223 if (table == NULL) {224 psAbort( __func__, "Failed to allocate table");228 list = (psList *) psListAlloc(NULL); 229 if (list == NULL) { 230 psAbort(__func__, "Failed to allocate list"); 231 } 232 233 table = (psHash *) psHashAlloc(10); 234 if (table == NULL) { 235 psAbort(__func__, "Failed to allocate table"); 225 236 } 226 237 … … 231 242 } 232 243 233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem)234 { 235 char * key = NULL;244 bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem) 245 { 246 char *key = NULL; 236 247 psHash *mdTable = NULL; 237 248 psList *mdList = NULL; … … 239 250 psMetadataType type = PS_META_ITEM_SET; 240 251 241 if (md == NULL) {242 psError( __func__, "Null metadata collection not allowed");243 return false; 244 } 245 246 if (metadataItem == NULL) {247 psError( __func__, "Null metadata item not allowed");252 if (md == NULL) { 253 psError(__func__, "Null metadata collection not allowed"); 254 return false; 255 } 256 257 if (metadataItem == NULL) { 258 psError(__func__, "Null metadata item not allowed"); 248 259 return false; 249 260 } … … 252 263 253 264 mdTable = md->table; 254 if (mdTable == NULL) {255 psError( __func__, "Null metadata table not allowed");256 return false; 257 } 258 259 mdList = md->list; 260 if (mdList == NULL) {261 psError( __func__, "Null metadata list not allowed");265 if (mdTable == NULL) { 266 psError(__func__, "Null metadata table not allowed"); 267 return false; 268 } 269 270 mdList = md->list; 271 if (mdList == NULL) { 272 psError(__func__, "Null metadata list not allowed"); 262 273 return false; 263 274 } 264 275 265 276 key = metadataItem->name; 266 if(key == NULL) { 267 psError( __func__, "Null key item not allowed" ); 268 return false; 269 } 270 277 if (key == NULL) { 278 psError(__func__, "Null key item not allowed"); 279 return false; 280 } 271 281 // Check if key is already in table 272 value = ( psMetadataItem* ) psHashLookup( mdTable, key);273 if (value != NULL && type != PS_META_ITEM_SET) {282 value = (psMetadataItem *) psHashLookup(mdTable, key); 283 if (value != NULL && type != PS_META_ITEM_SET) { 274 284 275 285 // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so 276 286 // add the new metadata item to hash as a child of the existing metadata item folder node. 277 if(!psListAdd( value->items, metadataItem, where )) { 278 psError( __func__, "Couldn't add metadata item to items list. Name: %s", 279 metadataItem->name ); 287 if (!psListAdd(value->items, metadataItem, where)) { 288 psError(__func__, "Couldn't add metadata item to items list. Name: %s", metadataItem->name); 280 289 return false; 281 290 } 282 } else 283 if(value != NULL) { 284 285 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 286 // it will wipe out existing node. 287 psError( __func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 288 metadataItem->name ); 291 } else if (value != NULL) { 292 293 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 294 // it will wipe out existing node. 295 psError(__func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 296 metadataItem->name); 297 return false; 298 } else { 299 300 // Duplicate key not found. Add new metadata item to metadata collection's hash 301 if (!psHashAdd(mdTable, key, metadataItem)) { 302 psError(__func__, "Couldn't add metadata item to metadata collection table. Name: %s", 303 metadataItem->name); 289 304 return false; 290 } else { 291 292 // Duplicate key not found. Add new metadata item to metadata collection's hash 293 if(!psHashAdd( mdTable, key, metadataItem )) { 294 psError( __func__, "Couldn't add metadata item to metadata collection table. Name: %s", 295 metadataItem->name ); 296 return false; 297 } 298 } 305 } 306 } 299 307 300 308 // Add all items to metadata collection's list, even if they have the same metadata item names 301 if (!psListAdd( md->list, metadataItem, where)) {302 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",303 metadataItem->name);309 if (!psListAdd(md->list, metadataItem, where)) { 310 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 311 metadataItem->name); 304 312 return false; 305 313 } … … 308 316 } 309 317 310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,311 const char *comment, ...)318 bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type, 319 const char *comment, ...) 312 320 { 313 321 va_list argPtr; 314 322 psMetadataItem *metadataItem = NULL; 315 323 316 va_start( argPtr, comment);317 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);318 va_end( argPtr);319 320 if (!psMetadataAddItem( md, where, metadataItem)) {321 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",322 metadataItem->name);323 psFree( metadataItem);324 return false; 325 } 326 327 // Decrement reference count, since the metadata item is now in metadata collection and no longer neededhere328 psMemDecrRefCounter( metadataItem);324 va_start(argPtr, comment); 325 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 326 va_end(argPtr); 327 328 if (!psMetadataAddItem(md, where, metadataItem)) { 329 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 330 metadataItem->name); 331 psFree(metadataItem); 332 return false; 333 } 334 // Decrement reference count, since the metadata item is now in metadata collection and no longer needed 335 // here 336 psMemDecrRefCounter(metadataItem); 329 337 330 338 return true; 331 339 } 332 340 333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key)341 bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key) 334 342 { 335 343 int numChildren = 0; … … 340 348 341 349 mdList = md->list; 342 if (mdList == NULL) {343 psError( __func__, "Null metadata list not allowed");350 if (mdList == NULL) { 351 psError(__func__, "Null metadata list not allowed"); 344 352 return false; 345 353 } 346 354 347 355 mdTable = md->table; 348 if(mdTable == NULL) { 349 psError( __func__, "Null metadata table not allowed" ); 350 return false; 351 } 352 356 if (mdTable == NULL) { 357 psError(__func__, "Null metadata table not allowed"); 358 return false; 359 } 353 360 // Select removal by key or index 354 if (key != NULL) {361 if (key != NULL) { 355 362 356 363 // Remove by key name 357 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);358 if (entry == NULL) {359 psError( __func__, "Couldn't find metadata item remove. Name: %s", key);364 entry = (psMetadataItem *) psHashLookup(mdTable, key); 365 if (entry == NULL) { 366 psError(__func__, "Couldn't find metadata item remove. Name: %s", key); 360 367 return false; 361 368 } 362 369 363 370 numChildren = entry->items->size; 364 if (entry->type == PS_META_ITEM_SET && numChildren > 0) {371 if (entry->type == PS_META_ITEM_SET && numChildren > 0) { 365 372 366 373 // Table entry has children. Entry and children must be removed from metadata collection's list 367 psListSetIterator( mdList, PS_LIST_HEAD);368 entryChild = psListGetCurrent( mdList);369 while (entryChild != NULL) {370 if (!psListRemove( entry->items, entryChild, PS_LIST_UNKNOWN)) {371 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);374 psListSetIterator(mdList, PS_LIST_HEAD); 375 entryChild = psListGetCurrent(mdList); 376 while (entryChild != NULL) { 377 if (!psListRemove(entry->items, entryChild, PS_LIST_UNKNOWN)) { 378 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 372 379 return false; 373 380 } 374 entryChild = psListGetNext( entry->items);381 entryChild = psListGetNext(entry->items); 375 382 } 376 383 } 377 378 384 // Remove entry from metadata collection's list 379 if (!psListRemove( mdList, entry, PS_LIST_UNKNOWN)) {380 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);385 if (!psListRemove(mdList, entry, PS_LIST_UNKNOWN)) { 386 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 381 387 return false; 382 388 } 383 384 389 // Remove entry from metadata collection's table 385 if (!psHashRemove( mdTable, key)) {386 psError( __func__, "Couldn't remove metadata item from table. Name: %s", key);390 if (!psHashRemove(mdTable, key)) { 391 psError(__func__, "Couldn't remove metadata item from table. Name: %s", key); 387 392 return false; 388 393 } … … 390 395 391 396 // Remove by index 392 entry = psListGet( mdList, where);393 if (entry == NULL) {394 psError( __func__, "Couldn't find metadata item from list. Index: %d", where);397 entry = psListGet(mdList, where); 398 if (entry == NULL) { 399 psError(__func__, "Couldn't find metadata item from list. Index: %d", where); 395 400 return false; 396 401 } 397 402 398 403 key = entry->name; 399 if (key == NULL) {400 psError( __func__, "Null key name not allowed. Index: %d", where);404 if (key == NULL) { 405 psError(__func__, "Null key name not allowed. Index: %d", where); 401 406 return false; 402 407 } 403 404 408 // Use recursive remove, now that key is known 405 psMetadataRemove( md, PS_LIST_UNKNOWN, key);409 psMetadataRemove(md, PS_LIST_UNKNOWN, key); 406 410 } 407 411 … … 409 413 } 410 414 411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key)412 { 413 psHash * mdTable = NULL;415 psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key) 416 { 417 psHash *mdTable = NULL; 414 418 psMetadataItem *entry = NULL; 415 419 416 420 mdTable = md->table; 417 if (mdTable == NULL) {418 psError( __func__, "Null metadata table not allowed");419 return NULL; 420 } 421 422 if (key == NULL) {423 psError( __func__, "Null key name not allowed");424 return NULL; 425 } 426 427 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);428 if (entry == NULL) {429 psError( __func__, "Could not find metadata item with given key. Key: %s", key);421 if (mdTable == NULL) { 422 psError(__func__, "Null metadata table not allowed"); 423 return NULL; 424 } 425 426 if (key == NULL) { 427 psError(__func__, "Null key name not allowed"); 428 return NULL; 429 } 430 431 entry = (psMetadataItem *) psHashLookup(mdTable, key); 432 if (entry == NULL) { 433 psError(__func__, "Could not find metadata item with given key. Key: %s", key); 430 434 return NULL; 431 435 } … … 434 438 } 435 439 436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where)437 { 438 psList * mdList = NULL;440 psMetadataItem *psMetadataGet(psMetadata * restrict md, int where) 441 { 442 psList *mdList = NULL; 439 443 psMetadataItem *entry = NULL; 440 444 441 445 mdList = md->list; 442 if (mdList == NULL) {443 psError( __func__, "Null metadata list not allowed");444 return NULL; 445 } 446 447 entry = ( psMetadataItem* ) psListGet( mdList, where);448 if (entry == NULL) {449 psError( __func__, "Couldn't find metadata item with given index. Index: %d", where);446 if (mdList == NULL) { 447 psError(__func__, "Null metadata list not allowed"); 448 return NULL; 449 } 450 451 entry = (psMetadataItem *) psListGet(mdList, where); 452 if (entry == NULL) { 453 psError(__func__, "Couldn't find metadata item with given index. Index: %d", where); 450 454 return NULL; 451 455 } … … 454 458 } 455 459 456 bool psMetadataSetIterator( psMetadata *restrict md, int where)457 { 458 psList * mdList = NULL;459 460 mdList = md->list; 461 if (mdList == NULL) {462 psError( __func__, "Null metadata list not allowed");463 return false; 464 } 465 466 psListSetIterator( mdList, where);460 bool psMetadataSetIterator(psMetadata * restrict md, int where) 461 { 462 psList *mdList = NULL; 463 464 mdList = md->list; 465 if (mdList == NULL) { 466 psError(__func__, "Null metadata list not allowed"); 467 return false; 468 } 469 470 psListSetIterator(mdList, where); 467 471 468 472 return true; 469 473 } 470 474 471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which)472 { 473 psList * mdList = NULL;475 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which) 476 { 477 psList *mdList = NULL; 474 478 psMetadataItem *entry = NULL; 475 479 476 480 mdList = md->list; 477 if (mdList == NULL) {478 psError( __func__, "Null metadata list not allowed");479 return NULL; 480 } 481 482 mdList = md->list; 483 if (mdList == NULL) {484 psError( __func__, "Null metadata list not allowed");485 return NULL; 486 } 487 488 psListSetIterator( mdList, which);489 entry = psListGetCurrent( mdList);490 while (entry != NULL) {491 if (!strncmp( match, entry->name, strlen( match ))) {481 if (mdList == NULL) { 482 psError(__func__, "Null metadata list not allowed"); 483 return NULL; 484 } 485 486 mdList = md->list; 487 if (mdList == NULL) { 488 psError(__func__, "Null metadata list not allowed"); 489 return NULL; 490 } 491 492 psListSetIterator(mdList, which); 493 entry = psListGetCurrent(mdList); 494 while (entry != NULL) { 495 if (!strncmp(match, entry->name, strlen(match))) { 492 496 493 497 // Match found 494 498 return entry; 495 499 } 496 entry = psListGetNext( mdList);500 entry = psListGetNext(mdList); 497 501 } 498 502 499 503 // Match not found 500 if (entry == NULL) {501 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);504 if (entry == NULL) { 505 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 502 506 } 503 507 … … 505 509 } 506 510 507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which)508 { 509 psList * mdList = NULL;511 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which) 512 { 513 psList *mdList = NULL; 510 514 psMetadataItem *entry = NULL; 511 515 512 516 mdList = md->list; 513 if (mdList == NULL) {514 psError( __func__, "Null metadata list not allowed");515 return NULL; 516 } 517 518 mdList = md->list; 519 if (mdList == NULL) {520 psError( __func__, "Null metadata list not allowed");521 return NULL; 522 } 523 524 psListSetIterator( mdList, which);525 entry = psListGetCurrent( mdList);526 while (entry != NULL) {527 if (!strncmp( match, entry->name, strlen( match ))) {517 if (mdList == NULL) { 518 psError(__func__, "Null metadata list not allowed"); 519 return NULL; 520 } 521 522 mdList = md->list; 523 if (mdList == NULL) { 524 psError(__func__, "Null metadata list not allowed"); 525 return NULL; 526 } 527 528 psListSetIterator(mdList, which); 529 entry = psListGetCurrent(mdList); 530 while (entry != NULL) { 531 if (!strncmp(match, entry->name, strlen(match))) { 528 532 529 533 // Match found 530 534 return entry; 531 535 } 532 entry = psListGetPrevious( mdList);536 entry = psListGetPrevious(mdList); 533 537 } 534 538 535 539 // Match not found 536 if (entry == NULL) {537 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);540 if (entry == NULL) { 541 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 538 542 } 539 543 … … 541 545 } 542 546 543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem)547 void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem) 544 548 { 545 549 psMetadataType type; 546 550 547 if (fd == NULL) {548 psError( __func__, "Null file descriptor not allowed");549 return ;550 } 551 552 if (format == NULL) {553 psError( __func__, "Null format not allowed");554 return ;555 } 556 557 if (metadataItem == NULL) {558 psError( __func__, "Null metadata not allowed");559 return ;551 if (fd == NULL) { 552 psError(__func__, "Null file descriptor not allowed"); 553 return; 554 } 555 556 if (format == NULL) { 557 psError(__func__, "Null format not allowed"); 558 return; 559 } 560 561 if (metadataItem == NULL) { 562 psError(__func__, "Null metadata not allowed"); 563 return; 560 564 } 561 565 562 566 type = metadataItem->type; 563 567 564 switch (type) {568 switch (type) { 565 569 case PS_META_BOOL: 566 fprintf( fd, format, metadataItem->data.B);570 fprintf(fd, format, metadataItem->data.B); 567 571 break; 568 572 case PS_META_S32: 569 fprintf( fd, format, metadataItem->data.S32);573 fprintf(fd, format, metadataItem->data.S32); 570 574 break; 571 575 case PS_META_F32: 572 fprintf( fd, format, metadataItem->data.F32);576 fprintf(fd, format, metadataItem->data.F32); 573 577 break; 574 578 case PS_META_F64: 575 fprintf( fd, format, metadataItem->data.F64);579 fprintf(fd, format, metadataItem->data.F64); 576 580 break; 577 581 case PS_META_STR: 578 fprintf( fd, format, metadataItem->data.V);582 fprintf(fd, format, metadataItem->data.V); 579 583 break; 580 584 case PS_META_ITEM_SET: … … 585 589 case PS_META_UNKNOWN: 586 590 default: 587 psError( __func__, " Invalid psMetadataType to print: %d", type);588 } 589 } 590 591 psMetadata *psMetadataFReadHeader( psMetadata *output, char *extName, int extNum, fitsfile *fd)591 psError(__func__, " Invalid psMetadataType to print: %d", type); 592 } 593 } 594 595 psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd) 592 596 { 593 597 bool tempBool; 594 598 bool success; 595 599 char keyType; 596 char keyName[ FITS_LINE_SIZE];597 char keyValue[ FITS_LINE_SIZE];598 char keyComment[ FITS_LINE_SIZE];599 char fitsErr[ MAX_STRING_LENGTH];600 char keyName[FITS_LINE_SIZE]; 601 char keyValue[FITS_LINE_SIZE]; 602 char keyComment[FITS_LINE_SIZE]; 603 char fitsErr[MAX_STRING_LENGTH]; 600 604 int i; 601 605 int hduType = 0; … … 605 609 psMetadataType metadataItemType; 606 610 607 if(fd == NULL) { 608 psError( __func__, "Null FITS file descriptor not allowed" ); 609 return NULL; 610 } 611 612 if(extName == NULL && extNum == 0) { 613 psError( __func__, "Null extName and extNum = 0 not allowed" ); 614 return NULL; 615 } else 616 if(extName && extNum) { 617 psError( __func__, "Both extName and extNum arguments should not have non zero values." ); 618 return NULL; 619 } 620 611 if (fd == NULL) { 612 psError(__func__, "Null FITS file descriptor not allowed"); 613 return NULL; 614 } 615 616 if (extName == NULL && extNum == 0) { 617 psError(__func__, "Null extName and extNum = 0 not allowed"); 618 return NULL; 619 } else if (extName && extNum) { 620 psError(__func__, "Both extName and extNum arguments should not have non zero values."); 621 return NULL; 622 } 621 623 // Allocate metadata if user didn't 622 if (output == NULL) {624 if (output == NULL) { 623 625 output = psMetadataAlloc(); 624 626 } 625 626 627 // Move to user designated HDU number or HDU name in FITS file. HDU numbers starts at one. 627 if (extName != NULL) {628 if (fits_movnam_hdu( fd, ANY_HDU, extName, 0, &status) != 0) {628 if (extName != NULL) { 629 if (fits_movnam_hdu(fd, ANY_HDU, extName, 0, &status) != 0) { 629 630 FITS_ERROR("FITS error while locating header %s: %s", extName); 630 631 } 631 632 } else { 632 if (fits_movabs_hdu( fd, extNum, &hduType, &status) != 0) {633 if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) { 633 634 FITS_ERROR("FITS error while locating header %d: %s", extNum); 634 635 } … … 636 637 637 638 // Get number of key names 638 if (fits_get_hdrpos( fd, &numKeys, &keyNum, &status) != 0) {639 if (fits_get_hdrpos(fd, &numKeys, &keyNum, &status) != 0) { 639 640 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 640 641 } 641 642 642 // Get each key name. Keywords start at one. 643 for (i = 1; i <= numKeys; i++) {644 if (fits_read_keyn( fd, i, keyName, keyValue, keyComment, &status) != 0) {643 for (i = 1; i <= numKeys; i++) { 644 if (fits_read_keyn(fd, i, keyName, keyValue, keyComment, &status) != 0) { 645 645 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 646 646 } 647 if (fits_get_keytype( keyValue, &keyType, &status) != 0) {648 fits_get_errstatus( status, fitsErr);649 if (status != VALUE_UNDEFINED) {647 if (fits_get_keytype(keyValue, &keyType, &status) != 0) { 648 fits_get_errstatus(status, fitsErr); 649 if (status != VALUE_UNDEFINED) { 650 650 FITS_ERROR("FITS error while determining key %d type: %s", keyNum); 651 651 } else { 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and HISTORY 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and 653 // HISTORY 653 654 keyType = 'C'; 654 655 status = 0; … … 656 657 } 657 658 658 switch (keyType) {659 switch (keyType) { 659 660 case 'I': 660 661 metadataItemType = PS_META_S32; 661 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atoi( keyValue ) ); 662 success = 663 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 664 atoi(keyValue)); 662 665 break; 663 666 case 'F': 664 667 metadataItemType = PS_META_F64; 665 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atof( keyValue ) ); 668 success = 669 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 670 atof(keyValue)); 666 671 break; 667 672 case 'C': 668 673 metadataItemType = PS_META_STR; 669 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue ); 674 success = 675 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue); 670 676 break; 671 677 case 'L': 672 678 metadataItemType = PS_META_BOOL; 673 tempBool = ( keyValue[ 0 ] == 'T' ) ? 1 : 0; 674 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool ); 679 tempBool = (keyValue[0] == 'T') ? 1 : 0; 680 success = 681 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool); 675 682 break; 676 683 case 'U': 677 684 case 'X': 678 685 default: 679 psError( __func__, "Invalid psMetadataType: %c", keyType);686 psError(__func__, "Invalid psMetadataType: %c", keyType); 680 687 return output; 681 688 } 682 689 683 if (!success) {684 psError( __func__, "Failed to add metadata item. Name: %s", keyName);690 if (!success) { 691 psError(__func__, "Failed to add metadata item. Name: %s", keyName); 685 692 return output; 686 693 } -
trunk/psLib/src/astronomy/psMetadata.h
r1394 r1407 1 1 2 /** @file psMetadata.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 5 20:55:22$13 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 #ifndef PS_METADATA_H 18 # define PS_METADATA_H19 20 # include <stdarg.h>21 # include <stdio.h>22 # include <fitsio.h>23 24 # include "psHash.h"25 # include "psList.h"19 # define PS_METADATA_H 20 21 # include <stdarg.h> 22 # include <stdio.h> 23 # include <fitsio.h> 24 25 # include "psHash.h" 26 # include "psList.h" 26 27 27 28 /// @addtogroup Metadata … … 33 34 */ 34 35 typedef enum { 35 PS_META_ITEM_SET = 0, ///< Null. Metadata is in psMetadataItem.items36 PS_META_BOOL, ///< Boolean data.37 PS_META_S32, ///< Signed 32-bit integer data.38 PS_META_F32, ///< Single-precision float data.39 PS_META_F64, ///< Double-precision float data.40 PS_META_STR, ///< String data (Stored in as void *).41 PS_META_IMG, ///< Image data (Stored in as void *).42 PS_META_JPEG, ///< JPEG data (Stored in as void .43 PS_META_PNG, ///< PNG data (Stored in as void *).44 PS_META_ASTROM, ///< Astrometric coefficients (Stored in as void *).45 PS_META_UNKNOWN, ///< Other data (Stored in as void *).46 PS_META_NTYPE ///< Number of types. Must be last.36 PS_META_ITEM_SET = 0, // /< Null. Metadata is in psMetadataItem.items 37 PS_META_BOOL, // /< Boolean data. 38 PS_META_S32, // /< Signed 32-bit integer data. 39 PS_META_F32, // /< Single-precision float data. 40 PS_META_F64, // /< Double-precision float data. 41 PS_META_STR, // /< String data (Stored in as void *). 42 PS_META_IMG, // /< Image data (Stored in as void *). 43 PS_META_JPEG, // /< JPEG data (Stored in as void . 44 PS_META_PNG, // /< PNG data (Stored in as void *). 45 PS_META_ASTROM, // /< Astrometric coefficients (Stored in as void *). 46 PS_META_UNKNOWN, // /< Other data (Stored in as void *). 47 PS_META_NTYPE // /< Number of types. Must be last. 47 48 } psMetadataType; 48 49 … … 54 55 typedef struct psMetadataItem 55 56 { 56 const int id; ///< Unique ID for metadata item. 57 char *restrict name; ///< Name of metadata item. 58 psMetadataType type; ///< Type of metadata item. 59 union 60 { 57 const int id; // /< Unique ID for metadata item. 58 char *restrict name; // /< Name of metadata item. 59 psMetadataType type; // /< Type of metadata item. 60 union { 61 61 bool B; 62 psS32 S32; ///< Signed 32-bit integer data.63 psF32 F32; ///< Single-precision float data.64 psF64 F64; ///< Double-precision float data.65 psPTR V; ///< Pointer to other type of data.66 } data; ///< Union for data types.67 char *comment; ///< Optional comment ("", not NULL).68 psList *restrict items; ///< List of psMetadataItems with same name.62 psS32 S32; // /< Signed 32-bit integer data. 63 psF32 F32; // /< Single-precision float data. 64 psF64 F64; // /< Double-precision float data. 65 psPTR V; // /< Pointer to other type of data. 66 } data; // /< Union for data types. 67 char *comment; // /< Optional comment ("", not NULL). 68 psList *restrict items; // /< List of psMetadataItems with same name. 69 69 } 70 70 psMetadataItem; … … 78 78 typedef struct psMetadata 79 79 { 80 psList *restrict list;81 psHash *restrict table;80 psList *restrict list; 81 psHash *restrict table; 82 82 } 83 83 psMetadata; 84 84 85 86 85 /*****************************************************************************/ 86 87 87 /* FUNCTION PROTOTYPES */ 88 88 89 /*****************************************************************************/ 89 90 … … 101 102 * @return psMetadataItem*: Pointer metadata item. 102 103 */ 103 psMetadataItem *psMetadataItemAlloc( 104 const char *name, ///< Name of metadata item. 105 psMetadataType type, ///< Type of metadata item. 106 const char *comment, ///< Comment for metadata item. 107 ... ///< Arguments for name formatting and metadata item data. 108 ); 104 psMetadataItem *psMetadataItemAlloc(const char *name, // /< Name of metadata item. 105 psMetadataType type, // /< Type of metadata item. 106 const char *comment, // /< Comment for metadata item. 107 ... // /< Arguments for name formatting and metadata item data. 108 ); 109 109 110 110 /** Create a metadata item with va_list. … … 121 121 * @return psMetadataItem*: Pointer metadata item. 122 122 */ 123 psMetadataItem *psMetadataItemAllocV( 124 const char *name, ///< Name of metadata item.125 psMetadataType type, ///< Type ofmetadata item.126 const char *comment, ///< Comment for metadata item.127 va_list list ///< Arguments for name formatting and metadata itemdata.128 );123 psMetadataItem *psMetadataItemAllocV(const char *name, // /< Name of metadata item. 124 psMetadataType type, // /< Type of metadata item. 125 const char *comment, // /< Comment for metadata item. 126 va_list list // /< Arguments for name formatting and metadata item 127 // data. 128 ); 129 129 130 130 /** Create a metadata collection. … … 134 134 * @return psMetadata*: Pointer metadata. 135 135 */ 136 psMetadata *psMetadataAlloc( 137 void ///< Void. 138 ); 136 psMetadata *psMetadataAlloc(void // /< Void. 137 ); 139 138 140 139 /** Add existing metadata item to metadata collection. … … 144 143 * @return bool: True for success, false for failure. 145 144 */ 146 bool psMetadataAddItem( 147 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 148 int where, ///< Location to be added. 149 psMetadataItem *restrict item ///< Metadata item to be added. 150 ); 145 bool psMetadataAddItem(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 146 int where, // /< Location to be added. 147 psMetadataItem * restrict item // /< Metadata item to be added. 148 ); 151 149 152 150 /** Create and add a metadata item to metadata collection. … … 156 154 * @return bool: True for success, false for failure. 157 155 */ 158 bool psMetadataAdd( 159 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 160 int where, ///< Location to be added. 161 const char *name, ///< Name of metadata item. 162 psMetadataType type, ///< Type of metadata item. 163 const char *comment, ///< Comment for metadata item. 164 ... ///< Arguments for name formatting and metadata item data. 165 ); 156 bool psMetadataAdd(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 157 int where, // /< Location to be added. 158 const char *name, // /< Name of metadata item. 159 psMetadataType type, // /< Type of metadata item. 160 const char *comment, // /< Comment for metadata item. 161 ... // /< Arguments for name formatting and metadata item data. 162 ); 166 163 167 164 /** Remove an item from metadata collection. … … 174 171 * @return bool: True for success, false for failure. 175 172 */ 176 bool psMetadataRemove( 177 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 178 int where, ///< Location to be removed. 179 const char *restrict key ///< Name of metadata key. 180 ); 173 bool psMetadataRemove(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 174 int where, // /< Location to be removed. 175 const char *restrict key // /< Name of metadata key. 176 ); 181 177 182 178 /** Find an item in the metadata collection based on key name. … … 187 183 * @return psMetadataItem*: Pointer metadata item. 188 184 */ 189 psMetadataItem *psMetadataLookup( 190 psMetadata *restrict md, ///< Metadata collection to insert metadatitem.191 const char *restrict key ///< Name of metadata key.192 );185 psMetadataItem *psMetadataLookup(psMetadata * restrict md, // /< Metadata collection to insert metadat 186 // item. 187 const char *restrict key // /< Name of metadata key. 188 ); 193 189 194 190 /** Find an item in the metadata collection based on list index. … … 198 194 * @return psMetadataItem*: Pointer metadata item. 199 195 */ 200 psMetadataItem *psMetadataGet( 201 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 202 int where ///< Location to be retrieved. 203 ); 196 psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 197 int where // /< Location to be retrieved. 198 ); 204 199 205 200 /** Set or reset metadata iterator. … … 209 204 * @return void: void. 210 205 */ 211 bool psMetadataSetIterator( 212 psMetadata *restrict md, ///< Metadata collection to iterate. 213 int where ///< Location of iterator. 214 ); 206 bool psMetadataSetIterator(psMetadata * restrict md, // /< Metadata collection to iterate. 207 int where // /< Location of iterator. 208 ); 215 209 216 210 /** Get next metadata item. … … 220 214 * @return psMetadataItem*: Pointer metadata item. 221 215 */ 222 psMetadataItem *psMetadataGetNext( 223 psMetadata *restrict md, ///< Metadata collection to iterate. 224 const char *restrict match, ///< Beginning of key name. 225 int which ///< Iterator to be used. 226 ); 216 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, // /< Metadata collection to iterate. 217 const char *restrict match, // /< Beginning of key name. 218 int which // /< Iterator to be used. 219 ); 227 220 228 221 /** Get previous metadata item. … … 232 225 * @return psMetadataItem*: Pointer metadata item. 233 226 */ 234 psMetadataItem *psMetadataGetPrevious( 235 psMetadata *restrict md, ///< Metadata collection to iterate. 236 const char *restrict match, ///< Beginning of key name. 237 int which ///< Iterator to be used. 238 ); 227 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, // /< Metadata collection to iterate. 228 const char *restrict match, // /< Beginning of key name. 229 int which // /< Iterator to be used. 230 ); 239 231 240 232 /** Print metadata item to file. … … 248 240 * @return psMetadataItem*: Pointer metadata item. 249 241 */ 250 void psMetadataItemPrint( 251 FILE *fd, ///< Pointer to file to write metadata item. 252 const char *format, ///< Format to print metadata item. 253 const psMetadataItem *restrict metadataItem ///< Metadata item to print. 254 ); 242 void psMetadataItemPrint(FILE * fd, // /< Pointer to file to write metadata item. 243 const char *format, // /< Format to print metadata item. 244 const psMetadataItem * restrict metadataItem // /< Metadata item to print. 245 ); 255 246 256 247 /** Read metadata header. … … 261 252 * @return psMetadata*: Pointer metadata. 262 253 */ 263 psMetadata *psMetadataReadHeader( 264 psMetadata *output, ///< Resulting metadata from read. 265 char *extname, ///< File name extension string. 266 int extnum, ///< File name extension number. Starts at 1. 267 char *filename ///< Name of file to read. 268 ); 254 psMetadata *psMetadataReadHeader(psMetadata * output, // /< Resulting metadata from read. 255 char *extname, // /< File name extension string. 256 int extnum, // /< File name extension number. Starts at 1. 257 char *filename // /< Name of file to read. 258 ); 269 259 270 260 /** Read metadata header. … … 274 264 * @return psMetadata*: Pointer metadata. 275 265 */ 276 psMetadata *psMetadataFReadHeader( 277 psMetadata *output, ///< Resulting metadata from read.278 char *extName, ///< File name extension string.279 int extNum, ///< File name extension number.280 fitsfile *fd ///< Pointer to file to read.281 ); 266 psMetadata *psMetadataFReadHeader(psMetadata * output, // /< Resulting metadata from read. 267 char *extName, // /< File name extension string. 268 int extNum, // /< File name extension number. 269 fitsfile * fd // /< Pointer to file to read. 270 ); 271 282 272 /// @} 283 273 -
trunk/psLib/src/astronomy/psPhotometry.h
r1385 r1407 1 1 2 /** @file psPhotometry.h 2 3 * … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1. 4$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 4 23:37:39$12 * @version $Revision: 1.5 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 17 # ifndef PS_PHOTOMETRIC_H18 # define PS_PHOTOMETRIC_H18 #ifndef PS_PHOTOMETRIC_H 19 # define PS_PHOTOMETRIC_H 19 20 20 # include "psType.h"21 # include "psImage.h"22 # include "psArray.h"23 # include "psList.h"24 # include "psFunctions.h"21 # include "psType.h" 22 # include "psImage.h" 23 # include "psArray.h" 24 # include "psList.h" 25 # include "psFunctions.h" 25 26 26 27 /// @addtogroup Photometry … … 42 43 typedef struct 43 44 { 44 const int ID; ///< ID number for this photometric system45 const char *name; ///< Name of photometric system46 const char *camera; ///< Camera for photometric system47 const char *filter; ///< Filter used for photometric system48 const char *detector; ///< Detector used for photometric system45 const int ID; // /< ID number for this photometric system 46 const char *name; // /< Name of photometric system 47 const char *camera; // /< Camera for photometric system 48 const char *filter; // /< Filter used for photometric system 49 const char *detector; // /< Detector used for photometric system 49 50 } 50 51 psPhotSystem; … … 58 59 typedef struct 59 60 { 60 psPhotSystem src; ///< Source photometric system61 psPhotSystem dst; ///< Destination photometric system62 psPhotSystem pP; ///< Primary color reference63 psPhotSystem pM; ///< Primary color reference64 psPhotSystem sP; ///< Secondary color reference65 psPhotSystem sM; ///< Secondary color reference66 float pA; ///< Color offset for references67 float sA; ///< Color offset for references68 psPolynomial3D transform; ///< Transformation from source to destination61 psPhotSystem src; // /< Source photometric system 62 psPhotSystem dst; // /< Destination photometric system 63 psPhotSystem pP; // /< Primary color reference 64 psPhotSystem pM; // /< Primary color reference 65 psPhotSystem sP; // /< Secondary color reference 66 psPhotSystem sM; // /< Secondary color reference 67 float pA; // /< Color offset for references 68 float sA; // /< Color offset for references 69 psPolynomial3D transform; // /< Transformation from source to destination 69 70 } 70 71 psPhotTransform; -
trunk/psLib/src/astronomy/psTime.c
r1406 r1407 1 1 2 /** @file psTime.c 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1.1 3$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.14 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 18 19 */ 19 20 20 21 21 /******************************************************************************/ 22 22 23 /* INCLUDE FILES */ 24 23 25 /******************************************************************************/ 24 26 … … 32 34 33 35 /******************************************************************************/ 36 34 37 /* DEFINE STATEMENTS */ 38 35 39 /******************************************************************************/ 36 40 … … 73 77 } \ 74 78 79 75 80 /******************************************************************************/ 81 76 82 /* TYPE DEFINITIONS */ 83 77 84 /******************************************************************************/ 78 85 … … 80 87 81 88 /*****************************************************************************/ 89 82 90 /* GLOBAL VARIABLES */ 91 83 92 /*****************************************************************************/ 84 93 … … 86 95 87 96 /*****************************************************************************/ 97 88 98 /* FILE STATIC VARIABLES */ 99 89 100 /*****************************************************************************/ 90 101 … … 119 130 120 131 // Table for Julian date of leapsecond update and current total number of leapseconds at that date 121 static double leapseconds[NUM_LEAPSECOND_UPDATES][2] = 122 { 123 { 124 2441317.5, 10.0 125 }, 126 { 127 2441499.5, 11.0 128 }, 129 { 130 2441683.5, 12.0 131 }, 132 { 133 2442048.5, 13.0 134 }, 135 { 136 2442413.5, 14.0 137 }, 138 { 139 2442778.5, 15.0 140 }, 141 { 142 2443144.5, 16.0 143 }, 144 { 145 2443509.5, 17.0 146 }, 147 { 148 2443874.5, 18.0 149 }, 150 { 151 2444239.5, 19.0 152 }, 153 { 154 2444786.5, 20.0 155 }, 156 { 157 2445151.5, 21.0 158 }, 159 { 160 2445516.5, 22.0 161 }, 162 { 163 2446247.5, 23.0 164 }, 165 { 166 2447161.5, 24.0 167 }, 168 { 169 2447892.5, 25.0 170 }, 171 { 172 2448257.5, 26.0 173 }, 174 { 175 2448804.5, 27.0 176 }, 177 { 178 2449169.5, 28.0 179 }, 180 { 181 2449534.5, 29.0 182 }, 183 { 184 2450083.5, 30.0 185 }, 186 { 187 2450630.5, 31.0 188 }, 189 { 190 2451179.5, 32.0 191 } 192 }; 193 194 /*****************************************************************************/ 132 static double leapseconds[NUM_LEAPSECOND_UPDATES][2] = { 133 { 134 2441317.5, 10.0}, 135 { 136 2441499.5, 11.0}, 137 { 138 2441683.5, 12.0}, 139 { 140 2442048.5, 13.0}, 141 { 142 2442413.5, 14.0}, 143 { 144 2442778.5, 15.0}, 145 { 146 2443144.5, 16.0}, 147 { 148 2443509.5, 17.0}, 149 { 150 2443874.5, 18.0}, 151 { 152 2444239.5, 19.0}, 153 { 154 2444786.5, 20.0}, 155 { 156 2445151.5, 21.0}, 157 { 158 2445516.5, 22.0}, 159 { 160 2446247.5, 23.0}, 161 { 162 2447161.5, 24.0}, 163 { 164 2447892.5, 25.0}, 165 { 166 2448257.5, 26.0}, 167 { 168 2448804.5, 27.0}, 169 { 170 2449169.5, 28.0}, 171 { 172 2449534.5, 29.0}, 173 { 174 2450083.5, 30.0}, 175 { 176 2450630.5, 31.0}, 177 { 178 2451179.5, 32.0} 179 }; 180 181 /*****************************************************************************/ 182 195 183 /* FUNCTION IMPLEMENTATION - LOCAL */ 184 196 185 /*****************************************************************************/ 197 186 … … 199 188 200 189 /*****************************************************************************/ 190 201 191 /* FUNCTION IMPLEMENTATION - PUBLIC */ 192 202 193 /*****************************************************************************/ 203 194 … … 210 201 time.tv_usec = 0; 211 202 212 if (gettimeofday(&now,(struct timezone *)0) == -1) {203 if (gettimeofday(&now, (struct timezone *)0) == -1) { 213 204 psError(__func__, " : Line %d - Failed to get time", __LINE__); 214 205 return time; 215 206 } 216 217 207 // Convert timeval time to psTime 218 208 time.tv_sec = now.tv_sec; … … 220 210 221 211 // Add most current leapseconds value to UTC time to get TAI time 222 time.tv_sec += leapseconds[NUM_LEAPSECOND_UPDATES -1][1];212 time.tv_sec += leapseconds[NUM_LEAPSECOND_UPDATES - 1][1]; 223 213 224 214 return time; 225 215 } 226 216 227 char *psTimeToISO(psTime time)217 char *psTimeToISO(psTime time) 228 218 { 229 219 int ms = 0; … … 232 222 struct tm *tmTime = NULL; 233 223 234 CHECK_NEGATIVE_TIME_STRUCT(time, NULL);224 CHECK_NEGATIVE_TIME_STRUCT(time, NULL); 235 225 236 226 tempString = psAlloc(MAX_TIME_STRING_LENGTH); … … 238 228 239 229 // Converts psTime to YYYY/MM/DD,HH:MM:SS.SSS in string form 240 ms = time.tv_usec /1000;230 ms = time.tv_usec / 1000; 241 231 242 232 // tmTime variable is statically allocated, no need to free 243 233 tmTime = gmtime(&time.tv_sec); 244 if (!strftime(tempString, MAX_TIME_STRING_LENGTH, "%Y/%m/%d,%H:%M:%S", tmTime)) {234 if (!strftime(tempString, MAX_TIME_STRING_LENGTH, "%Y/%m/%d,%H:%M:%S", tmTime)) { 245 235 psError(__func__, " : Line %d - Failed strftime conversion", __LINE__); 246 236 } 247 237 248 if (snprintf(timeString,MAX_TIME_STRING_LENGTH,"%s.%3.3d", tempString, ms) < 0) {238 if (snprintf(timeString, MAX_TIME_STRING_LENGTH, "%s.%3.3d", tempString, ms) < 0) { 249 239 psError(__func__, " : Line %d - Failed snprintf conversion", __LINE__); 250 240 } … … 262 252 psTime outTime; 263 253 264 CHECK_NEGATIVE_TIME_STRUCT(time, outTime);254 CHECK_NEGATIVE_TIME_STRUCT(time, outTime); 265 255 266 256 // Find leapseconds to subtract from psTime to get UTC time 267 257 jd = psTimeToJD(time); 268 258 jdTable = leapseconds[0]; 269 for (i=0; i<NUM_LEAPSECOND_UPDATES; i++, jdTable+=2) {270 if (jd > *jdTable) {259 for (i = 0; i < NUM_LEAPSECOND_UPDATES; i++, jdTable += 2) { 260 if (jd > *jdTable) { 271 261 ls = *(jdTable + 1); 272 262 } … … 276 266 outTime.tv_usec = time.tv_usec; 277 267 278 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);268 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 279 269 280 270 return outTime; … … 285 275 double mjd = 0.0; 286 276 287 CHECK_NEGATIVE_TIME_STRUCT(time, mjd);277 CHECK_NEGATIVE_TIME_STRUCT(time, mjd); 288 278 289 279 // Modified Julian date conversion courtesy of Eugene Magnier 290 mjd = time.tv_sec /SEC_PER_DAY + time.tv_usec/USEC_PER_DAY + 40587.0;280 mjd = time.tv_sec / SEC_PER_DAY + time.tv_usec / USEC_PER_DAY + 40587.0; 291 281 292 282 return mjd; … … 297 287 double jd = 0.0; 298 288 299 CHECK_NEGATIVE_TIME_STRUCT(time, jd);289 CHECK_NEGATIVE_TIME_STRUCT(time, jd); 300 290 301 291 // Julian date conversion courtesy of Eugene Magnier 302 jd = time.tv_sec /SEC_PER_DAY + time.tv_usec/USEC_PER_DAY + 2440587.5;292 jd = time.tv_sec / SEC_PER_DAY + time.tv_usec / USEC_PER_DAY + 2440587.5; 303 293 304 294 return jd; … … 309 299 struct timeval timevalTime; 310 300 311 CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime);301 CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime); 312 302 timevalTime.tv_sec = time.tv_sec; 313 303 timevalTime.tv_usec = time.tv_usec; … … 316 306 } 317 307 318 struct tm *psTimeToTM(psTime time)308 struct tm *psTimeToTM(psTime time) 319 309 { 320 310 struct tm *tmTime = NULL; 321 311 322 CHECK_NEGATIVE_TIME_STRUCT(time, tmTime);312 CHECK_NEGATIVE_TIME_STRUCT(time, tmTime); 323 313 tmTime = gmtime(&time.tv_sec); 324 314 … … 343 333 // Convert YYYY/MM/DD,HH:MM:SS.SSS in string form to tm time 344 334 year = atoi(strtok(tempString, "/")); 345 if (year < 1900) {346 psError(__func__, "Years less than 1900 not allowed. Value: %d", year);335 if (year < 1900) { 336 psError(__func__, "Years less than 1900 not allowed. Value: %d", year); 347 337 return outTime; 348 338 } 349 339 350 340 month = atoi(strtok(NULL, "/")); 351 if (month<1 || month>12) {352 psError(__func__, "Month must have a value from 1 to 12. Value: %d", month);341 if (month < 1 || month > 12) { 342 psError(__func__, "Month must have a value from 1 to 12. Value: %d", month); 353 343 return outTime; 354 344 } 355 345 356 346 day = atoi(strtok(NULL, ",")); 357 if (day<1 || day>31) {358 psError(__func__, "Day must have a value from 1 to 31. Value: %d", day);347 if (day < 1 || day > 31) { 348 psError(__func__, "Day must have a value from 1 to 31. Value: %d", day); 359 349 return outTime; 360 350 } 361 351 362 352 hour = atoi(strtok(NULL, ":")); 363 if (hour<0 || hour>23) {364 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", hour);353 if (hour < 0 || hour > 23) { 354 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", hour); 365 355 return outTime; 366 356 } 367 357 368 358 minute = atoi(strtok(NULL, ":")); 369 if (minute<0 || minute>59) {370 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", minute);359 if (minute < 0 || minute > 59) { 360 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", minute); 371 361 return outTime; 372 362 } 373 363 374 364 second = atoi(strtok(NULL, ".")); 375 if (second<0 || second>59) {376 psError(__func__, "Second must have a value from 0 to 59. Value: %d", second);365 if (second < 0 || second > 59) { 366 psError(__func__, "Second must have a value from 0 to 59. Value: %d", second); 377 367 return outTime; 378 368 } 379 369 380 370 millisecond = atoi(strtok(NULL, "X")); 381 if (millisecond<0 || millisecond>1000) {382 psError(__func__, "Millisecond must have a value from 0 to 999. Value: %d", millisecond);371 if (millisecond < 0 || millisecond > 1000) { 372 psError(__func__, "Millisecond must have a value from 0 to 999. Value: %d", millisecond); 383 373 return outTime; 384 374 } … … 394 384 // Convert tm time to psTime 395 385 outTime = psTMToTime(&tmTime); 396 outTime.tv_usec = millisecond *1000;386 outTime.tv_usec = millisecond * 1000; 397 387 398 388 return outTime; … … 403 393 psTime outTime; 404 394 405 CHECK_NEGATIVE_TIME_STRUCT(time, outTime);395 CHECK_NEGATIVE_TIME_STRUCT(time, outTime); 406 396 407 397 // Convert UTC time to psTime/TAI 408 outTime.tv_sec = time.tv_sec + leapseconds[NUM_LEAPSECOND_UPDATES -1][1];398 outTime.tv_sec = time.tv_sec + leapseconds[NUM_LEAPSECOND_UPDATES - 1][1]; 409 399 outTime.tv_usec = time.tv_usec; 410 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);400 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 411 401 412 402 return outTime; … … 419 409 double seconds = 0.0; 420 410 421 CHECK_NEGATIVE_TIME(time, outTime);411 CHECK_NEGATIVE_TIME(time, outTime); 422 412 423 413 // Modified Julian date conversion courtesy of Eugene Magnier … … 425 415 426 416 // Convert to psTime/TAI 427 seconds = days *SEC_PER_DAY;428 outTime.tv_usec = (seconds - (long)seconds)*1000000.0;417 seconds = days * SEC_PER_DAY; 418 outTime.tv_usec = (seconds - (long)seconds) * 1000000.0; 429 419 outTime.tv_sec = seconds; 430 420 431 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);421 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 432 422 433 423 return outTime; … … 440 430 psTime outTime; 441 431 442 CHECK_NEGATIVE_TIME(time, outTime);432 CHECK_NEGATIVE_TIME(time, outTime); 443 433 444 434 // Julian date conversion courtesy of Eugene Magnier … … 446 436 447 437 // Convert to psTime/TAI 448 seconds = days *SEC_PER_DAY;438 seconds = days * SEC_PER_DAY; 449 439 outTime.tv_sec = seconds; 450 outTime.tv_usec = (seconds -(long)seconds)*1000000.0; 451 452 CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime); 453 454 return outTime; 455 } 456 457 psTime psTimevalToTime(struct timeval *time) 458 { 459 psTime outTime; 460 if(time == NULL) 461 { 462 psError(__func__,"Null value for timeval arg not allowed"); 463 return outTime; 464 } else 465 if(time->tv_sec < 0) 466 { 467 psError(__func__,"Negative seconds are not allowed: %ld", time->tv_sec); 468 return outTime; 469 } else 470 if(time->tv_usec<0) 471 { 472 psError(__func__,"Negative microseconds are not allowed: %ld", time->tv_usec); 473 return outTime; 474 } 475 440 outTime.tv_usec = (seconds - (long)seconds) * 1000000.0; 441 442 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 443 444 return outTime; 445 } 446 447 psTime psTimevalToTime(struct timeval * time) 448 { 449 psTime outTime; 450 451 if (time == NULL) 452 { 453 psError(__func__, "Null value for timeval arg not allowed"); 454 return outTime; 455 } else if (time->tv_sec < 0) 456 { 457 psError(__func__, "Negative seconds are not allowed: %ld", time->tv_sec); 458 return outTime; 459 } else if (time->tv_usec < 0) 460 { 461 psError(__func__, "Negative microseconds are not allowed: %ld", time->tv_usec); 462 return outTime; 463 } 476 464 // Convert to psTime/TAI 477 465 outTime.tv_sec = time->tv_sec; 478 466 outTime.tv_usec = time->tv_usec; 479 467 480 CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime); 481 482 return outTime; 483 } 484 485 486 psTime psTMToTime(struct tm *time) 468 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 469 470 return outTime; 471 } 472 473 psTime psTMToTime(struct tm * time) 487 474 { 488 475 int i; 489 476 int n; 490 477 int y; 491 int mon [] = 492 { 493 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 494 }; 478 int mon[] = { 479 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 480 }; 495 481 long epoch; 496 482 psTime outTime; 497 483 498 i = 0;484 i = 0; 499 485 n = 0; 500 486 y = 0; 501 487 epoch = 0; 502 488 503 if(time == NULL) 504 { 505 psError(__func__,"Null value for tm arg not allowed"); 506 return outTime; 507 } else 508 if(time->tm_year < 70) 509 { 510 psError(__func__,"Input times earlier than 1970 not allowed. Value: %d", time->tm_year+1900); 511 return outTime; 512 } else 513 if(time->tm_mon<0 || time->tm_mon>11) 514 { 515 psError(__func__,"Month must have a value from 0 to 11. Value: %d", time->tm_mon); 516 return outTime; 517 } else 518 if(time->tm_mday<1 || time->tm_mday>31) 519 { 520 psError(__func__,"Day must have a value from 1 to 31. Value: %d", time->tm_mday); 521 return outTime; 522 } else 523 if(time->tm_hour<0 || time->tm_hour>23) 524 { 525 psError(__func__,"Hour must have a value from 0 to 23. Value: %d", time->tm_hour); 526 return outTime; 527 } else 528 if(time->tm_min<0 || time->tm_min>59) 529 { 530 psError(__func__,"Minute must have a value from 0 to 59. Value: %d", time->tm_min); 531 return outTime; 532 } else 533 if(time->tm_sec<0 || time->tm_sec>59) 534 { 535 psError(__func__,"Second must have a value from 0 to 59. Value: %d", time->tm_sec); 536 return outTime; 537 } 489 if (time == NULL) 490 { 491 psError(__func__, "Null value for tm arg not allowed"); 492 return outTime; 493 } else if (time->tm_year < 70) 494 { 495 psError(__func__, "Input times earlier than 1970 not allowed. Value: %d", time->tm_year + 1900); 496 return outTime; 497 } else if (time->tm_mon < 0 || time->tm_mon > 11) 498 { 499 psError(__func__, "Month must have a value from 0 to 11. Value: %d", time->tm_mon); 500 return outTime; 501 } else if (time->tm_mday < 1 || time->tm_mday > 31) 502 { 503 psError(__func__, "Day must have a value from 1 to 31. Value: %d", time->tm_mday); 504 return outTime; 505 } else if (time->tm_hour < 0 || time->tm_hour > 23) 506 { 507 psError(__func__, "Hour must have a value from 0 to 23. Value: %d", time->tm_hour); 508 return outTime; 509 } else if (time->tm_min < 0 || time->tm_min > 59) 510 { 511 psError(__func__, "Minute must have a value from 0 to 59. Value: %d", time->tm_min); 512 return outTime; 513 } else if (time->tm_sec < 0 || time->tm_sec > 59) 514 { 515 psError(__func__, "Second must have a value from 0 to 59. Value: %d", time->tm_sec); 516 return outTime; 517 } 538 518 539 519 n = time->tm_year + 1900 - 1; 540 epoch = (time->tm_year - 70) * SEC_PER_YEAR + ((n /4 - n/100 + n/400) -541 (1969 /4 - 1969/100 + 1969/400)) * SEC_PER_DAY;520 epoch = (time->tm_year - 70) * SEC_PER_YEAR + ((n / 4 - n / 100 + n / 400) - 521 (1969 / 4 - 1969 / 100 + 1969 / 400)) * SEC_PER_DAY; 542 522 543 523 y = time->tm_year + 1900; 544 524 545 525 // Adjust for leap years 546 for (i = 0; i<time->tm_mon; i++)547 { 548 epoch += mon [i] * SEC_PER_DAY;549 if (i == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) {526 for (i = 0; i < time->tm_mon; i++) 527 { 528 epoch += mon[i] * SEC_PER_DAY; 529 if (i == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) { 550 530 epoch += SEC_PER_DAY; 551 531 } … … 554 534 // Add everything 555 535 epoch += (time->tm_mday - 1) * SEC_PER_DAY; 556 epoch += time->tm_hour * SEC_PER_HOUR + time->tm_min * SEC_PER_MINUTE + time->tm_sec;536 epoch += time->tm_hour * SEC_PER_HOUR + time->tm_min * SEC_PER_MINUTE + time->tm_sec; 557 537 558 538 // Create psTime … … 560 540 outTime.tv_sec = epoch; 561 541 562 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);563 564 return outTime; 565 } 542 CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime); 543 544 return outTime; 545 } -
trunk/psLib/src/astronomy/psTime.h
r1406 r1407 1 1 2 /** @file psTime.h 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PSTIME_H 21 # define PSTIME_H22 23 # include <time.h>24 # include <sys/types.h>25 # include <sys/time.h>26 27 # include "psType.h"22 # define PSTIME_H 23 24 # include <time.h> 25 # include <sys/types.h> 26 # include <sys/time.h> 27 28 # include "psType.h" 28 29 29 30 /// @addtogroup Time … … 31 32 32 33 /******************************************************************************/ 34 33 35 /* TYPE DEFINITIONS */ 36 34 37 /******************************************************************************/ 35 38 … … 42 45 typedef struct 43 46 { 44 time_t tv_sec; /**< Seconds since epoch, Jan 1, 1970. */ 45 suseconds_t tv_usec; /**< Microseconds since last second. */ 47 48 time_t tv_sec; /**< Seconds since epoch, Jan 1, 1970. */ 49 50 suseconds_t tv_usec; /**< Microseconds since last second. */ 46 51 } 47 52 psTime; 48 53 49 54 /*****************************************************************************/ 55 50 56 /* FUNCTION PROTOTYPES */ 57 51 58 /*****************************************************************************/ 52 59 … … 57 64 * @return psTime: Struct with current time. 58 65 */ 59 psTime psTimeGetTime( 60 void /** No argument. */ 61 ); 66 67 psTime psTimeGetTime(void 68 /** No argument. */ 69 ); 62 70 63 71 /** Convert psTime to ISO time in TAI units. … … 68 76 * @return char*: Pointer null terminated array of chars in ISO time. 69 77 */ 70 char* psTimeToISO( 71 psTime time /** Input time to be converted. */ 72 ); 78 79 char *psTimeToISO(psTime time 80 /** Input time to be converted. */ 81 ); 73 82 74 83 /** Convert psTime to UTC time. … … 80 89 * @return psTime: UTC time psTime format. 81 90 */ 82 psTime psTimeToUTC( 83 psTime time /** Input time to be converted. */ 84 ); 91 92 psTime psTimeToUTC(psTime time 93 /** Input time to be converted. */ 94 ); 85 95 86 96 /** Convert psTime to modified Julian date time. … … 91 101 * @return double: Modified Julian Days (MJD) time. 92 102 */ 93 double psTimeToMJD( 94 psTime time /** Input time to be converted. */ 95 ); 103 104 double psTimeToMJD(psTime time 105 /** Input time to be converted. */ 106 ); 96 107 97 108 /** Convert psTime to Julian date time. … … 102 113 * @return double: Julian Date (JD) time. 103 114 */ 104 double psTimeToJD( 105 psTime time /** Input time to be converted. */ 106 ); 115 116 double psTimeToJD(psTime time 117 /** Input time to be converted. */ 118 ); 107 119 108 120 /** Convert psTime to timeval time. … … 113 125 * @return timeval: timeval struct time. 114 126 */ 115 struct timeval psTimeToTimeval( 116 psTime time /** Input time to be converted. */ 117 ); 127 128 struct timeval psTimeToTimeval(psTime time 129 /** Input time to be converted. */ 130 ); 118 131 119 132 /** Convert psTime to tm time. … … 124 137 * @return tm: tm struct time. 125 138 */ 126 struct tm* psTimeToTM( 127 psTime time /** Input time to be converted. */ 128 ); 139 140 struct tm *psTimeToTM(psTime time 141 /** Input time to be converted. */ 142 ); 129 143 130 144 /** Convert ISO to psTime. … … 135 149 * @return psTime: time 136 150 */ 137 psTime psISOToTime( 138 char *time /** Input time to be converted. */ 139 ); 151 152 psTime psISOToTime(char *time 153 /** Input time to be converted. */ 154 ); 140 155 141 156 /** Convert UTC to psTime. … … 146 161 * @return psTime: time in TAI units. 147 162 */ 148 psTime psUTCToTime( 149 psTime time /** Input time to be converted. */ 150 ); 163 164 psTime psUTCToTime(psTime time 165 /** Input time to be converted. */ 166 ); 151 167 152 168 /** Convert MJD to psTime. … … 157 173 * @return psTime: time. 158 174 */ 159 psTime psMJDToTime( 160 double time /** Input time to be converted. */ 161 ); 175 176 psTime psMJDToTime(double time 177 /** Input time to be converted. */ 178 ); 162 179 163 180 /** Convert JD to psTime. … … 168 185 * @return psTime: time. 169 186 */ 170 psTime psJDToTime( 171 double time /** Input time to be converted. */ 172 ); 187 188 psTime psJDToTime(double time 189 /** Input time to be converted. */ 190 ); 173 191 174 192 /** Convert timeval to psTime. … … 179 197 * @return psTime: time. 180 198 */ 181 psTime psTimevalToTime( 182 struct timeval *time /** Input time to be converted. */ 183 ); 199 200 psTime psTimevalToTime(struct timeval *time 201 /** Input time to be converted. */ 202 ); 184 203 185 204 /** Convert tm time to psTime. … … 190 209 * @return psTime: time. 191 210 */ 192 psTime psTMToTime( 193 struct tm *time /** Input time to be converted. */ 194 ); 211 212 psTime psTMToTime(struct tm *time 213 /** Input time to be converted. */ 214 ); 215 195 216 /// @} 196 217 -
trunk/psLib/src/collections/psArray.c
r1406 r1407 1 1 2 /** @file psArray.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 #include<stdlib.h> // for qsort, etc.22 #include<stdlib.h> // for qsort, etc. 20 23 21 24 #include "psMemory.h" … … 24 27 #include "psLogMsg.h" 25 28 29 /*****************************************************************************/ 30 31 /* FUNCTION IMPLEMENTATION - LOCAL */ 26 32 27 33 /*****************************************************************************/ 28 /* FUNCTION IMPLEMENTATION - LOCAL */ 29 /*****************************************************************************/ 30 static void arrayFree(psArray *restrict psArr); 34 static void arrayFree(psArray * restrict psArr); 31 35 32 36 /*****************************************************************************/ 37 33 38 /* FUNCTION IMPLEMENTATION - PUBLIC */ 39 34 40 /*****************************************************************************/ 35 psArray *psArrayAlloc(unsigned int nalloc)41 psArray *psArrayAlloc(unsigned int nalloc) 36 42 { 37 43 psArray *psArr = NULL; 38 44 39 45 // Invalid nalloc 40 if (nalloc < 1) {46 if (nalloc < 1) { 41 47 psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc); 42 48 return NULL; 43 49 } 44 45 50 // Create vector struct 46 psArr = (psArray *) psAlloc(sizeof(psArray));47 p_psMemSetDeallocator(psArr, (psFreeFcn)arrayFree);51 psArr = (psArray *) psAlloc(sizeof(psArray)); 52 p_psMemSetDeallocator(psArr, (psFreeFcn) arrayFree); 48 53 49 54 psArr->nalloc = nalloc; … … 51 56 52 57 // Create vector data array 53 psArr->data = psAlloc(nalloc *sizeof(psPTR));58 psArr->data = psAlloc(nalloc * sizeof(psPTR)); 54 59 55 60 return psArr; 56 61 } 57 62 58 psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in)63 psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in) 59 64 { 60 65 // Invalid nalloc 61 if (nalloc < 1) {66 if (nalloc < 1) { 62 67 psError(__func__, "Invalid value for realloc (%d)\n", nalloc); 63 68 return NULL; 64 69 } 65 70 66 if (in == NULL) {71 if (in == NULL) { 67 72 psError(__func__, "Null input vector\n"); 68 73 return NULL; 69 } else 70 if(in->nalloc != nalloc) { // No need to realloc to same size 71 if(nalloc < in->n) { 72 for (int i = nalloc; i < in->n; i++) { // For reduction in vector size 73 psFree(in->data[i]); 74 } 75 in->n = nalloc; 74 } else if (in->nalloc != nalloc) { // No need to realloc to same size 75 if (nalloc < in->n) { 76 for (int i = nalloc; i < in->n; i++) { // For reduction in vector size 77 psFree(in->data[i]); 76 78 } 77 78 // Realloc after decrementation to avoid accessing freed array elements 79 in->data = psRealloc(in->data,nalloc*sizeof(psPTR)); 80 in->nalloc = nalloc; 79 in->n = nalloc; 81 80 } 81 // Realloc after decrementation to avoid accessing freed array elements 82 in->data = psRealloc(in->data, nalloc * sizeof(psPTR)); 83 in->nalloc = nalloc; 84 } 82 85 83 86 return in; 84 87 } 85 88 86 static void arrayFree(psArray * restrict psArr)89 static void arrayFree(psArray * restrict psArr) 87 90 { 88 91 if (psArr == NULL) { … … 95 98 } 96 99 97 void psArrayElementFree(psArray * restrict psArr)100 void psArrayElementFree(psArray * restrict psArr) 98 101 { 99 102 100 if (psArr == NULL) {103 if (psArr == NULL) { 101 104 return; 102 105 } 103 106 104 for (int i = 0; i < psArr->n; i++) {107 for (int i = 0; i < psArr->n; i++) { 105 108 psFree(psArr->data[i]); 106 109 psArr->data[i] = NULL; … … 108 111 } 109 112 110 psArray * psArraySort(psArray* in, psComparePtrFcn compare)113 psArray *psArraySort(psArray * in, psComparePtrFcn compare) 111 114 { 112 115 if (in == NULL) { … … 114 117 } 115 118 116 qsort(in->data, in->n, sizeof(psPTR), 117 (int(*)(const void *, const void *))compare); 118 119 qsort(in->data, in->n, sizeof(psPTR), (int (*)(const void *, const void *))compare); 119 120 120 121 return in; -
trunk/psLib/src/collections/psArray.h
r1228 r1407 1 1 2 /** @file psArray.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-0 7-15 22:18:02$14 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_ARRAY_H 20 # define PS_ARRAY_H21 # define PS_ARRAY_H 21 22 22 # include "psType.h"23 # include "psCompare.h"23 # include "psType.h" 24 # include "psCompare.h" 24 25 25 26 /// @addtogroup Array … … 33 34 typedef struct 34 35 { 35 unsigned int nalloc; ///< Total number of elements available.36 unsigned int n; ///< Number of elements in use.37 psPTR * data; ///< An Array of pointer elements36 unsigned int nalloc; // /< Total number of elements available. 37 unsigned int n; // /< Number of elements in use. 38 psPTR *data; // /< An Array of pointer elements 38 39 } 39 40 psArray; 40 41 41 42 /*****************************************************************************/ 43 42 44 /* FUNCTION PROTOTYPES */ 45 43 46 /*****************************************************************************/ 44 47 … … 51 54 * 52 55 */ 53 psArray *psArrayAlloc( 54 unsigned int nalloc ///< Total number of elements to make available. 55 ); 56 psArray *psArrayAlloc(unsigned int nalloc // /< Total number of elements to make available. 57 ); 56 58 57 59 /** Reallocate an array. … … 63 65 * 64 66 */ 65 psArray *psArrayRealloc( 66 unsigned int nalloc, ///< Total number of elements to make available. 67 psArray *restrict psArr ///< array to reallocate. 68 ); 67 psArray *psArrayRealloc(unsigned int nalloc, // /< Total number of elements to make available. 68 psArray * restrict psArr // /< array to reallocate. 69 ); 69 70 70 71 /** Deallocate/Dereference elements of an array. … … 75 76 * 76 77 */ 77 void psArrayElementFree( 78 psArray *restrict psArr ///< Void pointer array to destroy. 79 ); 78 void psArrayElementFree(psArray * restrict psArr // /< Void pointer array to destroy. 79 ); 80 80 81 81 /** Sort the array according to an external compare function. … … 86 86 * @return psArray* The sorted array. 87 87 */ 88 psArray * psArraySort(psArray* in, psComparePtrFcn compare);88 psArray *psArraySort(psArray * in, psComparePtrFcn compare); 89 89 90 90 /// @} -
trunk/psLib/src/collections/psBitSet.c
r1406 r1407 1 1 2 /** @file psBitSet.c 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 /******************************************************************************/ 20 19 21 /* INCLUDE FILES */ 22 20 23 /******************************************************************************/ 21 24 #include <string.h> … … 31 34 32 35 /******************************************************************************/ 36 33 37 /* DEFINE STATEMENTS */ 34 /******************************************************************************/ 35 36 // None 37 38 /******************************************************************************/ 38 39 /******************************************************************************/ 40 41 // None 42 43 /******************************************************************************/ 44 39 45 /* TYPE DEFINITIONS */ 40 /******************************************************************************/ 41 42 // None 43 44 /*****************************************************************************/ 46 47 /******************************************************************************/ 48 49 // None 50 51 /*****************************************************************************/ 52 45 53 /* GLOBAL VARIABLES */ 46 /*****************************************************************************/ 47 48 // None 49 50 /*****************************************************************************/ 54 55 /*****************************************************************************/ 56 57 // None 58 59 /*****************************************************************************/ 60 51 61 /* FILE STATIC VARIABLES */ 52 /*****************************************************************************/ 53 54 // None 55 56 /*****************************************************************************/ 62 63 /*****************************************************************************/ 64 65 // None 66 67 /*****************************************************************************/ 68 57 69 /* FUNCTION IMPLEMENTATION - LOCAL */ 58 /*****************************************************************************/ 59 static void psBitSetFree(psBitSet *restrict inBitSet); 60 70 71 /*****************************************************************************/ 72 static void psBitSetFree(psBitSet * restrict inBitSet); 61 73 62 74 /** Private function to create a mask. … … 70 82 { 71 83 char mask = (char)0x01; 84 72 85 // Ignore splint warning about negative bit shifts 73 /* @i@*/74 mask = mask << (bit %8);86 /* @i@ */ 87 mask = mask << (bit % 8); 75 88 76 89 return mask; … … 78 91 79 92 /*****************************************************************************/ 93 80 94 /* FUNCTION IMPLEMENTATION - PUBLIC */ 81 /*****************************************************************************/ 82 psBitSet* psBitSetAlloc(int n) 95 96 /*****************************************************************************/ 97 psBitSet *psBitSetAlloc(int n) 83 98 { 84 99 int numBytes = 0; 85 100 psBitSet *newObj = NULL; 86 101 87 if (n <= 0) {102 if (n <= 0) { 88 103 psError(__func__, " : Line %d - Allocation size must be > 0: size = %d", __LINE__, n); 89 104 return 0; 90 105 } 91 106 92 numBytes = ceil(n /8.0);107 numBytes = ceil(n / 8.0); 93 108 newObj = psAlloc(sizeof(psBitSet)); 94 if (newObj == NULL) {95 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);96 } 97 p_psMemSetDeallocator(newObj, (psFreeFcn)psBitSetFree);109 if (newObj == NULL) { 110 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 111 } 112 p_psMemSetDeallocator(newObj, (psFreeFcn) psBitSetFree); 98 113 newObj->n = numBytes; 99 114 100 115 // Ignore splint warning about releasing pointer members, since they've not been allocated yet 101 /* @i@*/102 newObj->bits = psAlloc(sizeof(char) *numBytes);103 if (newObj->bits == NULL) {104 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);116 /* @i@ */ 117 newObj->bits = psAlloc(sizeof(char) * numBytes); 118 if (newObj->bits == NULL) { 119 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 105 120 } 106 121 … … 110 125 } 111 126 112 static void psBitSetFree(psBitSet * restrict inBitSet)113 { 114 if (inBitSet == NULL) {127 static void psBitSetFree(psBitSet * restrict inBitSet) 128 { 129 if (inBitSet == NULL) { 115 130 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 116 131 return; … … 119 134 } 120 135 121 psBitSet * psBitSetSet(psBitSet *inBitSet, int bit)122 { 123 char *byte = NULL;124 125 if (inBitSet == NULL) {136 psBitSet *psBitSetSet(psBitSet * inBitSet, int bit) 137 { 138 char *byte = NULL; 139 140 if (inBitSet == NULL) { 126 141 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 127 142 return inBitSet; 128 } else 129 if(bit < 0) { 130 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 131 return inBitSet; 132 } else 133 if(bit > inBitSet->n*8-1) { 134 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 135 return inBitSet; 136 } 137 143 } else if (bit < 0) { 144 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 145 return inBitSet; 146 } else if (bit > inBitSet->n * 8 - 1) { 147 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 148 return inBitSet; 149 } 138 150 // Variable byte is the byte in the array that contains the bit to be set 139 byte = inBitSet->bits +bit/8;151 byte = inBitSet->bits + bit / 8; 140 152 *byte |= mask(bit); 141 153 … … 143 155 } 144 156 145 bool psBitSetTest(const psBitSet *inBitSet, int bit) 146 { 147 char* byte = NULL; 148 149 if(inBitSet == NULL) { 150 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 151 return 0; 152 } else 153 if(bit < 0) { 154 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 155 return 0; 156 } else 157 if(bit > inBitSet->n*8-1) { 158 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 159 return 0; 160 } 161 157 bool psBitSetTest(const psBitSet * inBitSet, int bit) 158 { 159 char *byte = NULL; 160 161 if (inBitSet == NULL) { 162 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 163 return 0; 164 } else if (bit < 0) { 165 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 166 return 0; 167 } else if (bit > inBitSet->n * 8 - 1) { 168 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 169 return 0; 170 } 162 171 // Variable byte is the byte in the array that contains the bit to be tested 163 byte = inBitSet->bits +bit/8;164 if ((int)(*byte&mask(bit)) == 0) {172 byte = inBitSet->bits + bit / 8; 173 if ((int)(*byte & mask(bit)) == 0) { 165 174 return 0; 166 175 } … … 169 178 } 170 179 171 psBitSet * psBitSetOp(psBitSet *outBitSet, const psBitSet *restrict inBitSet1, char *operator,172 const psBitSet * restrict inBitSet2)180 psBitSet *psBitSetOp(psBitSet * outBitSet, const psBitSet * restrict inBitSet1, char *operator, 181 const psBitSet * restrict inBitSet2) 173 182 { 174 183 int i = 0; … … 179 188 char *inBits2 = NULL; 180 189 181 if (inBitSet1 == NULL) {190 if (inBitSet1 == NULL) { 182 191 psError(__func__, " : Line %d - Null psBitSet for inBitSet1 argument", __LINE__); 183 192 return outBitSet; 184 193 } 185 194 186 if (operator == NULL) {195 if (operator == NULL) { 187 196 psError(__func__, " : Line %d - Null input operator\n", __LINE__); 188 197 return outBitSet; 189 198 } 190 199 191 if (inBitSet2 == NULL) {200 if (inBitSet2 == NULL) { 192 201 psError(__func__, " : Line %d - Null psBitSet for inBitSet2 argument", __LINE__); 193 202 return outBitSet; 194 203 } 195 204 196 if (outBitSet == NULL) {197 outBitSet = psBitSetAlloc(inBitSet1->n *8);198 } 199 200 if (inBitSet1->n != inBitSet2->n || outBitSet->n != inBitSet1->n) {205 if (outBitSet == NULL) { 206 outBitSet = psBitSetAlloc(inBitSet1->n * 8); 207 } 208 209 if (inBitSet1->n != inBitSet2->n || outBitSet->n != inBitSet1->n) { 201 210 psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__); 202 211 return outBitSet; … … 209 218 210 219 tempChar = toupper(operator[0]); 211 switch (tempChar) {220 switch (tempChar) { 212 221 case 'A': 213 for (i=0; i<n; i++) {222 for (i = 0; i < n; i++) { 214 223 outBits[i] = inBits1[i] & inBits2[i]; 215 224 } 216 225 break; 217 226 case 'O': 218 for (i=0; i<n; i++) {227 for (i = 0; i < n; i++) { 219 228 outBits[i] = inBits1[i] | inBits2[i]; 220 229 } 221 230 break; 222 231 case 'X': 223 for (i=0; i<n; i++) {232 for (i = 0; i < n; i++) { 224 233 outBits[i] = inBits1[i] ^ inBits2[i]; 225 234 } … … 232 241 } 233 242 234 psBitSet * psBitSetNot(psBitSet *outBitSet, const psBitSet *restrict inBitSet)243 psBitSet *psBitSetNot(psBitSet * outBitSet, const psBitSet * restrict inBitSet) 235 244 { 236 245 int i = 0; … … 239 248 char *inBits = NULL; 240 249 241 if (inBitSet == NULL) {250 if (inBitSet == NULL) { 242 251 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 243 252 return outBitSet; … … 245 254 246 255 n = inBitSet->n; 247 if (n == 0) {256 if (n == 0) { 248 257 psError(__func__, " : Line %d - No elements in inBitSet", __LINE__); 249 258 return outBitSet; 250 259 } 251 260 252 if (outBitSet == NULL) {253 outBitSet = psBitSetAlloc(n *8);254 } 255 256 if (inBitSet->n != outBitSet->n) {261 if (outBitSet == NULL) { 262 outBitSet = psBitSetAlloc(n * 8); 263 } 264 265 if (inBitSet->n != outBitSet->n) { 257 266 psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__); 258 267 return outBitSet; … … 262 271 inBits = inBitSet->bits; 263 272 264 for (i=0; i<n; i++) {273 for (i = 0; i < n; i++) { 265 274 outBits[i] = ~inBits[i]; 266 275 } … … 269 278 } 270 279 271 char *psBitSetToString(const psBitSet * restrict inBitSet)280 char *psBitSetToString(const psBitSet * restrict inBitSet) 272 281 { 273 282 int i = 0; 274 int numBits = inBitSet->n*8; 275 char* outString = psAlloc((size_t)numBits+1); 276 if(outString == NULL) { 277 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__); 278 } 279 280 for(i=0; i<numBits; i++) { 281 outString[numBits-i-1] = (psBitSetTest(inBitSet, i) == 1)?'1':'0'; 283 int numBits = inBitSet->n * 8; 284 char *outString = psAlloc((size_t) numBits + 1); 285 286 if (outString == NULL) { 287 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 288 } 289 290 for (i = 0; i < numBits; i++) { 291 outString[numBits - i - 1] = (psBitSetTest(inBitSet, i) == 1) ? '1' : '0'; 282 292 } 283 293 -
trunk/psLib/src/collections/psBitSet.h
r1172 r1407 1 1 2 /** @file psBitSet.h 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-0 7-01 21:48:11$15 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PSBITSET_H 21 # define PSBITSET_H22 # define PSBITSET_H 22 23 23 24 /// @addtogroup BitSet … … 25 26 26 27 /******************************************************************************/ 28 27 29 /* TYPE DEFINITIONS */ 30 28 31 /******************************************************************************/ 29 32 … … 35 38 typedef struct 36 39 { 40 37 41 int n; /**< Number of bytes in the array */ 42 38 43 char *bits; /**< Aray of bytes holding bits */ 39 44 } … … 41 46 42 47 /*****************************************************************************/ 48 43 49 /* FUNCTION PROTOTYPES */ 50 44 51 /*****************************************************************************/ 45 52 … … 51 58 * @return psBitSet*: Pointer to struct containing array of bits and size of array. 52 59 */ 60 53 61 /*@null@*/ 54 psBitSet* psBitSetAlloc( 55 int n /**< Number of bits in psBitSet array */ 56 ); 62 63 psBitSet *psBitSetAlloc(int n 64 /**< Number of bits in psBitSet array */ 65 ); 57 66 58 67 /** Set a bit. … … 64 73 * @return psBitSet*: Pointer to struct containing psBitSet. 65 74 */ 66 psBitSet* psBitSetSet( 67 /*@returned@*/psBitSet *restrict inMask, /**< Pointer to psBitSet to be set. */ 68 int bit /**< Bit to be set. */ 75 psBitSet *psBitSetSet( 76 77 /* @returned@ */ psBitSet * restrict inMask, 78 /**< Pointer to psBitSet to be set. */ 79 80 int bit/**< Bit to be set. */ 69 81 ); 70 82 … … 78 90 * @return int: Value of bit, either one or zero. 79 91 */ 80 bool psBitSetTest( 81 const psBitSet *restrict inMask, /**< Pointer psBitSet to be tested. */ 82 int bit /**< Bit to be tested. */ 83 ); 92 93 bool psBitSetTest(const psBitSet * restrict inMask, 94 /**< Pointer psBitSet to be tested. */ 95 96 int bit /**< Bit to be tested. */ 97 ); 84 98 85 99 /** Perform a binary operation on two psBitSets … … 90 104 * @return psBitSet*: Pointer to struct containing result of binary operation. 91 105 */ 92 psBitSet* psBitSetOp( 93 /*@returned@*/psBitSet *restrict outMask, /**< Resulting psBitSet from binary operation */ 94 const psBitSet *restrict inMask1, /**< First psBitSet on which to operate */ 95 char *operator, /**< Bit operation */ 96 const psBitSet *restrict inMask2 /**< First psBitSet on which to operate */ 106 psBitSet *psBitSetOp( 107 108 /* @returned@ */ psBitSet * restrict outMask, 109 /**< Resulting psBitSet from binary operation */ 110 111 const psBitSet * restrict inMask1, 112 /**< First psBitSet on which to operate */ 113 114 char *operator, /**< Bit operation */ 115 116 const psBitSet * restrict inMask2 117 /**< First psBitSet on which to operate */ 97 118 ); 98 119 … … 103 124 * @return psBitSet*: Pointer to struct containing result of operation. 104 125 */ 105 psBitSet* psBitSetNot( 106 psBitSet *outBitSet, /**< Resulting psBitSet from operation */ 107 const psBitSet *restrict inBitSet /**< Input psBitSet */ 108 ); 126 127 psBitSet *psBitSetNot(psBitSet * outBitSet, 128 /**< Resulting psBitSet from operation */ 129 130 const psBitSet * restrict inBitSet 131 /**< Input psBitSet */ 132 ); 109 133 110 134 /** Convert the psBitSet to a string of ones and zeros. … … 115 139 * @return char*: Pointer to character array containing string data. 116 140 */ 117 char *psBitSetToString( 118 const psBitSet *restrict inMask /**< psBitSet to convert */ 119 ); 141 142 char *psBitSetToString(const psBitSet * restrict inMask 143 /**< psBitSet to convert */ 144 ); 120 145 121 146 /// @} -
trunk/psLib/src/collections/psCompare.c
r1393 r1407 1 1 2 /** @file psCompare.c 2 3 * @brief Comparison functions for sorting routines … … 6 7 * @author Robert Daniel DeSonia, MHPCC 7 8 * 8 * @version $Revision: 1. 3$ $Name: not supported by cvs2svn $9 * @date $Date: 2004-08-0 5 19:38:52$9 * @version $Revision: 1.4 $ $Name: not supported by cvs2svn $ 10 * @date $Date: 2004-08-07 00:06:06 $ 10 11 * 11 12 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii -
trunk/psLib/src/collections/psCompare.h
r1111 r1407 1 1 #if !defined(PS_COMPARE_H) 2 # define PS_COMPARE_H2 # define PS_COMPARE_H 3 3 4 4 /** @file psCompare.h … … 9 9 * @ingroup Compare 10 10 * 11 * @version $Revision: 1. 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-0 6-28 20:36:37$11 * @version $Revision: 1.2 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 13 13 * 14 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 26 26 * than, equal to, or greater than the second. 27 27 */ 28 typedef int (*psComparePtrFcn) (const void** a, const void**b);28 typedef int (*psComparePtrFcn) (const void **a, const void **b); 29 29 30 30 /** A comparison function for sorting. … … 34 34 * than, equal to, or greater than the second. 35 35 */ 36 typedef int (*psCompareFcn) (const void* a, const void*b);36 typedef int (*psCompareFcn) (const void *a, const void *b); 37 37 38 38 /** Compare function of psS8 data. For use with psListSort. … … 42 42 * than, equal to, or greater than the second. 43 43 */ 44 int psCompareS8Ptr(const void ** a, const void**b);44 int psCompareS8Ptr(const void **a, const void **b); 45 45 46 46 /** Compare function of psS16 data. For use with psListSort. … … 50 50 * than, equal to, or greater than the second. 51 51 */ 52 int psCompareS16Ptr(const void ** a, const void**b);52 int psCompareS16Ptr(const void **a, const void **b); 53 53 54 54 /** Compare function of psS32 data. For use with psListSort. … … 58 58 * than, equal to, or greater than the second. 59 59 */ 60 int psCompareS32Ptr(const void ** a, const void**b);60 int psCompareS32Ptr(const void **a, const void **b); 61 61 62 62 /** Compare function of psS64 data. For use with psListSort. … … 66 66 * than, equal to, or greater than the second. 67 67 */ 68 int psCompareS64Ptr(const void ** a, const void**b);68 int psCompareS64Ptr(const void **a, const void **b); 69 69 70 70 /** Compare function of psU8 data. For use with psListSort. … … 74 74 * than, equal to, or greater than the second. 75 75 */ 76 int psCompareU8Ptr(const void ** a, const void**b);76 int psCompareU8Ptr(const void **a, const void **b); 77 77 78 78 /** Compare function of psU16 data. For use with psListSort. … … 82 82 * than, equal to, or greater than the second. 83 83 */ 84 int psCompareU16Ptr(const void ** a, const void**b);84 int psCompareU16Ptr(const void **a, const void **b); 85 85 86 86 /** Compare function of psU32 data. For use with psListSort. … … 90 90 * than, equal to, or greater than the second. 91 91 */ 92 int psCompareU32Ptr(const void ** a, const void**b);92 int psCompareU32Ptr(const void **a, const void **b); 93 93 94 94 /** Compare function of psU64 data. For use with psListSort. … … 98 98 * than, equal to, or greater than the second. 99 99 */ 100 int psCompareU64Ptr(const void ** a, const void**b);100 int psCompareU64Ptr(const void **a, const void **b); 101 101 102 102 /** Compare function of psF32 data. For use with psListSort. … … 106 106 * than, equal to, or greater than the second. 107 107 */ 108 int psCompareF32Ptr(const void ** a, const void**b);108 int psCompareF32Ptr(const void **a, const void **b); 109 109 110 110 /** Compare function of psF64 data. For use with psListSort. … … 114 114 * than, equal to, or greater than the second. 115 115 */ 116 int psCompareF64Ptr(const void ** a, const void**b);116 int psCompareF64Ptr(const void **a, const void **b); 117 117 118 118 /** Compare function of psS8 data. For use with psListSort for descending ordering. … … 122 122 * than, equal to, or less than the second. 123 123 */ 124 int psCompareDescendingS8Ptr(const void ** a, const void**b);124 int psCompareDescendingS8Ptr(const void **a, const void **b); 125 125 126 126 /** Compare function of psS16 data. For use with psListSort for descending ordering. … … 130 130 * than, equal to, or less than the second. 131 131 */ 132 int psCompareDescendingS16Ptr(const void ** a, const void**b);132 int psCompareDescendingS16Ptr(const void **a, const void **b); 133 133 134 134 /** Compare function of psS32 data. For use with psListSort for descending ordering. … … 138 138 * than, equal to, or less than the second. 139 139 */ 140 int psCompareDescendingS32Ptr(const void ** a, const void**b);140 int psCompareDescendingS32Ptr(const void **a, const void **b); 141 141 142 142 /** Compare function of psS64 data. For use with psListSort for descending ordering. … … 146 146 * than, equal to, or less than the second. 147 147 */ 148 int psCompareDescendingS64Ptr(const void ** a, const void**b);148 int psCompareDescendingS64Ptr(const void **a, const void **b); 149 149 150 150 /** Compare function of psU8 data. For use with psListSort for descending ordering. … … 154 154 * than, equal to, or less than the second. 155 155 */ 156 int psCompareDescendingU8Ptr(const void ** a, const void**b);156 int psCompareDescendingU8Ptr(const void **a, const void **b); 157 157 158 158 /** Compare function of psU16 data. For use with psListSort for descending ordering. … … 162 162 * than, equal to, or less than the second. 163 163 */ 164 int psCompareDescendingU16Ptr(const void ** a, const void**b);164 int psCompareDescendingU16Ptr(const void **a, const void **b); 165 165 166 166 /** Compare function of psU32 data. For use with psListSort for descending ordering. … … 170 170 * than, equal to, or lessg than the second. 171 171 */ 172 int psCompareDescendingU32Ptr(const void ** a, const void**b);172 int psCompareDescendingU32Ptr(const void **a, const void **b); 173 173 174 174 /** Compare function of psU64 data. For use with psListSort for descending ordering. … … 178 178 * than, equal to, or lessg than the second. 179 179 */ 180 int psCompareDescendingU64Ptr(const void ** a, const void**b);180 int psCompareDescendingU64Ptr(const void **a, const void **b); 181 181 182 182 /** Compare function of psF32 data. For use with psListSort for descending ordering. … … 186 186 * than, equal to, or lessg than the second. 187 187 */ 188 int psCompareDescendingF32Ptr(const void ** a, const void**b);188 int psCompareDescendingF32Ptr(const void **a, const void **b); 189 189 190 190 /** Compare function of psF64 data. For use with psListSort for descending ordering. … … 194 194 * than, equal to, or lessg than the second. 195 195 */ 196 int psCompareDescendingF64Ptr(const void ** a, const void**b);196 int psCompareDescendingF64Ptr(const void **a, const void **b); 197 197 198 198 /** Compare function of psS8 data. … … 202 202 * than, equal to, or greater than the second. 203 203 */ 204 int psCompareS8(const void * a, const void*b);204 int psCompareS8(const void *a, const void *b); 205 205 206 206 /** Compare function of psS16 data. … … 210 210 * than, equal to, or greater than the second. 211 211 */ 212 int psCompareS16(const void * a, const void*b);212 int psCompareS16(const void *a, const void *b); 213 213 214 214 /** Compare function of psS32 data. … … 218 218 * than, equal to, or greater than the second. 219 219 */ 220 int psCompareS32(const void * a, const void*b);220 int psCompareS32(const void *a, const void *b); 221 221 222 222 /** Compare function of psS64 data. … … 226 226 * than, equal to, or greater than the second. 227 227 */ 228 int psCompareS64(const void * a, const void*b);228 int psCompareS64(const void *a, const void *b); 229 229 230 230 /** Compare function of psU8 data. … … 234 234 * than, equal to, or greater than the second. 235 235 */ 236 int psCompareU8(const void * a, const void*b);236 int psCompareU8(const void *a, const void *b); 237 237 238 238 /** Compare function of psU16 data. … … 242 242 * than, equal to, or greater than the second. 243 243 */ 244 int psCompareU16(const void * a, const void*b);244 int psCompareU16(const void *a, const void *b); 245 245 246 246 /** Compare function of psU32 data. … … 250 250 * than, equal to, or greater than the second. 251 251 */ 252 int psCompareU32(const void * a, const void*b);252 int psCompareU32(const void *a, const void *b); 253 253 254 254 /** Compare function of psU64 data. … … 258 258 * than, equal to, or greater than the second. 259 259 */ 260 int psCompareU64(const void * a, const void*b);260 int psCompareU64(const void *a, const void *b); 261 261 262 262 /** Compare function of psF32 data. … … 266 266 * than, equal to, or greater than the second. 267 267 */ 268 int psCompareF32(const void * a, const void*b);268 int psCompareF32(const void *a, const void *b); 269 269 270 270 /** Compare function of psF64 data. … … 274 274 * than, equal to, or greater than the second. 275 275 */ 276 int psCompareF64(const void * a, const void*b);276 int psCompareF64(const void *a, const void *b); 277 277 278 278 /** Compare function of psS8 data. … … 282 282 * than, equal to, or less than the second. 283 283 */ 284 int psCompareDescendingS8(const void * a, const void*b);284 int psCompareDescendingS8(const void *a, const void *b); 285 285 286 286 /** Compare function of psS16 data. … … 290 290 * than, equal to, or less than the second. 291 291 */ 292 int psCompareDescendingS16(const void * a, const void*b);292 int psCompareDescendingS16(const void *a, const void *b); 293 293 294 294 /** Compare function of psS32 data. … … 298 298 * than, equal to, or less than the second. 299 299 */ 300 int psCompareDescendingS32(const void * a, const void*b);300 int psCompareDescendingS32(const void *a, const void *b); 301 301 302 302 /** Compare function of psS64 data. … … 306 306 * than, equal to, or less than the second. 307 307 */ 308 int psCompareDescendingS64(const void * a, const void*b);308 int psCompareDescendingS64(const void *a, const void *b); 309 309 310 310 /** Compare function of psU8 data. … … 314 314 * than, equal to, or less than the second. 315 315 */ 316 int psCompareDescendingU8(const void * a, const void*b);316 int psCompareDescendingU8(const void *a, const void *b); 317 317 318 318 /** Compare function of psU16 data. … … 322 322 * than, equal to, or less than the second. 323 323 */ 324 int psCompareDescendingU16(const void * a, const void*b);324 int psCompareDescendingU16(const void *a, const void *b); 325 325 326 326 /** Compare function of psU32 data. … … 330 330 * than, equal to, or lessg than the second. 331 331 */ 332 int psCompareDescendingU32(const void * a, const void*b);332 int psCompareDescendingU32(const void *a, const void *b); 333 333 334 334 /** Compare function of psU64 data. … … 338 338 * than, equal to, or lessg than the second. 339 339 */ 340 int psCompareDescendingU64(const void * a, const void*b);340 int psCompareDescendingU64(const void *a, const void *b); 341 341 342 342 /** Compare function of psF32 data. … … 346 346 * than, equal to, or lessg than the second. 347 347 */ 348 int psCompareDescendingF32(const void * a, const void*b);348 int psCompareDescendingF32(const void *a, const void *b); 349 349 350 350 /** Compare function of psF64 data. … … 354 354 * than, equal to, or lessg than the second. 355 355 */ 356 int psCompareDescendingF64(const void* a, const void* b); 357 358 356 int psCompareDescendingF64(const void *a, const void *b); 359 357 360 358 /// @} -
trunk/psLib/src/collections/psList.c
r1406 r1407 1 1 2 /** @file psList.c 2 3 * @brief Support for doubly linked lists … … 6 7 * @author Robert Daniel DeSonia, MHPCC 7 8 * 8 * @version $Revision: 1.1 3$ $Name: not supported by cvs2svn $9 * @date $Date: 2004-08-0 6 22:34:05$9 * @version $Revision: 1.14 $ $Name: not supported by cvs2svn $ 10 * @date $Date: 2004-08-07 00:06:06 $ 10 11 * 11 12 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 #include <stdbool.h> 16 17 #include <stdio.h> 17 #include <pthread.h> // we need a mutex to make this stuff thread safe.18 #include <pthread.h> // we need a mutex to make this stuff thread safe. 18 19 19 20 #include "psError.h" … … 24 25 #include "psLogMsg.h" 25 26 26 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head27 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail27 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head 28 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail 28 29 29 30 // private functions. 30 static psListElem* listGetIterator(psList* list); 31 static int listGetIteratorIndex(psList* list); 32 static void listSetIterator(psList *list, int where, bool lockList); 33 static void listFree(psList *list); 34 31 static psListElem *listGetIterator(psList * list); 32 static int listGetIteratorIndex(psList * list); 33 static void listSetIterator(psList * list, int where, bool lockList); 34 static void listFree(psList * list); 35 35 36 36 psList *psListAlloc(void *data) 37 37 { 38 38 psList *list = psAlloc(sizeof(psList)); 39 p_psMemSetDeallocator(list,(psFreeFcn)listFree); 39 40 p_psMemSetDeallocator(list, (psFreeFcn) listFree); 40 41 41 42 list->size = 0; … … 44 45 list->iterIndex = PS_LIST_HEAD; 45 46 46 pthread_mutex_init(&(list->lock), NULL)47 pthread_mutex_init(&(list->lock), NULL) 47 48 ; 48 49 … … 54 55 } 55 56 56 static void listFree(psList * list)57 static void listFree(psList * list) 57 58 { 58 59 if (list == NULL) { … … 63 64 ; 64 65 65 for (psListElem *ptr = list->head; ptr != NULL;) {66 for (psListElem * ptr = list->head; ptr != NULL;) { 66 67 psListElem *next = ptr->next; 67 68 … … 80 81 } 81 82 82 bool psListAdd(psList * list, void *data, int where)83 { 84 psListElem *position;85 psListElem *elem;83 bool psListAdd(psList * list, void *data, int where) 84 { 85 psListElem *position; 86 psListElem *elem; 86 87 int cursorIndex = 0; 87 88 … … 95 96 96 97 if (where <= PS_LIST_UNKNOWN) { 97 /// XXX What is the better way to communicate this failure to the caller? 98 psLogMsg(__func__,PS_LOG_WARN, 99 "The given insert location (%i) for psListAdd is invalid.", 100 where); 98 // / XXX What is the better way to communicate this failure to the caller? 99 psLogMsg(__func__, PS_LOG_WARN, "The given insert location (%i) for psListAdd is invalid.", where); 101 100 return false; 102 101 } … … 108 107 109 108 if (where > 0 && where > list->size) { 110 psLogMsg(__func__,PS_LOG_WARN, 111 "Invalid index %d (only %d elements in psList); assuming tail.", 112 where, list->size); 109 psLogMsg(__func__, PS_LOG_WARN, 110 "Invalid index %d (only %d elements in psList); assuming tail.", where, list->size); 113 111 where = PS_LIST_TAIL; 114 112 } … … 138 136 139 137 if (position == NULL) { 140 psError(__func__,"%s failed to move cursor to specified location (%d)",__func__,where); 141 position = list->head; // since we no list->size != 0, this must be non-NULL 142 } 143 138 psError(__func__, "%s failed to move cursor to specified location (%d)", __func__, where); 139 position = list->head; // since we no list->size != 0, this must be non-NULL 140 } 144 141 // insert our new element in front of the given position 145 142 elem->prev = position->prev; … … 147 144 position->prev = elem; 148 145 149 if (elem->prev == NULL) { // must be front of list146 if (elem->prev == NULL) { // must be front of list 150 147 list->head = elem; 151 148 } else { … … 167 164 168 165 /*****************************************************************************/ 166 169 167 /* 170 168 * Remove an element from a list 171 169 */ 172 bool psListRemove(psList * list, void *data,int which)173 { 174 psListElem *elem = NULL; // element to remove170 bool psListRemove(psList * list, void *data, int which) 171 { 172 psListElem *elem = NULL; // element to remove 175 173 int cursorIndex = 0; 176 174 177 175 if (list == NULL) { 178 psError(__func__, "list parameter found to be NULL in %s",__func__);176 psError(__func__, "list parameter found to be NULL in %s", __func__); 179 177 return false; 180 178 } 181 182 179 // get exclusive access to list so that other threads will not get in the way. 183 180 pthread_mutex_lock(&list->lock) … … 187 184 // search list for the data item. 188 185 189 int i = 0; // index 190 for (psListElem *ptr = list->head; ptr != NULL; ptr = ptr->next) { 186 int i = 0; // index 187 188 for (psListElem * ptr = list->head; ptr != NULL; ptr = ptr->next) { 191 189 if (ptr->data == data) { 192 190 which = i; … … 201 199 } 202 200 } 203 204 201 // position the list's cursor to the desired location 205 listSetIterator(list, which,false);202 listSetIterator(list, which, false); 206 203 elem = listGetIterator(list); 207 204 cursorIndex = listGetIteratorIndex(list); 208 205 209 206 if (elem == NULL) { 210 psError(__func__, "Couldn't position to given index (%d) to remove element from list.", which);207 psError(__func__, "Couldn't position to given index (%d) to remove element from list.", which); 211 208 return false; 212 209 } … … 214 211 list->size--; 215 212 216 if (elem->prev == NULL) { // head of list?213 if (elem->prev == NULL) { // head of list? 217 214 list->head = elem->next; 218 215 } else { … … 220 217 } 221 218 222 if (elem->next == NULL) { // tail of list?219 if (elem->next == NULL) { // tail of list? 223 220 list->tail = elem->prev; 224 221 … … 246 243 } 247 244 248 void psListSetIterator(psList * list, int where)249 { 250 listSetIterator(list, where,true);251 } 252 253 void listSetIterator(psList * list, int where, bool lockList)254 { 255 psListElem *cursor;245 void psListSetIterator(psList * list, int where) 246 { 247 listSetIterator(list, where, true); 248 } 249 250 void listSetIterator(psList * list, int where, bool lockList) 251 { 252 psListElem *cursor; 256 253 int position; 257 254 258 255 if (list == NULL) { 259 psError(__func__, "Unexpected null pointer for psList parameter (%s:%d).",__FILE__,__LINE__);256 psError(__func__, "Unexpected null pointer for psList parameter (%s:%d).", __FILE__, __LINE__); 260 257 return; 261 258 } … … 291 288 if (cursor != NULL) { 292 289 list->iter = cursor->prev; 293 list->iterIndex = position -1;290 list->iterIndex = position - 1; 294 291 } 295 292 break; … … 301 298 if (cursor != NULL) { 302 299 list->iter = cursor->next; 303 list->iterIndex = position +1;300 list->iterIndex = position + 1; 304 301 } 305 302 break; … … 309 306 310 307 default: 311 if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above312 psError(__func__, "Can't move to an unknown position. Not moving the iterator position.");308 if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above 309 psError(__func__, "Can't move to an unknown position. Not moving the iterator position."); 313 310 } else { 314 311 cursor = listGetIterator(list); 315 if (cursor == NULL) { // reset the iterator if it is invalid312 if (cursor == NULL) { // reset the iterator if it is invalid 316 313 list->iter = ITER_INIT_HEAD; 317 314 list->iterIndex = 0; … … 321 318 322 319 if (where < position) { 323 int diff = position-where; 324 for (int count=0;count < diff; count++) { 325 listSetIterator(list,PS_LIST_PREVIOUS,false); 320 int diff = position - where; 321 322 for (int count = 0; count < diff; count++) { 323 listSetIterator(list, PS_LIST_PREVIOUS, false); 326 324 } 327 325 } else { 328 int diff = where-position; 329 for (int count=0;count < diff; count++) { 330 listSetIterator(list,PS_LIST_NEXT,false); 326 int diff = where - position; 327 328 for (int count = 0; count < diff; count++) { 329 listSetIterator(list, PS_LIST_NEXT, false); 331 330 } 332 331 } … … 341 340 } 342 341 343 psListElem * listGetIterator(psList* list)342 psListElem *listGetIterator(psList * list) 344 343 { 345 344 if (list == NULL) { … … 349 348 if (list->iter == ITER_INIT_HEAD) { 350 349 return list->head; 351 } else 352 if (list->iter == ITER_INIT_TAIL) { 353 return list->tail; 354 } else { 355 return list->iter; 356 } 357 } 358 359 int listGetIteratorIndex(psList* list) 350 } else if (list->iter == ITER_INIT_TAIL) { 351 return list->tail; 352 } else { 353 return list->iter; 354 } 355 } 356 357 int listGetIteratorIndex(psList * list) 360 358 { 361 359 if (list->iter == ITER_INIT_HEAD) { 362 360 return 0; 363 } else 364 if (list->iter == ITER_INIT_TAIL) { 365 return list->size-1; 366 } else { 367 return list->iterIndex; 368 } 369 } 370 371 void* psListGet(psList* list,int which) 372 { 373 psListElem* element; 374 375 psListSetIterator(list,which); 361 } else if (list->iter == ITER_INIT_TAIL) { 362 return list->size - 1; 363 } else { 364 return list->iterIndex; 365 } 366 } 367 368 void *psListGet(psList * list, int which) 369 { 370 psListElem *element; 371 372 psListSetIterator(list, which); 376 373 element = listGetIterator(list); 377 374 … … 382 379 } 383 380 } 381 384 382 /* 385 383 * and now return the previous/next element of the list 386 384 */ 387 void *psListGetNext(psList * list)385 void *psListGetNext(psList * list) 388 386 { 389 387 return psListGet(list, PS_LIST_NEXT); 390 388 } 391 389 392 void *psListGetPrevious(psList * list)390 void *psListGetPrevious(psList * list) 393 391 { 394 392 return psListGet(list, PS_LIST_PREVIOUS); 395 393 } 396 394 397 void *psListGetCurrent(psList * list)395 void *psListGetCurrent(psList * list) 398 396 { 399 397 return psListGet(list, PS_LIST_CURRENT); … … 403 401 * Convert a psList to/from a psVoidPtrArray 404 402 */ 405 psArray * psListToArray(psList* restrict list)406 { 407 psListElem *ptr;403 psArray *psListToArray(psList * restrict list) 404 { 405 psListElem *ptr; 408 406 unsigned int n; 409 psArray *restrict arr;407 psArray *restrict arr; 410 408 411 409 if (list == NULL) { … … 431 429 } 432 430 433 psList * psArrayToList(psArray* arr)431 psList *psArrayToList(psArray * arr) 434 432 { 435 433 unsigned int n; 436 psList * list;// list of elements434 psList *list; // list of elements 437 435 438 436 if (arr == NULL) { … … 443 441 n = arr->n; 444 442 for (int i = 0; i < n; i++) { 445 psListAdd(list, arr->data[i],PS_LIST_TAIL);443 psListAdd(list, arr->data[i], PS_LIST_TAIL); 446 444 } 447 445 … … 449 447 } 450 448 451 452 psList* psListSort(psList* list, psComparePtrFcn compare) 453 { 454 psArray* arr; 449 psList *psListSort(psList * list, psComparePtrFcn compare) 450 { 451 psArray *arr; 452 455 453 if (list == NULL) { 456 454 return NULL; 457 455 } 458 459 456 // convert to indexable vector for use by qsort. 460 457 arr = psListToArray(list); 461 458 psFree(list); 462 459 463 arr = psArraySort(arr, compare);460 arr = psArraySort(arr, compare); 464 461 465 462 // convert back to linked list -
trunk/psLib/src/collections/psList.h
r1228 r1407 1 1 #if !defined(PS_LIST_H) 2 # define PS_LIST_H2 # define PS_LIST_H 3 3 4 4 /** @file psList.h … … 10 10 * @ingroup LinkedList 11 11 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-0 7-15 22:18:02$12 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 14 14 * 15 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 16 */ 17 17 18 # include <pthread.h> // we need a mutex to make this stuff thread safe.19 # include <stdbool.h> // we use the bool type.18 # include <pthread.h> // we need a mutex to make this stuff thread safe. 19 # include <stdbool.h> // we use the bool type. 20 20 21 # include "psCompare.h"22 # include "psArray.h"21 # include "psCompare.h" 22 # include "psArray.h" 23 23 24 24 /** @addtogroup LinkedList … … 33 33 */ 34 34 enum { 35 PS_LIST_HEAD = 0, ///< at head36 PS_LIST_TAIL = -1, ///< at tail37 PS_LIST_PREVIOUS = -2, ///< previous element38 PS_LIST_CURRENT = -3, ///< current element39 PS_LIST_NEXT = -4, ///< next element40 PS_LIST_UNKNOWN = -5 ///< unknown position (should be last in enum list)35 PS_LIST_HEAD = 0, // /< at head 36 PS_LIST_TAIL = -1, // /< at tail 37 PS_LIST_PREVIOUS = -2, // /< previous element 38 PS_LIST_CURRENT = -3, // /< current element 39 PS_LIST_NEXT = -4, // /< next element 40 PS_LIST_UNKNOWN = -5 // /< unknown position (should be last in enum list) 41 41 }; 42 42 … … 44 44 typedef struct psListElem 45 45 { 46 struct psListElem *prev; ///< previous link in list47 struct psListElem *next; ///< next link in list48 void *data; ///< real data item46 struct psListElem *prev; // /< previous link in list 47 struct psListElem *next; // /< next link in list 48 void *data; // /< real data item 49 49 } 50 50 psListElem; … … 57 57 typedef struct 58 58 { 59 unsigned int size; ///< number of elements on list60 psListElem * head; ///< first element on list (may be NULL)61 psListElem * tail; ///< last element on list (may be NULL)62 psListElem * iter; ///< iteration cursor63 unsigned int iterIndex; ///< the numeric position of the iteration cursor in the list64 pthread_mutex_t lock; ///< mutex to lock a node during changes59 unsigned int size; // /< number of elements on list 60 psListElem *head; // /< first element on list (may be NULL) 61 psListElem *tail; // /< last element on list (may be NULL) 62 psListElem *iter; // /< iteration cursor 63 unsigned int iterIndex; // /< the numeric position of the iteration cursor in the list 64 pthread_mutex_t lock; // /< mutex to lock a node during changes 65 65 } 66 66 psList; … … 70 70 * @return psList* A new psList object. 71 71 */ 72 psList* psListAlloc( 73 void *data 74 ///< initial data item; may be NULL if no an empty psList is desired 75 ) 72 psList *psListAlloc(void *data 73 // /< initial data item; may be NULL if no an empty psList is desired 74 ) 76 75 ; 77 76 … … 81 80 * NULL, the return value will also be NULL. 82 81 */ 83 bool psListAdd( 84 psList* restrict list, ///< list to add to (if NULL, nothing is done) 85 void* data, ///< data item to add. If NULL, list is not modified. 86 int where ///< index, PS_LIST_HEAD, PS_LIST_TAIL, or numbered location. 87 ); 82 bool psListAdd(psList * restrict list, // /< list to add to (if NULL, nothing is done) 83 void *data, // /< data item to add. If NULL, list is not modified. 84 int where // /< index, PS_LIST_HEAD, PS_LIST_TAIL, or numbered location. 85 ); 88 86 89 87 /** Remove an item from a list. If which parameter is PS_LIST_UNKNOWN, … … 91 89 * @return bool TRUE if element is successfully removed, otherwise FALSE. 92 90 */ 93 bool psListRemove( 94 psList* restrict list, 95 ///< list to remove element from 96 void *data, 97 ///< if which is PS_LIST_UNKNOWN, data item to find and remove, otherwise this is ignored. 98 int which 99 ///< index of item, or PS_LIST_UNKNOWN, PS_LIST_NEXT, PS_LIST_PREV, or numbered location. 100 ); 91 bool psListRemove(psList * restrict list, 92 // /< list to remove element from 93 void *data, 94 // /< if which is PS_LIST_UNKNOWN, data item to find and remove, otherwise this is ignored. 95 int which 96 // /< index of item, or PS_LIST_UNKNOWN, PS_LIST_NEXT, PS_LIST_PREV, or numbered location. 97 ); 101 98 102 99 /** Retrieve an item from a list. … … 107 104 * NULL is returned. 108 105 */ 109 void* psListGet( 110 psList* restrict list, ///< list to retrieve element from 111 int which ///< index number, or PS_LIST_NEXT, PS_LIST_PREV, PS_LIST_UNKNOWN 112 ); 106 void *psListGet(psList * restrict list, // /< list to retrieve element from 107 int which // /< index number, or PS_LIST_NEXT, PS_LIST_PREV, PS_LIST_UNKNOWN 108 ); 113 109 114 110 /** Set the iterator of the list to a given position. If where is invalid the … … 116 112 * 117 113 */ 118 void psListSetIterator( 119 psList* restrict list, ///< list to retrieve element from 120 int where ///< index number, PS_LIST_HEAD, or PS_LIST_TAIL 121 ); 114 void psListSetIterator(psList * restrict list, // /< list to retrieve element from 115 int where // /< index number, PS_LIST_HEAD, or PS_LIST_TAIL 116 ); 122 117 123 118 /** Get next element relative to the iterator. This also moves the iterator to … … 128 123 * parameter was NULL. 129 124 */ 130 void* psListGetNext( 131 psList* restrict list ///< list to retrieve element from 132 ); 125 void *psListGetNext(psList * restrict list // /< list to retrieve element from 126 ); 133 127 134 128 /** Get current element according to the psList's iterator cursor. This does … … 139 133 * iterator is not valid or list parameter was NULL. 140 134 */ 141 void* psListGetCurrent( 142 psList* restrict list ///< list to retrieve element from 143 ); 135 void *psListGetCurrent(psList * restrict list // /< list to retrieve element from 136 ); 144 137 145 138 /** Get previous element relative to list's iterator. This also moves the … … 150 143 * parameter was NULL. 151 144 */ 152 void* psListGetPrevious( 153 psList* restrict list ///< list to retrieve element from 154 ); 145 void *psListGetPrevious(psList * restrict list // /< list to retrieve element from 146 ); 155 147 156 148 /** Convert a linked list to an array … … 159 151 * or NULL if the given dlist parameter is NULL. 160 152 */ 161 psArray* psListToArray( 162 psList *dlist ///< List to convert 163 ); 153 psArray *psListToArray(psList * dlist // /< List to convert 154 ); 164 155 165 156 /** Convert array to a doubly-linked list … … 168 159 * or NULL is the given arr parameter is NULL. 169 160 */ 170 psList* psArrayToList( 171 psArray* arr ///< vector to convert 172 ); 161 psList *psArrayToList(psArray * arr // /< vector to convert 162 ); 173 163 174 psList * psListSort(psList* list, psComparePtrFcn compare);164 psList *psListSort(psList * list, psComparePtrFcn compare); 175 165 176 166 /// @} End of DataGroup Functions 177 167 178 168 #endif 179 -
trunk/psLib/src/collections/psMetadata.c
r1406 r1407 1 1 2 /** @file psMetadata.c 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 #include<stdio.h> … … 34 37 #include "psString.h" 35 38 36 37 39 /******************************************************************************/ 40 38 41 /* DEFINE STATEMENTS */ 42 39 43 /******************************************************************************/ 40 44 … … 56 60 57 61 /******************************************************************************/ 62 58 63 /* TYPE DEFINITIONS */ 64 59 65 /******************************************************************************/ 60 66 … … 62 68 63 69 /*****************************************************************************/ 70 64 71 /* GLOBAL VARIABLES */ 72 65 73 /*****************************************************************************/ 66 74 … … 68 76 69 77 /*****************************************************************************/ 78 70 79 /* FILE STATIC VARIABLES */ 80 71 81 /*****************************************************************************/ 72 82 … … 74 84 75 85 /*****************************************************************************/ 86 76 87 /* FUNCTION IMPLEMENTATION - LOCAL */ 77 /*****************************************************************************/ 78 static void metadataItemFree( psMetadataItem *metadataItem ) 88 89 /*****************************************************************************/ 90 static void metadataItemFree(psMetadataItem * metadataItem) 79 91 { 80 92 psMetadataType type; … … 82 94 type = metadataItem->type; 83 95 84 if (metadataItem == NULL) {85 return ;86 } 87 88 psFree( metadataItem->name);89 psFree( metadataItem->comment);90 psFree( metadataItem->items);91 92 if (type == PS_META_STR ||96 if (metadataItem == NULL) { 97 return; 98 } 99 100 psFree(metadataItem->name); 101 psFree(metadataItem->comment); 102 psFree(metadataItem->items); 103 104 if (type == PS_META_STR || 93 105 type == PS_META_IMG || 94 type == PS_META_JPEG || 95 type == PS_META_PNG || 96 type == PS_META_ASTROM || 97 type == PS_META_UNKNOWN) { 98 psFree( metadataItem->data.V ); 99 } 100 } 101 102 static void metadataFree( psMetadata *metadata ) 103 { 104 if(metadata == NULL) { 105 return ; 106 } 107 psFree( metadata->list ); 108 psFree( metadata->table ); 109 } 110 111 /*****************************************************************************/ 106 type == PS_META_JPEG || type == PS_META_PNG || type == PS_META_ASTROM || type == PS_META_UNKNOWN) { 107 psFree(metadataItem->data.V); 108 } 109 } 110 111 static void metadataFree(psMetadata * metadata) 112 { 113 if (metadata == NULL) { 114 return; 115 } 116 psFree(metadata->list); 117 psFree(metadata->table); 118 } 119 120 /*****************************************************************************/ 121 112 122 /* FUNCTION IMPLEMENTATION - PUBLIC */ 113 /*****************************************************************************/ 114 115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... ) 123 124 /*****************************************************************************/ 125 126 psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...) 116 127 { 117 128 va_list argPtr; … … 119 130 120 131 // Get the variable list parameters to pass to allocation function 121 va_start( argPtr, comment);132 va_start(argPtr, comment); 122 133 123 134 // Call metadata item allocation 124 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);135 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 125 136 126 137 // Clean up stack after variable arguement has been used 127 va_end( argPtr);138 va_end(argPtr); 128 139 129 140 return metadataItem; 130 141 } 131 142 132 psMetadataItem *psMetadataItemAllocV( const char *name, psMetadataType type, const char *comment, va_list argPtr )133 { 134 psMetadataItem * metadataItem = NULL; 135 136 if(name == NULL) { 137 psError( __func__, "Null value for name not allowed" );138 return NULL;139 }140 143 psMetadataItem *psMetadataItemAllocV(const char *name, psMetadataType type, const char *comment, 144 va_list argPtr) 145 { 146 psMetadataItem *metadataItem = NULL; 147 148 if (name == NULL) { 149 psError(__func__, "Null value for name not allowed"); 150 return NULL; 151 } 141 152 // Allocate metadata item 142 metadataItem = ( psMetadataItem * ) psAlloc( sizeof( psMetadataItem ) ); 143 if(metadataItem == NULL) { 144 psAbort( __func__, "Failed to allocate memory" ); 145 } 146 153 metadataItem = (psMetadataItem *) psAlloc(sizeof(psMetadataItem)); 154 if (metadataItem == NULL) { 155 psAbort(__func__, "Failed to allocate memory"); 156 } 147 157 // Set deallocator 148 p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree);158 p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree); 149 159 150 160 // Allocate and set metadata item comment 151 metadataItem->comment = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);152 if (comment == NULL) {161 metadataItem->comment = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 162 if (comment == NULL) { 153 163 // Per SDRS, null isn't allowed, must use "" instead 154 strncpy( metadataItem->comment, "", MAX_STRING_LENGTH);164 strncpy(metadataItem->comment, "", MAX_STRING_LENGTH); 155 165 } else { 156 strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH);166 strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH); 157 167 } 158 168 159 169 // Set metadata item unique id 160 *( int* ) ( &metadataItem->id) = ++metadataId;170 *(int *)(&metadataItem->id) = ++metadataId; 161 171 162 172 // Set metadata item type … … 164 174 165 175 // Set metadata item value 166 switch (type) {176 switch (type) { 167 177 case PS_META_BOOL: 168 metadataItem->data.B = ( bool ) va_arg( argPtr, int ); 178 metadataItem->data.B = (bool) va_arg(argPtr, int); 179 169 180 break; 170 181 case PS_META_S32: 171 metadataItem->data.S32 = va_arg( argPtr, psS32);182 metadataItem->data.S32 = va_arg(argPtr, psS32); 172 183 break; 173 184 case PS_META_F32: 174 metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64);185 metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64); 175 186 break; 176 187 case PS_META_F64: 177 metadataItem->data.F64 = va_arg( argPtr, psF64);188 metadataItem->data.F64 = va_arg(argPtr, psF64); 178 189 break; 179 190 case PS_META_STR: 180 metadataItem->data.V = psStringNCopy( va_arg( argPtr, char* ), MAX_STRING_LENGTH ); 191 metadataItem->data.V = psStringNCopy(va_arg(argPtr, char *), MAX_STRING_LENGTH); 192 181 193 break; 182 194 case PS_META_IMG: … … 186 198 case PS_META_UNKNOWN: 187 199 default: 188 psError( __func__, "Invalid psMetadataType: %d", type);200 psError(__func__, "Invalid psMetadataType: %d", type); 189 201 } 190 202 191 203 // Allocate and set metadata item name 192 metadataItem->name = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);193 vsprintf( metadataItem->name, name, argPtr);204 metadataItem->name = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 205 vsprintf(metadataItem->name, name, argPtr); 194 206 195 207 // Allocate metadata items with same name. 196 metadataItem->items = psListAlloc( NULL);208 metadataItem->items = psListAlloc(NULL); 197 209 198 210 return metadataItem; 199 211 } 200 212 201 psMetadata *psMetadataAlloc( void)202 { 203 psList * list = NULL;213 psMetadata *psMetadataAlloc(void) 214 { 215 psList *list = NULL; 204 216 psHash *table = NULL; 205 217 psMetadata *metadata = NULL; 206 218 207 219 // Allocate metadata 208 metadata = ( psMetadata * ) psAlloc( sizeof( psMetadata ) ); 209 if(metadata == NULL) { 210 psAbort( __func__, "Failed to allocate metadata" ); 211 } 212 220 metadata = (psMetadata *) psAlloc(sizeof(psMetadata)); 221 if (metadata == NULL) { 222 psAbort(__func__, "Failed to allocate metadata"); 223 } 213 224 // Set deallocator 214 p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree);225 p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree); 215 226 216 227 // Allocate metadata's internal containers 217 list = ( psList * ) psListAlloc( NULL);218 if (list == NULL) {219 psAbort( __func__, "Failed to allocate list");220 } 221 222 table = ( psHash * ) psHashAlloc( 10);223 if (table == NULL) {224 psAbort( __func__, "Failed to allocate table");228 list = (psList *) psListAlloc(NULL); 229 if (list == NULL) { 230 psAbort(__func__, "Failed to allocate list"); 231 } 232 233 table = (psHash *) psHashAlloc(10); 234 if (table == NULL) { 235 psAbort(__func__, "Failed to allocate table"); 225 236 } 226 237 … … 231 242 } 232 243 233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem)234 { 235 char * key = NULL;244 bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem) 245 { 246 char *key = NULL; 236 247 psHash *mdTable = NULL; 237 248 psList *mdList = NULL; … … 239 250 psMetadataType type = PS_META_ITEM_SET; 240 251 241 if (md == NULL) {242 psError( __func__, "Null metadata collection not allowed");243 return false; 244 } 245 246 if (metadataItem == NULL) {247 psError( __func__, "Null metadata item not allowed");252 if (md == NULL) { 253 psError(__func__, "Null metadata collection not allowed"); 254 return false; 255 } 256 257 if (metadataItem == NULL) { 258 psError(__func__, "Null metadata item not allowed"); 248 259 return false; 249 260 } … … 252 263 253 264 mdTable = md->table; 254 if (mdTable == NULL) {255 psError( __func__, "Null metadata table not allowed");256 return false; 257 } 258 259 mdList = md->list; 260 if (mdList == NULL) {261 psError( __func__, "Null metadata list not allowed");265 if (mdTable == NULL) { 266 psError(__func__, "Null metadata table not allowed"); 267 return false; 268 } 269 270 mdList = md->list; 271 if (mdList == NULL) { 272 psError(__func__, "Null metadata list not allowed"); 262 273 return false; 263 274 } 264 275 265 276 key = metadataItem->name; 266 if(key == NULL) { 267 psError( __func__, "Null key item not allowed" ); 268 return false; 269 } 270 277 if (key == NULL) { 278 psError(__func__, "Null key item not allowed"); 279 return false; 280 } 271 281 // Check if key is already in table 272 value = ( psMetadataItem* ) psHashLookup( mdTable, key);273 if (value != NULL && type != PS_META_ITEM_SET) {282 value = (psMetadataItem *) psHashLookup(mdTable, key); 283 if (value != NULL && type != PS_META_ITEM_SET) { 274 284 275 285 // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so 276 286 // add the new metadata item to hash as a child of the existing metadata item folder node. 277 if(!psListAdd( value->items, metadataItem, where )) { 278 psError( __func__, "Couldn't add metadata item to items list. Name: %s", 279 metadataItem->name ); 287 if (!psListAdd(value->items, metadataItem, where)) { 288 psError(__func__, "Couldn't add metadata item to items list. Name: %s", metadataItem->name); 280 289 return false; 281 290 } 282 } else 283 if(value != NULL) { 284 285 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 286 // it will wipe out existing node. 287 psError( __func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 288 metadataItem->name ); 291 } else if (value != NULL) { 292 293 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 294 // it will wipe out existing node. 295 psError(__func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 296 metadataItem->name); 297 return false; 298 } else { 299 300 // Duplicate key not found. Add new metadata item to metadata collection's hash 301 if (!psHashAdd(mdTable, key, metadataItem)) { 302 psError(__func__, "Couldn't add metadata item to metadata collection table. Name: %s", 303 metadataItem->name); 289 304 return false; 290 } else { 291 292 // Duplicate key not found. Add new metadata item to metadata collection's hash 293 if(!psHashAdd( mdTable, key, metadataItem )) { 294 psError( __func__, "Couldn't add metadata item to metadata collection table. Name: %s", 295 metadataItem->name ); 296 return false; 297 } 298 } 305 } 306 } 299 307 300 308 // Add all items to metadata collection's list, even if they have the same metadata item names 301 if (!psListAdd( md->list, metadataItem, where)) {302 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",303 metadataItem->name);309 if (!psListAdd(md->list, metadataItem, where)) { 310 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 311 metadataItem->name); 304 312 return false; 305 313 } … … 308 316 } 309 317 310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,311 const char *comment, ...)318 bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type, 319 const char *comment, ...) 312 320 { 313 321 va_list argPtr; 314 322 psMetadataItem *metadataItem = NULL; 315 323 316 va_start( argPtr, comment);317 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);318 va_end( argPtr);319 320 if (!psMetadataAddItem( md, where, metadataItem)) {321 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",322 metadataItem->name);323 psFree( metadataItem);324 return false; 325 } 326 327 // Decrement reference count, since the metadata item is now in metadata collection and no longer neededhere328 psMemDecrRefCounter( metadataItem);324 va_start(argPtr, comment); 325 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 326 va_end(argPtr); 327 328 if (!psMetadataAddItem(md, where, metadataItem)) { 329 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 330 metadataItem->name); 331 psFree(metadataItem); 332 return false; 333 } 334 // Decrement reference count, since the metadata item is now in metadata collection and no longer needed 335 // here 336 psMemDecrRefCounter(metadataItem); 329 337 330 338 return true; 331 339 } 332 340 333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key)341 bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key) 334 342 { 335 343 int numChildren = 0; … … 340 348 341 349 mdList = md->list; 342 if (mdList == NULL) {343 psError( __func__, "Null metadata list not allowed");350 if (mdList == NULL) { 351 psError(__func__, "Null metadata list not allowed"); 344 352 return false; 345 353 } 346 354 347 355 mdTable = md->table; 348 if(mdTable == NULL) { 349 psError( __func__, "Null metadata table not allowed" ); 350 return false; 351 } 352 356 if (mdTable == NULL) { 357 psError(__func__, "Null metadata table not allowed"); 358 return false; 359 } 353 360 // Select removal by key or index 354 if (key != NULL) {361 if (key != NULL) { 355 362 356 363 // Remove by key name 357 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);358 if (entry == NULL) {359 psError( __func__, "Couldn't find metadata item remove. Name: %s", key);364 entry = (psMetadataItem *) psHashLookup(mdTable, key); 365 if (entry == NULL) { 366 psError(__func__, "Couldn't find metadata item remove. Name: %s", key); 360 367 return false; 361 368 } 362 369 363 370 numChildren = entry->items->size; 364 if (entry->type == PS_META_ITEM_SET && numChildren > 0) {371 if (entry->type == PS_META_ITEM_SET && numChildren > 0) { 365 372 366 373 // Table entry has children. Entry and children must be removed from metadata collection's list 367 psListSetIterator( mdList, PS_LIST_HEAD);368 entryChild = psListGetCurrent( mdList);369 while (entryChild != NULL) {370 if (!psListRemove( entry->items, entryChild, PS_LIST_UNKNOWN)) {371 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);374 psListSetIterator(mdList, PS_LIST_HEAD); 375 entryChild = psListGetCurrent(mdList); 376 while (entryChild != NULL) { 377 if (!psListRemove(entry->items, entryChild, PS_LIST_UNKNOWN)) { 378 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 372 379 return false; 373 380 } 374 entryChild = psListGetNext( entry->items);381 entryChild = psListGetNext(entry->items); 375 382 } 376 383 } 377 378 384 // Remove entry from metadata collection's list 379 if (!psListRemove( mdList, entry, PS_LIST_UNKNOWN)) {380 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);385 if (!psListRemove(mdList, entry, PS_LIST_UNKNOWN)) { 386 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 381 387 return false; 382 388 } 383 384 389 // Remove entry from metadata collection's table 385 if (!psHashRemove( mdTable, key)) {386 psError( __func__, "Couldn't remove metadata item from table. Name: %s", key);390 if (!psHashRemove(mdTable, key)) { 391 psError(__func__, "Couldn't remove metadata item from table. Name: %s", key); 387 392 return false; 388 393 } … … 390 395 391 396 // Remove by index 392 entry = psListGet( mdList, where);393 if (entry == NULL) {394 psError( __func__, "Couldn't find metadata item from list. Index: %d", where);397 entry = psListGet(mdList, where); 398 if (entry == NULL) { 399 psError(__func__, "Couldn't find metadata item from list. Index: %d", where); 395 400 return false; 396 401 } 397 402 398 403 key = entry->name; 399 if (key == NULL) {400 psError( __func__, "Null key name not allowed. Index: %d", where);404 if (key == NULL) { 405 psError(__func__, "Null key name not allowed. Index: %d", where); 401 406 return false; 402 407 } 403 404 408 // Use recursive remove, now that key is known 405 psMetadataRemove( md, PS_LIST_UNKNOWN, key);409 psMetadataRemove(md, PS_LIST_UNKNOWN, key); 406 410 } 407 411 … … 409 413 } 410 414 411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key)412 { 413 psHash * mdTable = NULL;415 psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key) 416 { 417 psHash *mdTable = NULL; 414 418 psMetadataItem *entry = NULL; 415 419 416 420 mdTable = md->table; 417 if (mdTable == NULL) {418 psError( __func__, "Null metadata table not allowed");419 return NULL; 420 } 421 422 if (key == NULL) {423 psError( __func__, "Null key name not allowed");424 return NULL; 425 } 426 427 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);428 if (entry == NULL) {429 psError( __func__, "Could not find metadata item with given key. Key: %s", key);421 if (mdTable == NULL) { 422 psError(__func__, "Null metadata table not allowed"); 423 return NULL; 424 } 425 426 if (key == NULL) { 427 psError(__func__, "Null key name not allowed"); 428 return NULL; 429 } 430 431 entry = (psMetadataItem *) psHashLookup(mdTable, key); 432 if (entry == NULL) { 433 psError(__func__, "Could not find metadata item with given key. Key: %s", key); 430 434 return NULL; 431 435 } … … 434 438 } 435 439 436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where)437 { 438 psList * mdList = NULL;440 psMetadataItem *psMetadataGet(psMetadata * restrict md, int where) 441 { 442 psList *mdList = NULL; 439 443 psMetadataItem *entry = NULL; 440 444 441 445 mdList = md->list; 442 if (mdList == NULL) {443 psError( __func__, "Null metadata list not allowed");444 return NULL; 445 } 446 447 entry = ( psMetadataItem* ) psListGet( mdList, where);448 if (entry == NULL) {449 psError( __func__, "Couldn't find metadata item with given index. Index: %d", where);446 if (mdList == NULL) { 447 psError(__func__, "Null metadata list not allowed"); 448 return NULL; 449 } 450 451 entry = (psMetadataItem *) psListGet(mdList, where); 452 if (entry == NULL) { 453 psError(__func__, "Couldn't find metadata item with given index. Index: %d", where); 450 454 return NULL; 451 455 } … … 454 458 } 455 459 456 bool psMetadataSetIterator( psMetadata *restrict md, int where)457 { 458 psList * mdList = NULL;459 460 mdList = md->list; 461 if (mdList == NULL) {462 psError( __func__, "Null metadata list not allowed");463 return false; 464 } 465 466 psListSetIterator( mdList, where);460 bool psMetadataSetIterator(psMetadata * restrict md, int where) 461 { 462 psList *mdList = NULL; 463 464 mdList = md->list; 465 if (mdList == NULL) { 466 psError(__func__, "Null metadata list not allowed"); 467 return false; 468 } 469 470 psListSetIterator(mdList, where); 467 471 468 472 return true; 469 473 } 470 474 471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which)472 { 473 psList * mdList = NULL;475 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which) 476 { 477 psList *mdList = NULL; 474 478 psMetadataItem *entry = NULL; 475 479 476 480 mdList = md->list; 477 if (mdList == NULL) {478 psError( __func__, "Null metadata list not allowed");479 return NULL; 480 } 481 482 mdList = md->list; 483 if (mdList == NULL) {484 psError( __func__, "Null metadata list not allowed");485 return NULL; 486 } 487 488 psListSetIterator( mdList, which);489 entry = psListGetCurrent( mdList);490 while (entry != NULL) {491 if (!strncmp( match, entry->name, strlen( match ))) {481 if (mdList == NULL) { 482 psError(__func__, "Null metadata list not allowed"); 483 return NULL; 484 } 485 486 mdList = md->list; 487 if (mdList == NULL) { 488 psError(__func__, "Null metadata list not allowed"); 489 return NULL; 490 } 491 492 psListSetIterator(mdList, which); 493 entry = psListGetCurrent(mdList); 494 while (entry != NULL) { 495 if (!strncmp(match, entry->name, strlen(match))) { 492 496 493 497 // Match found 494 498 return entry; 495 499 } 496 entry = psListGetNext( mdList);500 entry = psListGetNext(mdList); 497 501 } 498 502 499 503 // Match not found 500 if (entry == NULL) {501 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);504 if (entry == NULL) { 505 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 502 506 } 503 507 … … 505 509 } 506 510 507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which)508 { 509 psList * mdList = NULL;511 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which) 512 { 513 psList *mdList = NULL; 510 514 psMetadataItem *entry = NULL; 511 515 512 516 mdList = md->list; 513 if (mdList == NULL) {514 psError( __func__, "Null metadata list not allowed");515 return NULL; 516 } 517 518 mdList = md->list; 519 if (mdList == NULL) {520 psError( __func__, "Null metadata list not allowed");521 return NULL; 522 } 523 524 psListSetIterator( mdList, which);525 entry = psListGetCurrent( mdList);526 while (entry != NULL) {527 if (!strncmp( match, entry->name, strlen( match ))) {517 if (mdList == NULL) { 518 psError(__func__, "Null metadata list not allowed"); 519 return NULL; 520 } 521 522 mdList = md->list; 523 if (mdList == NULL) { 524 psError(__func__, "Null metadata list not allowed"); 525 return NULL; 526 } 527 528 psListSetIterator(mdList, which); 529 entry = psListGetCurrent(mdList); 530 while (entry != NULL) { 531 if (!strncmp(match, entry->name, strlen(match))) { 528 532 529 533 // Match found 530 534 return entry; 531 535 } 532 entry = psListGetPrevious( mdList);536 entry = psListGetPrevious(mdList); 533 537 } 534 538 535 539 // Match not found 536 if (entry == NULL) {537 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);540 if (entry == NULL) { 541 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 538 542 } 539 543 … … 541 545 } 542 546 543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem)547 void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem) 544 548 { 545 549 psMetadataType type; 546 550 547 if (fd == NULL) {548 psError( __func__, "Null file descriptor not allowed");549 return ;550 } 551 552 if (format == NULL) {553 psError( __func__, "Null format not allowed");554 return ;555 } 556 557 if (metadataItem == NULL) {558 psError( __func__, "Null metadata not allowed");559 return ;551 if (fd == NULL) { 552 psError(__func__, "Null file descriptor not allowed"); 553 return; 554 } 555 556 if (format == NULL) { 557 psError(__func__, "Null format not allowed"); 558 return; 559 } 560 561 if (metadataItem == NULL) { 562 psError(__func__, "Null metadata not allowed"); 563 return; 560 564 } 561 565 562 566 type = metadataItem->type; 563 567 564 switch (type) {568 switch (type) { 565 569 case PS_META_BOOL: 566 fprintf( fd, format, metadataItem->data.B);570 fprintf(fd, format, metadataItem->data.B); 567 571 break; 568 572 case PS_META_S32: 569 fprintf( fd, format, metadataItem->data.S32);573 fprintf(fd, format, metadataItem->data.S32); 570 574 break; 571 575 case PS_META_F32: 572 fprintf( fd, format, metadataItem->data.F32);576 fprintf(fd, format, metadataItem->data.F32); 573 577 break; 574 578 case PS_META_F64: 575 fprintf( fd, format, metadataItem->data.F64);579 fprintf(fd, format, metadataItem->data.F64); 576 580 break; 577 581 case PS_META_STR: 578 fprintf( fd, format, metadataItem->data.V);582 fprintf(fd, format, metadataItem->data.V); 579 583 break; 580 584 case PS_META_ITEM_SET: … … 585 589 case PS_META_UNKNOWN: 586 590 default: 587 psError( __func__, " Invalid psMetadataType to print: %d", type);588 } 589 } 590 591 psMetadata *psMetadataFReadHeader( psMetadata *output, char *extName, int extNum, fitsfile *fd)591 psError(__func__, " Invalid psMetadataType to print: %d", type); 592 } 593 } 594 595 psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd) 592 596 { 593 597 bool tempBool; 594 598 bool success; 595 599 char keyType; 596 char keyName[ FITS_LINE_SIZE];597 char keyValue[ FITS_LINE_SIZE];598 char keyComment[ FITS_LINE_SIZE];599 char fitsErr[ MAX_STRING_LENGTH];600 char keyName[FITS_LINE_SIZE]; 601 char keyValue[FITS_LINE_SIZE]; 602 char keyComment[FITS_LINE_SIZE]; 603 char fitsErr[MAX_STRING_LENGTH]; 600 604 int i; 601 605 int hduType = 0; … … 605 609 psMetadataType metadataItemType; 606 610 607 if(fd == NULL) { 608 psError( __func__, "Null FITS file descriptor not allowed" ); 609 return NULL; 610 } 611 612 if(extName == NULL && extNum == 0) { 613 psError( __func__, "Null extName and extNum = 0 not allowed" ); 614 return NULL; 615 } else 616 if(extName && extNum) { 617 psError( __func__, "Both extName and extNum arguments should not have non zero values." ); 618 return NULL; 619 } 620 611 if (fd == NULL) { 612 psError(__func__, "Null FITS file descriptor not allowed"); 613 return NULL; 614 } 615 616 if (extName == NULL && extNum == 0) { 617 psError(__func__, "Null extName and extNum = 0 not allowed"); 618 return NULL; 619 } else if (extName && extNum) { 620 psError(__func__, "Both extName and extNum arguments should not have non zero values."); 621 return NULL; 622 } 621 623 // Allocate metadata if user didn't 622 if (output == NULL) {624 if (output == NULL) { 623 625 output = psMetadataAlloc(); 624 626 } 625 626 627 // Move to user designated HDU number or HDU name in FITS file. HDU numbers starts at one. 627 if (extName != NULL) {628 if (fits_movnam_hdu( fd, ANY_HDU, extName, 0, &status) != 0) {628 if (extName != NULL) { 629 if (fits_movnam_hdu(fd, ANY_HDU, extName, 0, &status) != 0) { 629 630 FITS_ERROR("FITS error while locating header %s: %s", extName); 630 631 } 631 632 } else { 632 if (fits_movabs_hdu( fd, extNum, &hduType, &status) != 0) {633 if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) { 633 634 FITS_ERROR("FITS error while locating header %d: %s", extNum); 634 635 } … … 636 637 637 638 // Get number of key names 638 if (fits_get_hdrpos( fd, &numKeys, &keyNum, &status) != 0) {639 if (fits_get_hdrpos(fd, &numKeys, &keyNum, &status) != 0) { 639 640 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 640 641 } 641 642 642 // Get each key name. Keywords start at one. 643 for (i = 1; i <= numKeys; i++) {644 if (fits_read_keyn( fd, i, keyName, keyValue, keyComment, &status) != 0) {643 for (i = 1; i <= numKeys; i++) { 644 if (fits_read_keyn(fd, i, keyName, keyValue, keyComment, &status) != 0) { 645 645 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 646 646 } 647 if (fits_get_keytype( keyValue, &keyType, &status) != 0) {648 fits_get_errstatus( status, fitsErr);649 if (status != VALUE_UNDEFINED) {647 if (fits_get_keytype(keyValue, &keyType, &status) != 0) { 648 fits_get_errstatus(status, fitsErr); 649 if (status != VALUE_UNDEFINED) { 650 650 FITS_ERROR("FITS error while determining key %d type: %s", keyNum); 651 651 } else { 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and HISTORY 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and 653 // HISTORY 653 654 keyType = 'C'; 654 655 status = 0; … … 656 657 } 657 658 658 switch (keyType) {659 switch (keyType) { 659 660 case 'I': 660 661 metadataItemType = PS_META_S32; 661 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atoi( keyValue ) ); 662 success = 663 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 664 atoi(keyValue)); 662 665 break; 663 666 case 'F': 664 667 metadataItemType = PS_META_F64; 665 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atof( keyValue ) ); 668 success = 669 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 670 atof(keyValue)); 666 671 break; 667 672 case 'C': 668 673 metadataItemType = PS_META_STR; 669 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue ); 674 success = 675 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue); 670 676 break; 671 677 case 'L': 672 678 metadataItemType = PS_META_BOOL; 673 tempBool = ( keyValue[ 0 ] == 'T' ) ? 1 : 0; 674 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool ); 679 tempBool = (keyValue[0] == 'T') ? 1 : 0; 680 success = 681 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool); 675 682 break; 676 683 case 'U': 677 684 case 'X': 678 685 default: 679 psError( __func__, "Invalid psMetadataType: %c", keyType);686 psError(__func__, "Invalid psMetadataType: %c", keyType); 680 687 return output; 681 688 } 682 689 683 if (!success) {684 psError( __func__, "Failed to add metadata item. Name: %s", keyName);690 if (!success) { 691 psError(__func__, "Failed to add metadata item. Name: %s", keyName); 685 692 return output; 686 693 } -
trunk/psLib/src/collections/psMetadata.h
r1394 r1407 1 1 2 /** @file psMetadata.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 5 20:55:22$13 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 #ifndef PS_METADATA_H 18 # define PS_METADATA_H19 20 # include <stdarg.h>21 # include <stdio.h>22 # include <fitsio.h>23 24 # include "psHash.h"25 # include "psList.h"19 # define PS_METADATA_H 20 21 # include <stdarg.h> 22 # include <stdio.h> 23 # include <fitsio.h> 24 25 # include "psHash.h" 26 # include "psList.h" 26 27 27 28 /// @addtogroup Metadata … … 33 34 */ 34 35 typedef enum { 35 PS_META_ITEM_SET = 0, ///< Null. Metadata is in psMetadataItem.items36 PS_META_BOOL, ///< Boolean data.37 PS_META_S32, ///< Signed 32-bit integer data.38 PS_META_F32, ///< Single-precision float data.39 PS_META_F64, ///< Double-precision float data.40 PS_META_STR, ///< String data (Stored in as void *).41 PS_META_IMG, ///< Image data (Stored in as void *).42 PS_META_JPEG, ///< JPEG data (Stored in as void .43 PS_META_PNG, ///< PNG data (Stored in as void *).44 PS_META_ASTROM, ///< Astrometric coefficients (Stored in as void *).45 PS_META_UNKNOWN, ///< Other data (Stored in as void *).46 PS_META_NTYPE ///< Number of types. Must be last.36 PS_META_ITEM_SET = 0, // /< Null. Metadata is in psMetadataItem.items 37 PS_META_BOOL, // /< Boolean data. 38 PS_META_S32, // /< Signed 32-bit integer data. 39 PS_META_F32, // /< Single-precision float data. 40 PS_META_F64, // /< Double-precision float data. 41 PS_META_STR, // /< String data (Stored in as void *). 42 PS_META_IMG, // /< Image data (Stored in as void *). 43 PS_META_JPEG, // /< JPEG data (Stored in as void . 44 PS_META_PNG, // /< PNG data (Stored in as void *). 45 PS_META_ASTROM, // /< Astrometric coefficients (Stored in as void *). 46 PS_META_UNKNOWN, // /< Other data (Stored in as void *). 47 PS_META_NTYPE // /< Number of types. Must be last. 47 48 } psMetadataType; 48 49 … … 54 55 typedef struct psMetadataItem 55 56 { 56 const int id; ///< Unique ID for metadata item. 57 char *restrict name; ///< Name of metadata item. 58 psMetadataType type; ///< Type of metadata item. 59 union 60 { 57 const int id; // /< Unique ID for metadata item. 58 char *restrict name; // /< Name of metadata item. 59 psMetadataType type; // /< Type of metadata item. 60 union { 61 61 bool B; 62 psS32 S32; ///< Signed 32-bit integer data.63 psF32 F32; ///< Single-precision float data.64 psF64 F64; ///< Double-precision float data.65 psPTR V; ///< Pointer to other type of data.66 } data; ///< Union for data types.67 char *comment; ///< Optional comment ("", not NULL).68 psList *restrict items; ///< List of psMetadataItems with same name.62 psS32 S32; // /< Signed 32-bit integer data. 63 psF32 F32; // /< Single-precision float data. 64 psF64 F64; // /< Double-precision float data. 65 psPTR V; // /< Pointer to other type of data. 66 } data; // /< Union for data types. 67 char *comment; // /< Optional comment ("", not NULL). 68 psList *restrict items; // /< List of psMetadataItems with same name. 69 69 } 70 70 psMetadataItem; … … 78 78 typedef struct psMetadata 79 79 { 80 psList *restrict list;81 psHash *restrict table;80 psList *restrict list; 81 psHash *restrict table; 82 82 } 83 83 psMetadata; 84 84 85 86 85 /*****************************************************************************/ 86 87 87 /* FUNCTION PROTOTYPES */ 88 88 89 /*****************************************************************************/ 89 90 … … 101 102 * @return psMetadataItem*: Pointer metadata item. 102 103 */ 103 psMetadataItem *psMetadataItemAlloc( 104 const char *name, ///< Name of metadata item. 105 psMetadataType type, ///< Type of metadata item. 106 const char *comment, ///< Comment for metadata item. 107 ... ///< Arguments for name formatting and metadata item data. 108 ); 104 psMetadataItem *psMetadataItemAlloc(const char *name, // /< Name of metadata item. 105 psMetadataType type, // /< Type of metadata item. 106 const char *comment, // /< Comment for metadata item. 107 ... // /< Arguments for name formatting and metadata item data. 108 ); 109 109 110 110 /** Create a metadata item with va_list. … … 121 121 * @return psMetadataItem*: Pointer metadata item. 122 122 */ 123 psMetadataItem *psMetadataItemAllocV( 124 const char *name, ///< Name of metadata item.125 psMetadataType type, ///< Type ofmetadata item.126 const char *comment, ///< Comment for metadata item.127 va_list list ///< Arguments for name formatting and metadata itemdata.128 );123 psMetadataItem *psMetadataItemAllocV(const char *name, // /< Name of metadata item. 124 psMetadataType type, // /< Type of metadata item. 125 const char *comment, // /< Comment for metadata item. 126 va_list list // /< Arguments for name formatting and metadata item 127 // data. 128 ); 129 129 130 130 /** Create a metadata collection. … … 134 134 * @return psMetadata*: Pointer metadata. 135 135 */ 136 psMetadata *psMetadataAlloc( 137 void ///< Void. 138 ); 136 psMetadata *psMetadataAlloc(void // /< Void. 137 ); 139 138 140 139 /** Add existing metadata item to metadata collection. … … 144 143 * @return bool: True for success, false for failure. 145 144 */ 146 bool psMetadataAddItem( 147 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 148 int where, ///< Location to be added. 149 psMetadataItem *restrict item ///< Metadata item to be added. 150 ); 145 bool psMetadataAddItem(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 146 int where, // /< Location to be added. 147 psMetadataItem * restrict item // /< Metadata item to be added. 148 ); 151 149 152 150 /** Create and add a metadata item to metadata collection. … … 156 154 * @return bool: True for success, false for failure. 157 155 */ 158 bool psMetadataAdd( 159 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 160 int where, ///< Location to be added. 161 const char *name, ///< Name of metadata item. 162 psMetadataType type, ///< Type of metadata item. 163 const char *comment, ///< Comment for metadata item. 164 ... ///< Arguments for name formatting and metadata item data. 165 ); 156 bool psMetadataAdd(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 157 int where, // /< Location to be added. 158 const char *name, // /< Name of metadata item. 159 psMetadataType type, // /< Type of metadata item. 160 const char *comment, // /< Comment for metadata item. 161 ... // /< Arguments for name formatting and metadata item data. 162 ); 166 163 167 164 /** Remove an item from metadata collection. … … 174 171 * @return bool: True for success, false for failure. 175 172 */ 176 bool psMetadataRemove( 177 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 178 int where, ///< Location to be removed. 179 const char *restrict key ///< Name of metadata key. 180 ); 173 bool psMetadataRemove(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 174 int where, // /< Location to be removed. 175 const char *restrict key // /< Name of metadata key. 176 ); 181 177 182 178 /** Find an item in the metadata collection based on key name. … … 187 183 * @return psMetadataItem*: Pointer metadata item. 188 184 */ 189 psMetadataItem *psMetadataLookup( 190 psMetadata *restrict md, ///< Metadata collection to insert metadatitem.191 const char *restrict key ///< Name of metadata key.192 );185 psMetadataItem *psMetadataLookup(psMetadata * restrict md, // /< Metadata collection to insert metadat 186 // item. 187 const char *restrict key // /< Name of metadata key. 188 ); 193 189 194 190 /** Find an item in the metadata collection based on list index. … … 198 194 * @return psMetadataItem*: Pointer metadata item. 199 195 */ 200 psMetadataItem *psMetadataGet( 201 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 202 int where ///< Location to be retrieved. 203 ); 196 psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 197 int where // /< Location to be retrieved. 198 ); 204 199 205 200 /** Set or reset metadata iterator. … … 209 204 * @return void: void. 210 205 */ 211 bool psMetadataSetIterator( 212 psMetadata *restrict md, ///< Metadata collection to iterate. 213 int where ///< Location of iterator. 214 ); 206 bool psMetadataSetIterator(psMetadata * restrict md, // /< Metadata collection to iterate. 207 int where // /< Location of iterator. 208 ); 215 209 216 210 /** Get next metadata item. … … 220 214 * @return psMetadataItem*: Pointer metadata item. 221 215 */ 222 psMetadataItem *psMetadataGetNext( 223 psMetadata *restrict md, ///< Metadata collection to iterate. 224 const char *restrict match, ///< Beginning of key name. 225 int which ///< Iterator to be used. 226 ); 216 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, // /< Metadata collection to iterate. 217 const char *restrict match, // /< Beginning of key name. 218 int which // /< Iterator to be used. 219 ); 227 220 228 221 /** Get previous metadata item. … … 232 225 * @return psMetadataItem*: Pointer metadata item. 233 226 */ 234 psMetadataItem *psMetadataGetPrevious( 235 psMetadata *restrict md, ///< Metadata collection to iterate. 236 const char *restrict match, ///< Beginning of key name. 237 int which ///< Iterator to be used. 238 ); 227 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, // /< Metadata collection to iterate. 228 const char *restrict match, // /< Beginning of key name. 229 int which // /< Iterator to be used. 230 ); 239 231 240 232 /** Print metadata item to file. … … 248 240 * @return psMetadataItem*: Pointer metadata item. 249 241 */ 250 void psMetadataItemPrint( 251 FILE *fd, ///< Pointer to file to write metadata item. 252 const char *format, ///< Format to print metadata item. 253 const psMetadataItem *restrict metadataItem ///< Metadata item to print. 254 ); 242 void psMetadataItemPrint(FILE * fd, // /< Pointer to file to write metadata item. 243 const char *format, // /< Format to print metadata item. 244 const psMetadataItem * restrict metadataItem // /< Metadata item to print. 245 ); 255 246 256 247 /** Read metadata header. … … 261 252 * @return psMetadata*: Pointer metadata. 262 253 */ 263 psMetadata *psMetadataReadHeader( 264 psMetadata *output, ///< Resulting metadata from read. 265 char *extname, ///< File name extension string. 266 int extnum, ///< File name extension number. Starts at 1. 267 char *filename ///< Name of file to read. 268 ); 254 psMetadata *psMetadataReadHeader(psMetadata * output, // /< Resulting metadata from read. 255 char *extname, // /< File name extension string. 256 int extnum, // /< File name extension number. Starts at 1. 257 char *filename // /< Name of file to read. 258 ); 269 259 270 260 /** Read metadata header. … … 274 264 * @return psMetadata*: Pointer metadata. 275 265 */ 276 psMetadata *psMetadataFReadHeader( 277 psMetadata *output, ///< Resulting metadata from read.278 char *extName, ///< File name extension string.279 int extNum, ///< File name extension number.280 fitsfile *fd ///< Pointer to file to read.281 ); 266 psMetadata *psMetadataFReadHeader(psMetadata * output, // /< Resulting metadata from read. 267 char *extName, // /< File name extension string. 268 int extNum, // /< File name extension number. 269 fitsfile * fd // /< Pointer to file to read. 270 ); 271 282 272 /// @} 283 273 -
trunk/psLib/src/collections/psScalar.c
r1406 r1407 1 1 2 /** @file psScalar.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 22 #include "psMemory.h" … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 psScalar *psScalarAlloc(psC64 value, psElemType dataType) … … 61 76 62 77 // Create scalar 63 scalar = (psScalar *) psAlloc(sizeof(psScalar));64 if (scalar == NULL) {65 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);78 scalar = (psScalar *) psAlloc(sizeof(psScalar)); 79 if (scalar == NULL) { 80 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 66 81 } 67 82 … … 71 86 switch (dataType) { 72 87 case PS_TYPE_S8: 73 scalar->data.S8 = (psS8) value;88 scalar->data.S8 = (psS8) value; 74 89 break; 75 90 case PS_TYPE_U8: 76 scalar->data.U8 = (psU8) value;91 scalar->data.U8 = (psU8) value; 77 92 break; 78 93 case PS_TYPE_S16: 79 scalar->data.S16 = (psS16) value;94 scalar->data.S16 = (psS16) value; 80 95 break; 81 96 case PS_TYPE_U16: 82 scalar->data.U16 = (psU16) value;97 scalar->data.U16 = (psU16) value; 83 98 break; 84 99 case PS_TYPE_S32: 85 scalar->data.S32 = (psS32) value;100 scalar->data.S32 = (psS32) value; 86 101 break; 87 102 case PS_TYPE_U32: 88 scalar->data.U32 = (psU32) value;103 scalar->data.U32 = (psU32) value; 89 104 break; 90 105 case PS_TYPE_S64: 91 scalar->data.S64 = (psS64) value;106 scalar->data.S64 = (psS64) value; 92 107 break; 93 108 case PS_TYPE_U64: 94 scalar->data.U64 = (psU64) value;109 scalar->data.U64 = (psU64) value; 95 110 break; 96 111 case PS_TYPE_F32: 97 scalar->data.F32 = (psF32) value;112 scalar->data.F32 = (psF32) value; 98 113 break; 99 114 case PS_TYPE_F64: 100 scalar->data.F64 = (psF64) value;115 scalar->data.F64 = (psF64) value; 101 116 break; 102 117 case PS_TYPE_C32: 103 scalar->data.C32 = (psC32) value;118 scalar->data.C32 = (psC32) value; 104 119 break; 105 120 case PS_TYPE_C64: 106 scalar->data.C64 = (psC64) value;121 scalar->data.C64 = (psC64) value; 107 122 break; 108 123 default: … … 110 125 } 111 126 112 113 127 return scalar; 114 128 } 115 129 116 void psScalarFree(psScalar * restrict scalar)130 void psScalarFree(psScalar * restrict scalar) 117 131 { 118 132 if (scalar == NULL) { … … 122 136 psFree(scalar); 123 137 } 124 125 -
trunk/psLib/src/collections/psScalar.h
r1406 r1407 1 1 2 /** @file psScalar.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1. 3$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.4 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_SCALAR_H 19 # define PS_SCALAR_H20 # define PS_SCALAR_H 20 21 21 # include "psType.h"22 # include "psType.h" 22 23 23 24 /// @addtogroup Scalar … … 31 32 typedef struct 32 33 { 33 psType type; ///< Type of data.34 psType type; // /< Type of data. 34 35 35 36 union { 36 psU8 U8; ///< Unsigned 8-bit integer data.37 psU16 U16; ///< Unsigned 16-bit integer data.38 psU32 U32; ///< Unsigned 32-bit integer data.39 psU64 U64; ///< Unsigned 64-bit integer data.40 psS8 S8; ///< Signed 8-bit integer data.41 psS16 S16; ///< Signed 16-bit integer data.42 psS32 S32; ///< Signed 32-bit integer data.43 psS64 S64; ///< Signed 64-bit integer data.44 psF32 F32; ///< Single-precision float data.45 psF64 F64; ///< Double-precision float data.46 psC32 C32; ///< Single-precision complex data.47 psC64 C64; ///< Double-precision complex data.48 } data; ///< Union for data types.37 psU8 U8; // /< Unsigned 8-bit integer data. 38 psU16 U16; // /< Unsigned 16-bit integer data. 39 psU32 U32; // /< Unsigned 32-bit integer data. 40 psU64 U64; // /< Unsigned 64-bit integer data. 41 psS8 S8; // /< Signed 8-bit integer data. 42 psS16 S16; // /< Signed 16-bit integer data. 43 psS32 S32; // /< Signed 32-bit integer data. 44 psS64 S64; // /< Signed 64-bit integer data. 45 psF32 F32; // /< Single-precision float data. 46 psF64 F64; // /< Double-precision float data. 47 psC32 C32; // /< Single-precision complex data. 48 psC64 C64; // /< Double-precision complex data. 49 } data; // /< Union for data types. 49 50 } 50 51 psScalar; 51 52 52 53 /*****************************************************************************/ 54 53 55 /* FUNCTION PROTOTYPES */ 56 54 57 /*****************************************************************************/ 55 58 … … 62 65 * 63 66 */ 64 psScalar *psScalarAlloc( 65 psC64 value, ///< Data to be put into psScalar. 66 psElemType dataType ///< Type of data to be held by psScalar. 67 ); 68 67 psScalar *psScalarAlloc(psC64 value, // /< Data to be put into psScalar. 68 psElemType dataType // /< Type of data to be held by psScalar. 69 ); 69 70 70 71 /** Deallocate a scalar. … … 75 76 * 76 77 */ 77 void psScalarFree( 78 psScalar *restrict scalar ///< Scalar to free. 79 ); 78 void psScalarFree(psScalar * restrict scalar // /< Scalar to free. 79 ); 80 80 81 81 /// @} -
trunk/psLib/src/collections/psVector.c
r1406 r1407 1 1 2 /** @file psVector.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 18 /******************************************************************************/ 19 #include <string.h> // for memcpy 20 21 /******************************************************************************/ 22 #include <string.h> // for memcpy 20 23 #include <stdlib.h> 21 24 #include <math.h> … … 28 31 29 32 /******************************************************************************/ 33 30 34 /* DEFINE STATEMENTS */ 35 31 36 /******************************************************************************/ 32 37 … … 34 39 35 40 /******************************************************************************/ 41 36 42 /* TYPE DEFINITIONS */ 43 37 44 /******************************************************************************/ 38 45 … … 40 47 41 48 /*****************************************************************************/ 49 42 50 /* GLOBAL VARIABLES */ 51 43 52 /*****************************************************************************/ 44 53 … … 46 55 47 56 /*****************************************************************************/ 57 48 58 /* FILE STATIC VARIABLES */ 59 49 60 /*****************************************************************************/ 50 61 … … 52 63 53 64 /*****************************************************************************/ 65 54 66 /* FUNCTION IMPLEMENTATION - LOCAL */ 55 /*****************************************************************************/ 56 static void vectorFree( psVector *restrict psVec ); 57 58 /*****************************************************************************/ 67 68 /*****************************************************************************/ 69 static void vectorFree(psVector * restrict psVec); 70 71 /*****************************************************************************/ 72 59 73 /* FUNCTION IMPLEMENTATION - PUBLIC */ 60 /*****************************************************************************/ 61 psVector* psVectorAlloc( unsigned int nalloc, psElemType elemType ) 62 { 63 psVector * psVec = NULL; 74 75 /*****************************************************************************/ 76 psVector *psVectorAlloc(unsigned int nalloc, psElemType elemType) 77 { 78 psVector *psVec = NULL; 64 79 int elementSize = 0; 65 80 66 81 // Invalid nalloc 67 if ( nalloc < 1) {68 psError( __func__, "Invalid value for nalloc. nalloc: %d\n", nalloc);82 if (nalloc < 1) { 83 psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc); 69 84 return NULL; 70 85 } 71 86 72 elementSize = PSELEMTYPE_SIZEOF( elemType);87 elementSize = PSELEMTYPE_SIZEOF(elemType); 73 88 74 89 // Create vector struct 75 psVec = ( psVector * ) psAlloc( sizeof( psVector ));76 p_psMemSetDeallocator( psVec, ( psFreeFcn ) vectorFree);90 psVec = (psVector *) psAlloc(sizeof(psVector)); 91 p_psMemSetDeallocator(psVec, (psFreeFcn) vectorFree); 77 92 78 93 psVec->type.dimen = PS_DIMEN_VECTOR; … … 82 97 83 98 // Create vector data array 84 psVec->data.V = psAlloc( nalloc * elementSize);99 psVec->data.V = psAlloc(nalloc * elementSize); 85 100 86 101 return psVec; 87 102 } 88 103 89 psVector *psVectorRealloc( unsigned int nalloc, psVector *restrict in)104 psVector *psVectorRealloc(unsigned int nalloc, psVector * restrict in) 90 105 { 91 106 int elementSize = 0; … … 93 108 94 109 // Invalid nalloc 95 if ( nalloc < 1) {96 psError( __func__, "Invalid value for realloc (%d)\n", nalloc);110 if (nalloc < 1) { 111 psError(__func__, "Invalid value for realloc (%d)\n", nalloc); 97 112 return NULL; 98 113 } 99 114 100 if ( in == NULL) {101 psError( __func__, "Null input vector\n");115 if (in == NULL) { 116 psError(__func__, "Null input vector\n"); 102 117 return NULL; 103 } else 104 if ( in->nalloc != nalloc ) { // No need to realloc to same size 105 elemType = in->type.type; 106 elementSize = PSELEMTYPE_SIZEOF( elemType ); 107 if ( nalloc < in->n ) { 108 in->n = nalloc; 109 } 110 111 // Realloc after decrementation to avoid accessing freed array elements 112 in->data.V = psRealloc( in->data.V, nalloc * elementSize ); 113 in->nalloc = nalloc; 118 } else if (in->nalloc != nalloc) { // No need to realloc to same size 119 elemType = in->type.type; 120 elementSize = PSELEMTYPE_SIZEOF(elemType); 121 if (nalloc < in->n) { 122 in->n = nalloc; 114 123 } 124 // Realloc after decrementation to avoid accessing freed array elements 125 in->data.V = psRealloc(in->data.V, nalloc * elementSize); 126 in->nalloc = nalloc; 127 } 115 128 116 129 return in; 117 130 } 118 131 119 psVector *psVectorRecycle( psVector *restrict in, unsigned int nalloc, psElemType type)132 psVector *psVectorRecycle(psVector * restrict in, unsigned int nalloc, psElemType type) 120 133 { 121 134 psElemType elemType; 122 135 123 if ( in == NULL) {124 return psVectorAlloc( nalloc, type);136 if (in == NULL) { 137 return psVectorAlloc(nalloc, type); 125 138 } 126 139 127 140 elemType = in->type.type; 128 141 129 if ( in->nalloc == nalloc && elemType == type) {142 if (in->nalloc == nalloc && elemType == type) { 130 143 // it is proper size/type already 131 144 return in; 132 145 } 133 134 146 // Invalid nalloc 135 if ( nalloc < 1) {136 psError( __func__, "Invalid value for nalloc (%d)\n", nalloc);137 psFree( in);147 if (nalloc < 1) { 148 psError(__func__, "Invalid value for nalloc (%d)\n", nalloc); 149 psFree(in); 138 150 return NULL; 139 151 } 140 152 141 142 in->data.V = psRealloc( in->data.V, nalloc * PSELEMTYPE_SIZEOF( type ) ); 153 in->data.V = psRealloc(in->data.V, nalloc * PSELEMTYPE_SIZEOF(type)); 143 154 144 155 in->type.type = type; … … 149 160 } 150 161 151 psVector *psVectorSort( psVector *restrict outVector, const psVector *restrict inVector)162 psVector *psVectorSort(psVector * restrict outVector, const psVector * restrict inVector) 152 163 { 153 164 int inN = 0; … … 158 169 psElemType inType = 0; 159 170 160 if ( inVector == NULL) {161 psError( __func__, " : Line %d - Null input vector\n", __LINE__);171 if (inVector == NULL) { 172 psError(__func__, " : Line %d - Null input vector\n", __LINE__); 162 173 return outVector; 163 174 } … … 166 177 inN = inVector->n; 167 178 inVec = inVector->data.V; 168 elSize = PSELEMTYPE_SIZEOF( inType);169 170 if ( outVector == NULL) {171 outVector = psVectorAlloc( inN, inType);179 elSize = PSELEMTYPE_SIZEOF(inType); 180 181 if (outVector == NULL) { 182 outVector = psVectorAlloc(inN, inType); 172 183 outVector->n = inVector->n; 173 184 } … … 176 187 outVec = outVector->data.V; 177 188 178 if ( inN != outN ) { 179 psError( __func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", __LINE__, 180 inN, outN ); 181 return outVector; 182 } 183 184 if ( inType != outVector->type.type ) { 185 psError( __func__, " : Line %d - Input and output vectors are not same type: in=%d out=%d\n", __LINE__, 186 inType, outVector->type.type ); 187 return outVector; 188 } 189 190 if ( inN == 0 ) { 191 psError( __func__, " : Line %d - No elements in use for input vector\n", __LINE__ ); 192 return outVector; 193 } 194 195 if ( outN == 0 ) { 196 psError( __func__, " : Line %d - No elements in use for output vector\n", __LINE__ ); 197 return outVector; 198 } 199 189 if (inN != outN) { 190 psError(__func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", 191 __LINE__, inN, outN); 192 return outVector; 193 } 194 195 if (inType != outVector->type.type) { 196 psError(__func__, " : Line %d - Input and output vectors are not same type: in=%d out=%d\n", __LINE__, 197 inType, outVector->type.type); 198 return outVector; 199 } 200 201 if (inN == 0) { 202 psError(__func__, " : Line %d - No elements in use for input vector\n", __LINE__); 203 return outVector; 204 } 205 206 if (outN == 0) { 207 psError(__func__, " : Line %d - No elements in use for output vector\n", __LINE__); 208 return outVector; 209 } 200 210 // Copy input vector values into output vector 201 memcpy( outVec, inVec, elSize * outN);211 memcpy(outVec, inVec, elSize * outN); 202 212 203 213 // Sort output vector 204 switch ( inType) {214 switch (inType) { 205 215 case PS_TYPE_U8: 206 qsort( outVec, inN, elSize, psCompareU8);216 qsort(outVec, inN, elSize, psCompareU8); 207 217 break; 208 218 case PS_TYPE_U16: 209 qsort( outVec, inN, elSize, psCompareU16);219 qsort(outVec, inN, elSize, psCompareU16); 210 220 break; 211 221 case PS_TYPE_U32: 212 qsort( outVec, inN, elSize, psCompareU32);222 qsort(outVec, inN, elSize, psCompareU32); 213 223 break; 214 224 case PS_TYPE_U64: 215 qsort( outVec, inN, elSize, psCompareU64);225 qsort(outVec, inN, elSize, psCompareU64); 216 226 break; 217 227 case PS_TYPE_S8: 218 qsort( outVec, inN, elSize, psCompareS8);228 qsort(outVec, inN, elSize, psCompareS8); 219 229 break; 220 230 case PS_TYPE_S16: 221 qsort( outVec, inN, elSize, psCompareS16);231 qsort(outVec, inN, elSize, psCompareS16); 222 232 break; 223 233 case PS_TYPE_S32: 224 qsort( outVec, inN, elSize, psCompareS32);234 qsort(outVec, inN, elSize, psCompareS32); 225 235 break; 226 236 case PS_TYPE_S64: 227 qsort( outVec, inN, elSize, psCompareS64);237 qsort(outVec, inN, elSize, psCompareS64); 228 238 break; 229 239 case PS_TYPE_F32: 230 qsort( outVec, inN, elSize, psCompareF32);240 qsort(outVec, inN, elSize, psCompareF32); 231 241 break; 232 242 case PS_TYPE_F64: 233 qsort( outVec, inN, elSize, psCompareF64);243 qsort(outVec, inN, elSize, psCompareF64); 234 244 break; 235 245 default: 236 psError( __func__, " : Line %d - Invalid psType\n", __LINE__);246 psError(__func__, " : Line %d - Invalid psType\n", __LINE__); 237 247 } 238 248 … … 251 261 } 252 262 253 psVector *psVectorSortIndex( psVector *restrict outVector, const psVector *restrict inVector)263 psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector) 254 264 { 255 265 int inN = 0; … … 263 273 psElemType inType = 0; 264 274 265 if ( inVector == NULL) {266 psError( __func__, " : Line %d - Null input vector\n", __LINE__);275 if (inVector == NULL) { 276 psError(__func__, " : Line %d - Null input vector\n", __LINE__); 267 277 return outVector; 268 278 } … … 272 282 inType = inVector->type.type; 273 283 274 if ( outVector == NULL) {275 outVector = psVectorAlloc( inN, PS_TYPE_U32);284 if (outVector == NULL) { 285 outVector = psVectorAlloc(inN, PS_TYPE_U32); 276 286 outVector->n = inN; 277 287 } … … 280 290 outVec = outVector->data.V; 281 291 282 if ( inN != outN) {283 psError( __func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n",284 __LINE__, inN, outN);285 return outVector; 286 } 287 288 if ( outVector->type.type != PS_TYPE_U32) {289 psError( __func__, " : Line %d - Output vector is not of type U32: out=%d\n",290 __LINE__, outVector->type.type);291 return outVector; 292 } 293 294 tmpVector = psVectorAlloc( inN, inType);292 if (inN != outN) { 293 psError(__func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", 294 __LINE__, inN, outN); 295 return outVector; 296 } 297 298 if (outVector->type.type != PS_TYPE_U32) { 299 psError(__func__, " : Line %d - Output vector is not of type U32: out=%d\n", 300 __LINE__, outVector->type.type); 301 return outVector; 302 } 303 304 tmpVector = psVectorAlloc(inN, inType); 295 305 tmpVector->n = inN; 296 tmpVector = psVectorSort( tmpVector, inVector);306 tmpVector = psVectorSort(tmpVector, inVector); 297 307 298 308 // Sort output vector 299 switch ( inType) {309 switch (inType) { 300 310 case PS_TYPE_U8: 301 SORT_INDICES( U8);311 SORT_INDICES(U8); 302 312 break; 303 313 case PS_TYPE_U16: 304 SORT_INDICES( U16);314 SORT_INDICES(U16); 305 315 break; 306 316 case PS_TYPE_U32: 307 SORT_INDICES( U32);317 SORT_INDICES(U32); 308 318 break; 309 319 case PS_TYPE_U64: 310 SORT_INDICES( U64);320 SORT_INDICES(U64); 311 321 break; 312 322 case PS_TYPE_S8: 313 SORT_INDICES( S8);323 SORT_INDICES(S8); 314 324 break; 315 325 case PS_TYPE_S16: 316 SORT_INDICES( S16);326 SORT_INDICES(S16); 317 327 break; 318 328 case PS_TYPE_S32: 319 SORT_INDICES( S32);329 SORT_INDICES(S32); 320 330 break; 321 331 case PS_TYPE_S64: 322 SORT_INDICES( S64);332 SORT_INDICES(S64); 323 333 break; 324 334 case PS_TYPE_F32: 325 SORT_INDICES( F32);335 SORT_INDICES(F32); 326 336 break; 327 337 case PS_TYPE_F64: 328 SORT_INDICES( F64);338 SORT_INDICES(F64); 329 339 break; 330 340 default: 331 psError( __func__, " : Line %d - Invalid psType\n", __LINE__);341 psError(__func__, " : Line %d - Invalid psType\n", __LINE__); 332 342 } 333 343 334 344 // Free temp memory 335 psFree( tmpVector);345 psFree(tmpVector); 336 346 337 347 return outVector; 338 348 } 339 349 340 static void vectorFree( psVector *restrict psVec)341 { 342 if ( psVec == NULL) {343 return ;344 } 345 346 psFree( psVec->data.V);347 } 350 static void vectorFree(psVector * restrict psVec) 351 { 352 if (psVec == NULL) { 353 return; 354 } 355 356 psFree(psVec->data.V); 357 } -
trunk/psLib/src/collections/psVector.h
r1406 r1407 1 1 2 /** @file psVector.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_VECTOR_H 20 # define PS_VECTOR_H21 # define PS_VECTOR_H 21 22 22 # include "psType.h"23 # include "psType.h" 23 24 24 25 /// @addtogroup Vector … … 32 33 typedef struct 33 34 { 34 psType type; ///< Type of data.35 unsigned int nalloc; ///< Total number of elements available.36 unsigned int n; ///< Number of elements in use.35 psType type; // /< Type of data. 36 unsigned int nalloc; // /< Total number of elements available. 37 unsigned int n; // /< Number of elements in use. 37 38 38 39 union { 39 psU8 *U8; ///< Unsigned 8-bit integer data.40 psU16 *U16; ///< Unsigned 16-bit integer data.41 psU32 *U32; ///< Unsigned 32-bit integer data.42 psU64 *U64; ///< Unsigned 64-bit integer data.43 psS8 *S8; ///< Signed 8-bit integer data.44 psS16 *S16; ///< Signed 16-bit integer data.45 psS32 *S32; ///< Signed 32-bit integer data.46 psS64 *S64; ///< Signed 64-bit integer data.47 psF32 *F32; ///< Single-precision float data.48 psF64 *F64; ///< Double-precision float data.49 psC32 *C32; ///< Single-precision complex data.50 psC64 *C64; ///< Double-precision complex data.51 psPTR V; ///< Pointer to data.52 } data; ///< Union for data types.40 psU8 *U8; // /< Unsigned 8-bit integer data. 41 psU16 *U16; // /< Unsigned 16-bit integer data. 42 psU32 *U32; // /< Unsigned 32-bit integer data. 43 psU64 *U64; // /< Unsigned 64-bit integer data. 44 psS8 *S8; // /< Signed 8-bit integer data. 45 psS16 *S16; // /< Signed 16-bit integer data. 46 psS32 *S32; // /< Signed 32-bit integer data. 47 psS64 *S64; // /< Signed 64-bit integer data. 48 psF32 *F32; // /< Single-precision float data. 49 psF64 *F64; // /< Double-precision float data. 50 psC32 *C32; // /< Single-precision complex data. 51 psC64 *C64; // /< Double-precision complex data. 52 psPTR V; // /< Pointer to data. 53 } data; // /< Union for data types. 53 54 } 54 55 psVector; 55 56 56 57 /*****************************************************************************/ 58 57 59 /* FUNCTION PROTOTYPES */ 60 58 61 /*****************************************************************************/ 59 62 … … 65 68 * 66 69 */ 67 psVector *psVectorAlloc( 68 unsigned int nalloc, ///< Total number of elements to make available. 69 psElemType dataType ///< Type of data to be held by vector. 70 ); 70 psVector *psVectorAlloc(unsigned int nalloc, // /< Total number of elements to make available. 71 psElemType dataType // /< Type of data to be held by vector. 72 ); 71 73 72 74 /** Reallocate a vector. … … 78 80 * 79 81 */ 80 psVector *psVectorRealloc( 81 unsigned int nalloc, ///< Total number of elements to make available. 82 psVector *restrict psVec ///< Vector to reallocate. 83 ); 82 psVector *psVectorRealloc(unsigned int nalloc, // /< Total number of elements to make available. 83 psVector * restrict psVec // /< Vector to reallocate. 84 ); 84 85 85 86 /** Recycle a vector. … … 91 92 * 92 93 */ 93 psVector *psVectorRecycle( 94 psVector *restrict psVec, 95 ///< Vector to recycle. If NULL, a new vector is created. No effort taken to preserve the values. 96 97 unsigned int nalloc, ///< Total number of elements to make available. 98 psElemType type ///< the datatype of the returned vector 99 ); 94 psVector *psVectorRecycle(psVector * restrict psVec, 95 // /< Vector to recycle. If NULL, a new vector is created. No effort taken to 96 // preserve the values. 97 unsigned int nalloc, // /< Total number of elements to make available. 98 psElemType type // /< the datatype of the returned vector 99 ); 100 100 101 101 /** Sort an array of floats. … … 107 107 */ 108 108 109 psVector *psVectorSort( 110 psVector *restrict outVector, ///< the output vector to recycle, or NULL if newvector desired.111 const psVector *restrict inVector ///< the vector to sort.112 );109 psVector *psVectorSort(psVector * restrict outVector, // /< the output vector to recycle, or NULL if new 110 // vector desired. 111 const psVector * restrict inVector // /< the vector to sort. 112 ); 113 113 114 114 /** Creates an array of indices based on sort odred of float array. … … 120 120 */ 121 121 122 psVector *psVectorSortIndex( 123 psVector *restrict outVector, 124 const psVector *restrict inVector 125 ); 126 122 psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector); 127 123 128 124 /// @} -
trunk/psLib/src/dataManip/psFFT.c
r1406 r1407 1 1 2 /** @file psFFT.c 2 3 * … … 5 6 * @author Robert DeSonia, MHPCC 6 7 * 7 * @version $Revision: 1.1 8$ $Name: not supported by cvs2svn $8 * @date $Date: 2004-08-0 6 22:34:05$8 * @version $Revision: 1.19 $ $Name: not supported by cvs2svn $ 9 * @date $Date: 2004-08-07 00:06:06 $ 9 10 * 10 11 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 static bool p_fftwWisdomImported = false; 28 29 29 psImage * psImageFFT( psImage* out, const psImage* in, psFftDirection direction)30 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction) 30 31 { 31 32 unsigned int numCols; … … 35 36 36 37 /* got good image data? */ 37 if ( in == NULL ) { 38 psFree( out ); 39 return NULL; 40 } 41 42 type = in->type.type; 43 44 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 45 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 46 type ); 47 psFree( out ); 48 return NULL; 49 } 50 51 if ( type != PS_TYPE_C32 && direction == PS_FFT_REVERSE ) { 52 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 53 type ); 54 psFree( out ); 55 return NULL; 56 57 } 58 59 if ( type != PS_TYPE_F32 && direction == PS_FFT_FORWARD ) { 60 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 61 type ); 62 psFree( out ); 38 if (in == NULL) { 39 psFree(out); 40 return NULL; 41 } 42 43 type = in->type.type; 44 45 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 46 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 47 psFree(out); 48 return NULL; 49 } 50 51 if (type != PS_TYPE_C32 && direction == PS_FFT_REVERSE) { 52 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 53 psFree(out); 54 return NULL; 55 56 } 57 58 if (type != PS_TYPE_F32 && direction == PS_FFT_FORWARD) { 59 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 60 psFree(out); 63 61 return NULL; 64 62 } 65 63 66 64 /* make sure the system-level wisdom information is imported. */ 67 if ( ! p_fftwWisdomImported) {65 if (!p_fftwWisdomImported) { 68 66 fftwf_import_system_wisdom(); 69 67 p_fftwWisdomImported = true; … … 73 71 numCols = in->numCols; 74 72 75 out = psImageCopy( out, in, PS_TYPE_C32 ); 76 77 plan = fftwf_plan_dft_2d( numCols, numRows, 78 ( fftwf_complex* ) out->data.C32[ 0 ], 79 ( fftwf_complex* ) out->data.C32[ 0 ], 80 direction, 81 P_FFTW_PLAN_RIGOR ); 82 83 /* check if a plan exists now*/ 84 if ( plan == NULL ) { 85 psError( __func__, "Failed to create FFTW plan." ); 86 psFree( out ); 73 out = psImageCopy(out, in, PS_TYPE_C32); 74 75 plan = fftwf_plan_dft_2d(numCols, numRows, 76 (fftwf_complex *) out->data.C32[0], 77 (fftwf_complex *) out->data.C32[0], direction, P_FFTW_PLAN_RIGOR); 78 79 /* check if a plan exists now */ 80 if (plan == NULL) { 81 psError(__func__, "Failed to create FFTW plan."); 82 psFree(out); 87 83 return NULL; 88 84 } 89 85 90 86 /* finally, call FFTW with the plan made above */ 91 fftwf_execute( plan ); 92 93 fftwf_destroy_plan( plan ); 94 95 return out; 96 97 } 98 99 100 psImage *psImageReal( psImage *out, const psImage* in ) 87 fftwf_execute(plan); 88 89 fftwf_destroy_plan(plan); 90 91 return out; 92 93 } 94 95 psImage *psImageReal(psImage * out, const psImage * in) 101 96 { 102 97 psElemType type; … … 104 99 unsigned int numRows; 105 100 106 107 if ( in == NULL ) { 108 psFree( out ); 101 if (in == NULL) { 102 psFree(out); 109 103 return NULL; 110 104 } … … 115 109 116 110 /* if not a complex number, this is logically just a copy */ 117 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {111 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 118 112 // Warn user, as this is probably not expected 119 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 120 "Just an image copy was performed." ); 121 return psImageCopy( out, in, type ); 122 } 123 124 if ( type == PS_TYPE_C32 ) { 125 psF32 * outRow; 126 psC32* inRow; 127 128 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 129 for ( unsigned int row = 0;row < numRows;row++ ) { 130 outRow = out->data.F32[ row ]; 131 inRow = in->data.C32[ row ]; 132 133 for ( unsigned int col = 0;col < numCols;col++ ) { 134 outRow[ col ] = crealf( inRow[ col ] ); 135 } 136 } 137 } else 138 if ( type == PS_TYPE_C64 ) { 139 psF64 * outRow; 140 psC64* inRow; 141 142 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 143 for ( unsigned int row = 0;row < numRows;row++ ) { 144 outRow = out->data.F64[ row ]; 145 inRow = in->data.C64[ row ]; 146 147 for ( unsigned int col = 0;col < numCols;col++ ) { 148 outRow[ col ] = creal( inRow[ col ] ); 149 } 150 } 151 } else { 152 psError( __func__, "Can not extract real component from given image type (%d).", 153 type ); 154 psFree( out ); 155 return NULL; 156 } 157 158 return out; 159 } 160 161 psImage *psImageImaginary( psImage *out, const psImage* in ) 113 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 114 "Just an image copy was performed."); 115 return psImageCopy(out, in, type); 116 } 117 118 if (type == PS_TYPE_C32) { 119 psF32 *outRow; 120 psC32 *inRow; 121 122 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 123 for (unsigned int row = 0; row < numRows; row++) { 124 outRow = out->data.F32[row]; 125 inRow = in->data.C32[row]; 126 127 for (unsigned int col = 0; col < numCols; col++) { 128 outRow[col] = crealf(inRow[col]); 129 } 130 } 131 } else if (type == PS_TYPE_C64) { 132 psF64 *outRow; 133 psC64 *inRow; 134 135 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 136 for (unsigned int row = 0; row < numRows; row++) { 137 outRow = out->data.F64[row]; 138 inRow = in->data.C64[row]; 139 140 for (unsigned int col = 0; col < numCols; col++) { 141 outRow[col] = creal(inRow[col]); 142 } 143 } 144 } else { 145 psError(__func__, "Can not extract real component from given image type (%d).", type); 146 psFree(out); 147 return NULL; 148 } 149 150 return out; 151 } 152 153 psImage *psImageImaginary(psImage * out, const psImage * in) 162 154 { 163 155 psElemType type; … … 165 157 unsigned int numRows; 166 158 167 168 if ( in == NULL ) { 169 psFree( out ); 159 if (in == NULL) { 160 psFree(out); 170 161 return NULL; 171 162 } … … 176 167 177 168 /* if not a complex number, this is logically just zeroed image of same size */ 178 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {169 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 179 170 // Warn user, as this is probably not expected 180 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "181 "A zero image was returned.");182 out = psImageRecycle( out, numCols, numRows, type);183 memset( out->data.V[ 0 ], 0, PSELEMTYPE_SIZEOF( type ) * numCols * numRows);171 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 172 "A zero image was returned."); 173 out = psImageRecycle(out, numCols, numRows, type); 174 memset(out->data.V[0], 0, PSELEMTYPE_SIZEOF(type) * numCols * numRows); 184 175 return out; 185 176 } 186 177 187 if ( type == PS_TYPE_C32 ) { 188 psF32 * outRow; 189 psC32* inRow; 190 191 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 192 for ( unsigned int row = 0;row < numRows;row++ ) { 193 outRow = out->data.F32[ row ]; 194 inRow = in->data.C32[ row ]; 195 196 for ( unsigned int col = 0;col < numCols;col++ ) { 197 outRow[ col ] = cimagf( inRow[ col ] ); 198 } 199 } 200 } else 201 if ( type == PS_TYPE_C64 ) { 202 psF64 * outRow; 203 psC64* inRow; 204 205 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 206 for ( unsigned int row = 0;row < numRows;row++ ) { 207 outRow = out->data.F64[ row ]; 208 inRow = in->data.C64[ row ]; 209 210 for ( unsigned int col = 0;col < numCols;col++ ) { 211 outRow[ col ] = cimag( inRow[ col ] ); 212 } 213 } 214 } else { 215 psError( __func__, "Can not extract imaginary component from given image type (%d).", 216 type ); 217 psFree( out ); 218 return NULL; 219 } 220 221 return out; 222 } 223 224 psImage *psImageComplex( psImage* out, psImage *real, const psImage *imag ) 178 if (type == PS_TYPE_C32) { 179 psF32 *outRow; 180 psC32 *inRow; 181 182 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 183 for (unsigned int row = 0; row < numRows; row++) { 184 outRow = out->data.F32[row]; 185 inRow = in->data.C32[row]; 186 187 for (unsigned int col = 0; col < numCols; col++) { 188 outRow[col] = cimagf(inRow[col]); 189 } 190 } 191 } else if (type == PS_TYPE_C64) { 192 psF64 *outRow; 193 psC64 *inRow; 194 195 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 196 for (unsigned int row = 0; row < numRows; row++) { 197 outRow = out->data.F64[row]; 198 inRow = in->data.C64[row]; 199 200 for (unsigned int col = 0; col < numCols; col++) { 201 outRow[col] = cimag(inRow[col]); 202 } 203 } 204 } else { 205 psError(__func__, "Can not extract imaginary component from given image type (%d).", type); 206 psFree(out); 207 return NULL; 208 } 209 210 return out; 211 } 212 213 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag) 225 214 { 226 215 psElemType type; … … 228 217 unsigned int numRows; 229 218 230 231 if ( real == NULL || imag == NULL ) { 232 psFree( out ); 219 if (real == NULL || imag == NULL) { 220 psFree(out); 233 221 return NULL; 234 222 } … … 238 226 numRows = real->numRows; 239 227 240 if ( imag->type.type != type ) { 241 psError( __func__, "The inputs to psImageComplex must be the same type." ); 242 psFree( out ); 243 return NULL; 244 } 245 246 if ( imag->numCols != numCols || 247 imag->numRows != numRows ) { 248 psError( __func__, "The inputs to psImageComplex must be the same dimensions." ); 249 psFree( out ); 250 return NULL; 251 } 252 253 if ( PS_IS_PSELEMTYPE_COMPLEX( type ) ) { 254 psError( __func__, "The inputs to psImageComplex can not be complex." ); 255 psFree( out ); 256 return NULL; 257 } 258 259 if ( type != PS_TYPE_F32 && type != PS_TYPE_F64 ) { 260 psError( __func__, "The input type to psImageComplex must be a floating point." ); 261 psFree( out ); 262 return NULL; 263 } 264 265 if ( type == PS_TYPE_F32 ) { 266 psC32 * outRow; 267 psF32* realRow; 268 psF32* imagRow; 269 270 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 271 272 for ( unsigned int row = 0;row < numRows;row++ ) { 273 outRow = out->data.C32[ row ]; 274 realRow = real->data.F32[ row ]; 275 imagRow = imag->data.F32[ row ]; 276 277 for ( unsigned int col = 0;col < numCols;col++ ) { 278 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 279 } 280 } 281 } else 282 if ( type == PS_TYPE_F64 ) { 283 psC64 * outRow; 284 psF64* realRow; 285 psF64* imagRow; 286 287 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 288 for ( unsigned int row = 0;row < numRows;row++ ) { 289 outRow = out->data.C64[ row ]; 290 realRow = real->data.F64[ row ]; 291 imagRow = imag->data.F64[ row ]; 292 293 for ( unsigned int col = 0;col < numCols;col++ ) { 294 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 295 } 296 } 297 } else { 298 psError( __func__, "Can not merge real and imaginary portions for given image type (%d).", 299 type ); 300 psFree( out ); 301 return NULL; 302 } 303 304 return out; 305 } 306 307 psImage *psImageConjugate( psImage *out, const psImage *in ) 228 if (imag->type.type != type) { 229 psError(__func__, "The inputs to psImageComplex must be the same type."); 230 psFree(out); 231 return NULL; 232 } 233 234 if (imag->numCols != numCols || imag->numRows != numRows) { 235 psError(__func__, "The inputs to psImageComplex must be the same dimensions."); 236 psFree(out); 237 return NULL; 238 } 239 240 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 241 psError(__func__, "The inputs to psImageComplex can not be complex."); 242 psFree(out); 243 return NULL; 244 } 245 246 if (type != PS_TYPE_F32 && type != PS_TYPE_F64) { 247 psError(__func__, "The input type to psImageComplex must be a floating point."); 248 psFree(out); 249 return NULL; 250 } 251 252 if (type == PS_TYPE_F32) { 253 psC32 *outRow; 254 psF32 *realRow; 255 psF32 *imagRow; 256 257 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 258 259 for (unsigned int row = 0; row < numRows; row++) { 260 outRow = out->data.C32[row]; 261 realRow = real->data.F32[row]; 262 imagRow = imag->data.F32[row]; 263 264 for (unsigned int col = 0; col < numCols; col++) { 265 outRow[col] = realRow[col] + I * imagRow[col]; 266 } 267 } 268 } else if (type == PS_TYPE_F64) { 269 psC64 *outRow; 270 psF64 *realRow; 271 psF64 *imagRow; 272 273 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 274 for (unsigned int row = 0; row < numRows; row++) { 275 outRow = out->data.C64[row]; 276 realRow = real->data.F64[row]; 277 imagRow = imag->data.F64[row]; 278 279 for (unsigned int col = 0; col < numCols; col++) { 280 outRow[col] = realRow[col] + I * imagRow[col]; 281 } 282 } 283 } else { 284 psError(__func__, "Can not merge real and imaginary portions for given image type (%d).", type); 285 psFree(out); 286 return NULL; 287 } 288 289 return out; 290 } 291 292 psImage *psImageConjugate(psImage * out, const psImage * in) 308 293 { 309 294 psElemType type; … … 311 296 unsigned int numRows; 312 297 313 314 if ( in == NULL ) { 315 psFree( out ); 298 if (in == NULL) { 299 psFree(out); 316 300 return NULL; 317 301 } … … 322 306 323 307 /* if not a complex number, this is logically just a image copy */ 324 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {308 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 325 309 // Warn user, as this is probably not expected 326 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 327 "Image copy was performed instead." ); 328 return psImageCopy( out, in, type ); 329 } 330 331 if ( type == PS_TYPE_C32 ) { 332 psC32 * outRow; 333 psC32* inRow; 334 335 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 336 for ( unsigned int row = 0;row < numRows;row++ ) { 337 outRow = out->data.C32[ row ]; 338 inRow = in->data.C32[ row ]; 339 340 for ( unsigned int col = 0;col < numCols;col++ ) { 341 outRow[ col ] = crealf( inRow[ col ] ) - I * cimagf( inRow[ col ] ); 342 } 343 } 344 } else 345 if ( type == PS_TYPE_C64 ) { 346 psC64 * outRow; 347 psC64* inRow; 348 349 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 350 for ( unsigned int row = 0;row < numRows;row++ ) { 351 outRow = out->data.C64[ row ]; 352 inRow = in->data.C64[ row ]; 353 354 for ( unsigned int col = 0;col < numCols;col++ ) { 355 outRow[ col ] = creal( inRow[ col ] ) - I * cimag( inRow[ col ] ); 356 } 357 } 358 } else { 359 psError( __func__, "Can not compute complex conjugate for given image type (%d).", 360 type ); 361 psFree( out ); 362 return NULL; 363 } 364 365 return out; 366 } 367 368 psImage *psImagePowerSpectrum( psImage* out, const psImage* in ) 310 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 311 "Image copy was performed instead."); 312 return psImageCopy(out, in, type); 313 } 314 315 if (type == PS_TYPE_C32) { 316 psC32 *outRow; 317 psC32 *inRow; 318 319 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 320 for (unsigned int row = 0; row < numRows; row++) { 321 outRow = out->data.C32[row]; 322 inRow = in->data.C32[row]; 323 324 for (unsigned int col = 0; col < numCols; col++) { 325 outRow[col] = crealf(inRow[col]) - I * cimagf(inRow[col]); 326 } 327 } 328 } else if (type == PS_TYPE_C64) { 329 psC64 *outRow; 330 psC64 *inRow; 331 332 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 333 for (unsigned int row = 0; row < numRows; row++) { 334 outRow = out->data.C64[row]; 335 inRow = in->data.C64[row]; 336 337 for (unsigned int col = 0; col < numCols; col++) { 338 outRow[col] = creal(inRow[col]) - I * cimag(inRow[col]); 339 } 340 } 341 } else { 342 psError(__func__, "Can not compute complex conjugate for given image type (%d).", type); 343 psFree(out); 344 return NULL; 345 } 346 347 return out; 348 } 349 350 psImage *psImagePowerSpectrum(psImage * out, const psImage * in) 369 351 { 370 352 psElemType type; … … 373 355 int numElementsSquared; 374 356 375 if ( in == NULL) {376 psFree( out);357 if (in == NULL) { 358 psFree(out); 377 359 return NULL; 378 360 } … … 384 366 385 367 /* if not a complex number, this is not implemented */ 386 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {387 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");388 psFree( out);389 return NULL; 390 } 391 392 if ( type == PS_TYPE_C32) {393 psF32 * outRow;394 psC32 *inRow;368 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 369 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 370 psFree(out); 371 return NULL; 372 } 373 374 if (type == PS_TYPE_C32) { 375 psF32 *outRow; 376 psC32 *inRow; 395 377 psF32 real; 396 378 psF32 imag; 397 379 398 399 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 400 for ( unsigned int row = 0;row < numRows;row++ ) { 401 outRow = out->data.F32[ row ]; 402 inRow = in->data.C32[ row ]; 403 404 for ( unsigned int col = 0;col < numCols;col++ ) { 405 real = crealf( inRow[ col ] ); 406 imag = cimagf( inRow[ col ] ); 407 outRow[ col ] = ( real * real + imag * imag ) / numElementsSquared; 408 } 409 } 410 } else 411 if ( type == PS_TYPE_C64 ) { 412 psF64 * outRow; 413 psC64* inRow; 414 psF64 real; 415 psF64 imag; 416 417 418 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 419 for ( unsigned int row = 0;row < numRows;row++ ) { 420 outRow = out->data.F64[ row ]; 421 inRow = in->data.C64[ row ]; 422 423 for ( unsigned int col = 0;col < numCols;col++ ) { 424 real = crealf( inRow[ col ] ); 425 imag = cimagf( inRow[ col ] ); 426 outRow[ col ] = real * real + imag * imag / numElementsSquared; 427 } 428 } 429 } else { 430 psError( __func__, "Can not power spectrum for given image type (%d).", 431 type ); 432 psFree( out ); 433 return NULL; 434 } 380 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 381 for (unsigned int row = 0; row < numRows; row++) { 382 outRow = out->data.F32[row]; 383 inRow = in->data.C32[row]; 384 385 for (unsigned int col = 0; col < numCols; col++) { 386 real = crealf(inRow[col]); 387 imag = cimagf(inRow[col]); 388 outRow[col] = (real * real + imag * imag) / numElementsSquared; 389 } 390 } 391 } else if (type == PS_TYPE_C64) { 392 psF64 *outRow; 393 psC64 *inRow; 394 psF64 real; 395 psF64 imag; 396 397 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 398 for (unsigned int row = 0; row < numRows; row++) { 399 outRow = out->data.F64[row]; 400 inRow = in->data.C64[row]; 401 402 for (unsigned int col = 0; col < numCols; col++) { 403 real = crealf(inRow[col]); 404 imag = cimagf(inRow[col]); 405 outRow[col] = real * real + imag * imag / numElementsSquared; 406 } 407 } 408 } else { 409 psError(__func__, "Can not power spectrum for given image type (%d).", type); 410 psFree(out); 411 return NULL; 412 } 435 413 436 414 return out; … … 440 418 /************************************** Vector Functions ***************************************/ 441 419 442 psVector * psVectorFFT( psVector* out, const psVector* in, psFftDirection direction)420 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction) 443 421 { 444 422 unsigned int numElements; … … 447 425 448 426 /* got good image data? */ 449 if ( in == NULL ) { 450 psFree( out ); 451 return NULL; 452 } 453 454 type = in->type.type; 455 456 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 457 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 458 type ); 459 psFree( out ); 460 return NULL; 461 } 462 463 if ( ( type != PS_TYPE_C32 ) && ( direction == PS_FFT_REVERSE ) ) { 464 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 465 type ); 466 psFree( out ); 467 return NULL; 468 469 } 470 471 if ( ( type != PS_TYPE_F32 ) && ( direction == PS_FFT_FORWARD ) ) { 472 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 473 type ); 474 psFree( out ); 427 if (in == NULL) { 428 psFree(out); 429 return NULL; 430 } 431 432 type = in->type.type; 433 434 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 435 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 436 psFree(out); 437 return NULL; 438 } 439 440 if ((type != PS_TYPE_C32) && (direction == PS_FFT_REVERSE)) { 441 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 442 psFree(out); 443 return NULL; 444 445 } 446 447 if ((type != PS_TYPE_F32) && (direction == PS_FFT_FORWARD)) { 448 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 449 psFree(out); 475 450 return NULL; 476 451 } 477 452 478 453 /* make sure the system-level wisdom information is imported. */ 479 if ( ! p_fftwWisdomImported) {454 if (!p_fftwWisdomImported) { 480 455 fftwf_import_system_wisdom(); 481 456 p_fftwWisdomImported = true; … … 484 459 numElements = in->n; 485 460 486 out = psVectorRecycle( out, numElements, PS_TYPE_C32);461 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 487 462 out->n = numElements; 488 463 489 if ( type == PS_TYPE_F32) {464 if (type == PS_TYPE_F32) { 490 465 // need to convert to complex 491 psC32 * outVec = out->data.C32;492 psF32 *inVec = in->data.F32;493 for ( unsigned int i = 0;i < numElements;i++ ) { 494 outVec[ i ] = inVec[ i ];495 }496 } else {497 psC32* outVec = out->data.C32;498 psC32 * inVec = in->data.C32;499 for ( unsigned int i = 0;i < numElements;i++ ) {500 outVec[ i ] = inVec[ i ]; 501 }502 }503 504 plan = fftwf_plan_dft_1d( numElements,505 ( fftwf_complex* ) out->data.C32, 506 ( fftwf_complex* ) out->data.C32,507 direction,508 P_FFTW_PLAN_RIGOR);509 510 /* check if a plan exists now */511 if ( plan == NULL) {512 psError( __func__, "Failed to create FFTW plan.");513 psFree( out);466 psC32 *outVec = out->data.C32; 467 psF32 *inVec = in->data.F32; 468 469 for (unsigned int i = 0; i < numElements; i++) { 470 outVec[i] = inVec[i]; 471 } 472 } else { 473 psC32 *outVec = out->data.C32; 474 psC32 *inVec = in->data.C32; 475 476 for (unsigned int i = 0; i < numElements; i++) { 477 outVec[i] = inVec[i]; 478 } 479 } 480 481 plan = fftwf_plan_dft_1d(numElements, 482 (fftwf_complex *) out->data.C32, 483 (fftwf_complex *) out->data.C32, direction, P_FFTW_PLAN_RIGOR); 484 485 /* check if a plan exists now */ 486 if (plan == NULL) { 487 psError(__func__, "Failed to create FFTW plan."); 488 psFree(out); 514 489 return NULL; 515 490 } 516 491 517 492 /* finally, call FFTW with the plan made above */ 518 fftwf_execute( plan ); 519 520 fftwf_destroy_plan( plan ); 521 522 return out; 523 } 524 525 526 psVector *psVectorReal( psVector *out, const psVector* in ) 493 fftwf_execute(plan); 494 495 fftwf_destroy_plan(plan); 496 497 return out; 498 } 499 500 psVector *psVectorReal(psVector * out, const psVector * in) 527 501 { 528 502 psElemType type; 529 503 unsigned int numElements; 530 504 531 if ( in == NULL) {532 psFree( out);505 if (in == NULL) { 506 psFree(out); 533 507 return NULL; 534 508 } … … 538 512 539 513 /* if not a complex number, this is logically just a copy */ 540 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {514 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 541 515 // Warn user, as this is probably not expected 542 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. "543 "Just a vector copy was performed.");544 out = psVectorRecycle( out, numElements, type);516 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 517 "Just a vector copy was performed."); 518 out = psVectorRecycle(out, numElements, type); 545 519 out->n = numElements; 546 memcpy( out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF( type ));520 memcpy(out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF(type)); 547 521 return out; 548 522 } 549 523 550 if ( type == PS_TYPE_C32) {551 psF32 * outVec;552 psC32 *inVec = in->data.C32;553 554 out = psVectorRecycle( out, numElements, PS_TYPE_F32);524 if (type == PS_TYPE_C32) { 525 psF32 *outVec; 526 psC32 *inVec = in->data.C32; 527 528 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 555 529 out->n = numElements; 556 530 outVec = out->data.F32; 557 531 558 for ( unsigned int i = 0;i < numElements;i++ ) { 559 outVec[ i ] = crealf( inVec[ i ] ); 560 } 561 } else { 562 psError( __func__, "Can not extract real component from given vector type (%d).", 563 type ); 564 psFree( out ); 565 return NULL; 566 } 567 568 return out; 569 } 570 571 psVector *psVectorImaginary( psVector *out, const psVector* in ) 532 for (unsigned int i = 0; i < numElements; i++) { 533 outVec[i] = crealf(inVec[i]); 534 } 535 } else { 536 psError(__func__, "Can not extract real component from given vector type (%d).", type); 537 psFree(out); 538 return NULL; 539 } 540 541 return out; 542 } 543 544 psVector *psVectorImaginary(psVector * out, const psVector * in) 572 545 { 573 546 psElemType type; 574 547 unsigned int numElements; 575 548 576 577 if ( in == NULL ) { 578 psFree( out ); 549 if (in == NULL) { 550 psFree(out); 579 551 return NULL; 580 552 } … … 584 556 585 557 /* if not a complex number, this is logically just zeroed image of same size */ 586 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {558 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 587 559 // Warn user, as this is probably not expected 588 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "589 "A zeroed vector was returned.");590 out = psVectorRecycle( out, numElements, type);560 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 561 "A zeroed vector was returned."); 562 out = psVectorRecycle(out, numElements, type); 591 563 out->n = numElements; 592 memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements);564 memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements); 593 565 return out; 594 566 } 595 567 596 if ( type == PS_TYPE_C32) {597 psF32 * outVec;598 psC32 *inVec = in->data.C32;599 600 out = psVectorRecycle( out, numElements, PS_TYPE_F32);568 if (type == PS_TYPE_C32) { 569 psF32 *outVec; 570 psC32 *inVec = in->data.C32; 571 572 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 601 573 out->n = numElements; 602 574 outVec = out->data.F32; 603 575 604 for ( unsigned int i = 0;i < numElements;i++ ) { 605 outVec[ i ] = cimagf( inVec[ i ] ); 606 } 607 } else { 608 psError( __func__, "Can not extract imaginary component from given vector type (%d).", 609 type ); 610 psFree( out ); 611 return NULL; 612 } 613 614 return out; 615 } 616 617 psVector *psVectorComplex( psVector* out, psVector *real, const psVector *imag ) 576 for (unsigned int i = 0; i < numElements; i++) { 577 outVec[i] = cimagf(inVec[i]); 578 } 579 } else { 580 psError(__func__, "Can not extract imaginary component from given vector type (%d).", type); 581 psFree(out); 582 return NULL; 583 } 584 585 return out; 586 } 587 588 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag) 618 589 { 619 590 psElemType type; 620 591 unsigned int numElements; 621 592 622 623 if ( real == NULL || imag == NULL ) { 624 psFree( out ); 593 if (real == NULL || imag == NULL) { 594 psFree(out); 625 595 return NULL; 626 596 } 627 597 628 598 type = real->type.type; 629 if ( real->n < imag->n) {599 if (real->n < imag->n) { 630 600 numElements = real->n; 631 601 } else { … … 633 603 } 634 604 635 if ( imag->type.type != type) {636 psError( __func__, "The inputs to psVectorComplex must be the same type.");637 psFree( out);638 return NULL; 639 } 640 641 if ( PS_IS_PSELEMTYPE_COMPLEX( type )) {642 psError( __func__, "The inputs to psVectorComplex can not be complex.");643 psFree( out);644 return NULL; 645 } 646 647 if ( type == PS_TYPE_F32) {648 psC32 * outVec;649 psF32 *realVec = real->data.F32;650 psF32 *imagVec = imag->data.F32;651 652 out = psVectorRecycle( out, numElements, PS_TYPE_C32);605 if (imag->type.type != type) { 606 psError(__func__, "The inputs to psVectorComplex must be the same type."); 607 psFree(out); 608 return NULL; 609 } 610 611 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 612 psError(__func__, "The inputs to psVectorComplex can not be complex."); 613 psFree(out); 614 return NULL; 615 } 616 617 if (type == PS_TYPE_F32) { 618 psC32 *outVec; 619 psF32 *realVec = real->data.F32; 620 psF32 *imagVec = imag->data.F32; 621 622 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 653 623 out->n = numElements; 654 624 outVec = out->data.C32; 655 625 656 for ( unsigned int i = 0;i < numElements;i++ ) { 657 outVec[ i ] = realVec[ i ] + I * imagVec[ i ]; 658 } 659 } else { 660 psError( __func__, "Can not merge real and imaginary portions for given vector type (%d).", 661 type ); 662 psFree( out ); 663 return NULL; 664 } 665 666 return out; 667 } 668 669 psVector *psVectorConjugate( psVector *out, const psVector *in ) 626 for (unsigned int i = 0; i < numElements; i++) { 627 outVec[i] = realVec[i] + I * imagVec[i]; 628 } 629 } else { 630 psError(__func__, "Can not merge real and imaginary portions for given vector type (%d).", type); 631 psFree(out); 632 return NULL; 633 } 634 635 return out; 636 } 637 638 psVector *psVectorConjugate(psVector * out, const psVector * in) 670 639 { 671 640 psElemType type; 672 641 unsigned int numElements; 673 642 674 675 if ( in == NULL ) { 676 psFree( out ); 643 if (in == NULL) { 644 psFree(out); 677 645 return NULL; 678 646 } … … 682 650 683 651 /* if not a complex number, this is logically just a image copy */ 684 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {652 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 685 653 // Warn user, as this is probably not expected 686 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. "687 "Vector copy was performed instead.");688 689 out = psVectorRecycle( out, numElements, type);654 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 655 "Vector copy was performed instead."); 656 657 out = psVectorRecycle(out, numElements, type); 690 658 out->n = numElements; 691 memcpy( out->data.V, in->data.V, PSELEMTYPE_SIZEOF( type ) * numElements);659 memcpy(out->data.V, in->data.V, PSELEMTYPE_SIZEOF(type) * numElements); 692 660 return out; 693 661 } 694 662 695 if ( type == PS_TYPE_C32) {696 psC32 * outVec;697 psC32 *inVec = in->data.C32;698 699 out = psVectorRecycle( out, numElements, PS_TYPE_C32);663 if (type == PS_TYPE_C32) { 664 psC32 *outVec; 665 psC32 *inVec = in->data.C32; 666 667 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 700 668 out->n = numElements; 701 669 outVec = out->data.C32; 702 670 703 for ( unsigned int i = 0;i < numElements;i++ ) { 704 outVec[ i ] = crealf( inVec[ i ] ) - I * cimagf( inVec[ i ] ); 705 } 706 } else { 707 psError( __func__, "Can not compute complex conjugate for given vector type (%d).", 708 type ); 709 psFree( out ); 710 return NULL; 711 } 712 713 return out; 714 } 715 716 psVector *psVectorPowerSpectrum( psVector* out, const psVector* in ) 671 for (unsigned int i = 0; i < numElements; i++) { 672 outVec[i] = crealf(inVec[i]) - I * cimagf(inVec[i]); 673 } 674 } else { 675 psError(__func__, "Can not compute complex conjugate for given vector type (%d).", type); 676 psFree(out); 677 return NULL; 678 } 679 680 return out; 681 } 682 683 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in) 717 684 { 718 685 psElemType type; … … 722 689 unsigned int inNumElementsSquared; 723 690 724 if ( in == NULL) {725 psFree( out);691 if (in == NULL) { 692 psFree(out); 726 693 return NULL; 727 694 } … … 734 701 735 702 /* if not a complex number, this is not implemented */ 736 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {737 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");738 psFree( out);739 return NULL; 740 } 741 742 if ( type == PS_TYPE_C32) {743 psF32 * outVec;744 psC32 *inVec = in->data.C32;703 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 704 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 705 psFree(out); 706 return NULL; 707 } 708 709 if (type == PS_TYPE_C32) { 710 psF32 *outVec; 711 psC32 *inVec = in->data.C32; 745 712 psF32 inAbs1; 746 713 psF32 inAbs2; 747 714 748 out = psVectorRecycle( out, outNumElements, PS_TYPE_F32);715 out = psVectorRecycle(out, outNumElements, PS_TYPE_F32); 749 716 out->n = outNumElements; 750 717 outVec = out->data.F32; 751 718 752 719 // from ADD: P_0 = |C_0|^2/N^2 753 inAbs1 = cabsf( inVec[ 0 ]);754 outVec[ 0] = inAbs1 * inAbs1 / inNumElementsSquared;720 inAbs1 = cabsf(inVec[0]); 721 outVec[0] = inAbs1 * inAbs1 / inNumElementsSquared; 755 722 756 723 // from ADD: P_j = (|C_j|^2+|C_N-j|^2)/N^2, where j = 1,2,...,(N/2-1) 757 for ( unsigned int i = 1;i < inHalfNumElements;i++) {758 inAbs1 = cabsf( inVec[ i ]);759 inAbs2 = cabsf( inVec[ inNumElements - i ]);760 outVec[ i ] = ( inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared;724 for (unsigned int i = 1; i < inHalfNumElements; i++) { 725 inAbs1 = cabsf(inVec[i]); 726 inAbs2 = cabsf(inVec[inNumElements - i]); 727 outVec[i] = (inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared; 761 728 } 762 729 763 730 // from ADD: P_N/2 = |C_N/2|^2/N^2 764 inAbs1 = cabsf( inVec[ inHalfNumElements ] ); 765 outVec[ inHalfNumElements ] = inAbs1 * inAbs1 / inNumElementsSquared; 766 } else { 767 psError( __func__, "Can not power spectrum for given vector type (%d).", 768 type ); 769 psFree( out ); 770 return NULL; 771 } 772 773 return out; 774 775 } 731 inAbs1 = cabsf(inVec[inHalfNumElements]); 732 outVec[inHalfNumElements] = inAbs1 * inAbs1 / inNumElementsSquared; 733 } else { 734 psError(__func__, "Can not power spectrum for given vector type (%d).", type); 735 psFree(out); 736 return NULL; 737 } 738 739 return out; 740 741 } -
trunk/psLib/src/dataManip/psFFT.h
r1406 r1407 1 1 2 /** @file psFFT.h 2 3 * … … 7 8 * @author Robert DeSonia, MHPCC 8 9 * 9 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 14 15 15 16 #ifndef PS_FFT_H 16 # define PS_FFT_H17 # define PS_FFT_H 17 18 18 # include "psImage.h"19 # include "psVector.h"19 # include "psImage.h" 20 # include "psVector.h" 20 21 21 22 /// @addtogroup Transform … … 24 25 /** Details on FFT implementation (private). */ 25 26 26 27 27 typedef enum { 28 // / psImageFFT/psVectorFFT should perform a forward FFT.28 // / psImageFFT/psVectorFFT should perform a forward FFT. 29 29 PS_FFT_FORWARD = (-1), 30 30 31 // /< psImageFFT/psVectorFFT should perform a reverse FFT.31 // /< psImageFFT/psVectorFFT should perform a reverse FFT. 32 32 PS_FFT_REVERSE = (+1) 33 33 } psFftDirection; 34 34 35 psImage * psImageFFT(psImage* out, const psImage* in, psFftDirection direction);36 psImage * psImageReal(psImage *out, const psImage* in);37 psImage * psImageImaginary(psImage *out, const psImage* in);38 psImage * psImageComplex(psImage* out, psImage *real, const psImage *imag);39 psImage * psImageConjugate(psImage *out, const psImage *in);40 psImage * psImagePowerSpectrum(psImage* out, const psImage* in);35 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction); 36 psImage *psImageReal(psImage * out, const psImage * in); 37 psImage *psImageImaginary(psImage * out, const psImage * in); 38 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag); 39 psImage *psImageConjugate(psImage * out, const psImage * in); 40 psImage *psImagePowerSpectrum(psImage * out, const psImage * in); 41 41 42 psVector * psVectorFFT(psVector* out, const psVector* in, psFftDirection direction);43 psVector * psVectorReal(psVector* out, const psVector* in);44 psVector * psVectorImaginary(psVector* out, const psVector* in);45 psVector * psVectorComplex(psVector* out, psVector* real, const psVector* imag);46 psVector * psVectorConjugate(psVector* out, const psVector* in);47 psVector * psVectorPowerSpectrum(psVector* out, const psVector* in);42 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction); 43 psVector *psVectorReal(psVector * out, const psVector * in); 44 psVector *psVectorImaginary(psVector * out, const psVector * in); 45 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag); 46 psVector *psVectorConjugate(psVector * out, const psVector * in); 47 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in); 48 48 49 49 /// @} 50 50 51 51 #endif 52 -
trunk/psLib/src/dataManip/psFunctions.c
r1406 r1407 1 1 2 /** @file psFunctions.c 2 3 * … … 7 8 * polynomials. It also contains a Gaussian functions. 8 9 * 9 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 13 14 */ 14 /*****************************************************************************/ 15 16 /*****************************************************************************/ 17 15 18 /* INCLUDE FILES */ 19 16 20 /*****************************************************************************/ 17 21 #include <stdlib.h> … … 31 35 #include <gsl/gsl_rng.h> 32 36 #include <gsl/gsl_randist.h> 33 /*****************************************************************************/ 37 38 /*****************************************************************************/ 39 34 40 /* DEFINE STATEMENTS */ 41 35 42 /*****************************************************************************/ 36 43 … … 38 45 39 46 /*****************************************************************************/ 47 40 48 /* TYPE DEFINITIONS */ 41 /*****************************************************************************/ 42 static void polynomial1DFree(psPolynomial1D *myPoly); 43 static void polynomial2DFree(psPolynomial2D *myPoly); 44 static void polynomial3DFree(psPolynomial3D *myPoly); 45 static void polynomial4DFree(psPolynomial4D *myPoly); 46 static void dPolynomial1DFree(psDPolynomial1D *myPoly); 47 static void dPolynomial2DFree(psDPolynomial2D *myPoly); 48 static void dPolynomial3DFree(psDPolynomial3D *myPoly); 49 static void dPolynomial4DFree(psDPolynomial4D *myPoly); 50 51 /*****************************************************************************/ 49 50 /*****************************************************************************/ 51 static void polynomial1DFree(psPolynomial1D * myPoly); 52 static void polynomial2DFree(psPolynomial2D * myPoly); 53 static void polynomial3DFree(psPolynomial3D * myPoly); 54 static void polynomial4DFree(psPolynomial4D * myPoly); 55 static void dPolynomial1DFree(psDPolynomial1D * myPoly); 56 static void dPolynomial2DFree(psDPolynomial2D * myPoly); 57 static void dPolynomial3DFree(psDPolynomial3D * myPoly); 58 static void dPolynomial4DFree(psDPolynomial4D * myPoly); 59 60 /*****************************************************************************/ 61 52 62 /* GLOBAL VARIABLES */ 63 53 64 /*****************************************************************************/ 54 65 … … 56 67 57 68 /*****************************************************************************/ 69 58 70 /* FILE STATIC VARIABLES */ 71 59 72 /*****************************************************************************/ 60 73 … … 62 75 63 76 /*****************************************************************************/ 77 64 78 /* FUNCTION IMPLEMENTATION - LOCAL */ 79 65 80 /*****************************************************************************/ 66 81 … … 68 83 69 84 /*****************************************************************************/ 85 70 86 /* FUNCTION IMPLEMENTATION - PUBLIC */ 87 71 88 /*****************************************************************************/ 72 89 … … 76 93 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] 77 94 *****************************************************************************/ 78 float 79 psGaussian(float x, 80 float mean, 81 float sigma, 82 bool normal) 95 float psGaussian(float x, float mean, float sigma, bool normal) 83 96 { 84 97 float tmp = 1.0; … … 94 107 } 95 108 96 return (tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));109 return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma))); 97 110 } 98 111 … … 107 120 NOTE: There is no way to seed the random generator. 108 121 *****************************************************************************/ 109 psVector *psGaussianDev(float mean, 110 float sigma, 111 int Npts) 122 psVector *psGaussianDev(float mean, float sigma, int Npts) 112 123 { 113 124 psVector *gauss = NULL; … … 127 138 128 139 // NOTE: Should I free r as well? 129 return(gauss); 130 } 131 140 return (gauss); 141 } 132 142 133 143 /***************************************************************************** … … 140 150 141 151 newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D)); 142 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial1DFree);152 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree); 143 153 newPoly->n = n; 144 newPoly->coeff = (float *)psAlloc(n * sizeof(float));145 newPoly->coeffErr = (float *) psAlloc(n * sizeof(float));146 newPoly->mask = (char *)psAlloc(n * sizeof(char));147 for (i =0;i<n;i++) {154 newPoly->coeff = (float *)psAlloc(n * sizeof(float)); 155 newPoly->coeffErr = (float *)psAlloc(n * sizeof(float)); 156 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 157 for (i = 0; i < n; i++) { 148 158 newPoly->coeff[i] = 0.0; 149 159 newPoly->coeffErr[i] = 0.0; … … 151 161 } 152 162 153 return (newPoly);163 return (newPoly); 154 164 } 155 165 … … 161 171 162 172 newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D)); 163 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial2DFree);173 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree); 164 174 newPoly->nX = nX; 165 175 newPoly->nY = nY; 166 176 167 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *));168 newPoly->coeffErr = (float **) psAlloc(nX * sizeof(float *));169 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));170 for (x =0;x<nX;x++) {171 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float));172 newPoly->coeffErr[x] = (float *) psAlloc(nY * sizeof(float));173 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));174 } 175 for (x =0;x<nX;x++) {176 for (y =0;y<nY;y++) {177 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *)); 178 newPoly->coeffErr = (float **)psAlloc(nX * sizeof(float *)); 179 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 180 for (x = 0; x < nX; x++) { 181 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float)); 182 newPoly->coeffErr[x] = (float *)psAlloc(nY * sizeof(float)); 183 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 184 } 185 for (x = 0; x < nX; x++) { 186 for (y = 0; y < nY; y++) { 177 187 newPoly->coeff[x][y] = 0.0; 178 188 newPoly->coeffErr[x][y] = 0.0; … … 181 191 } 182 192 183 return (newPoly);193 return (newPoly); 184 194 } 185 195 … … 192 202 193 203 newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D)); 194 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial3DFree);204 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree); 195 205 newPoly->nX = nX; 196 206 newPoly->nY = nY; 197 207 newPoly->nZ = nZ; 198 208 199 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **));200 newPoly->coeffErr = (float ***) psAlloc(nX * sizeof(float **));201 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));202 for (x =0;x<nX;x++) {203 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *));204 newPoly->coeffErr[x] = (float **) psAlloc(nY * sizeof(float *));205 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));206 for (y =0;y<nY;y++) {207 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float));208 newPoly->coeffErr[x][y] = (float *) psAlloc(nZ * sizeof(float));209 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));210 } 211 } 212 for (x =0;x<nX;x++) {213 for (y =0;y<nY;y++) {214 for (z =0;z<nZ;z++) {209 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **)); 210 newPoly->coeffErr = (float ***)psAlloc(nX * sizeof(float **)); 211 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 212 for (x = 0; x < nX; x++) { 213 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *)); 214 newPoly->coeffErr[x] = (float **)psAlloc(nY * sizeof(float *)); 215 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 216 for (y = 0; y < nY; y++) { 217 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float)); 218 newPoly->coeffErr[x][y] = (float *)psAlloc(nZ * sizeof(float)); 219 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 220 } 221 } 222 for (x = 0; x < nX; x++) { 223 for (y = 0; y < nY; y++) { 224 for (z = 0; z < nZ; z++) { 215 225 newPoly->coeff[x][y][z] = 0.0; 216 226 newPoly->coeffErr[x][y][z] = 0.0; … … 220 230 } 221 231 222 return (newPoly);232 return (newPoly); 223 233 } 224 234 … … 232 242 233 243 newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D)); 234 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial4DFree);244 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree); 235 245 newPoly->nW = nW; 236 246 newPoly->nX = nX; … … 238 248 newPoly->nZ = nZ; 239 249 240 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***));241 newPoly->coeffErr = (float ****) psAlloc(nW * sizeof(float ***));242 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));243 for (w =0;w<nW;w++) {244 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **));245 newPoly->coeffErr[w] = (float ***) psAlloc(nX * sizeof(float **));246 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));247 for (x =0;x<nX;x++) {248 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *));249 newPoly->coeffErr[w][x] = (float **) psAlloc(nY * sizeof(float *));250 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));251 for (y =0;y<nY;y++) {252 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float));253 newPoly->coeffErr[w][x][y] = (float *) psAlloc(nZ * sizeof(float));254 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));255 } 256 } 257 } 258 for (w =0;w<nW;w++) {259 for (x =0;x<nX;x++) {260 for (y =0;y<nY;y++) {261 for (z =0;z<nZ;z++) {250 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***)); 251 newPoly->coeffErr = (float ****)psAlloc(nW * sizeof(float ***)); 252 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 253 for (w = 0; w < nW; w++) { 254 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **)); 255 newPoly->coeffErr[w] = (float ***)psAlloc(nX * sizeof(float **)); 256 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 257 for (x = 0; x < nX; x++) { 258 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *)); 259 newPoly->coeffErr[w][x] = (float **)psAlloc(nY * sizeof(float *)); 260 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 261 for (y = 0; y < nY; y++) { 262 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 263 newPoly->coeffErr[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 264 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 265 } 266 } 267 } 268 for (w = 0; w < nW; w++) { 269 for (x = 0; x < nX; x++) { 270 for (y = 0; y < nY; y++) { 271 for (z = 0; z < nZ; z++) { 262 272 newPoly->coeff[w][x][y][z] = 0.0; 263 273 newPoly->coeffErr[w][x][y][z] = 0.0; … … 268 278 } 269 279 270 return (newPoly);271 } 272 273 static void polynomial1DFree(psPolynomial1D * myPoly)280 return (newPoly); 281 } 282 283 static void polynomial1DFree(psPolynomial1D * myPoly) 274 284 { 275 285 psFree(myPoly->coeff); … … 278 288 } 279 289 280 static void polynomial2DFree(psPolynomial2D * myPoly)281 { 282 int x = 0; 283 284 for (x =0;x<myPoly->nX;x++) {290 static void polynomial2DFree(psPolynomial2D * myPoly) 291 { 292 int x = 0; 293 294 for (x = 0; x < myPoly->nX; x++) { 285 295 psFree(myPoly->coeff[x]); 286 296 psFree(myPoly->coeffErr[x]); … … 292 302 } 293 303 294 static void polynomial3DFree(psPolynomial3D * myPoly)295 { 296 int x = 0; 297 int y = 0; 298 299 for (x =0;x<myPoly->nX;x++) {300 for (y =0;y<myPoly->nY;y++) {304 static void polynomial3DFree(psPolynomial3D * myPoly) 305 { 306 int x = 0; 307 int y = 0; 308 309 for (x = 0; x < myPoly->nX; x++) { 310 for (y = 0; y < myPoly->nY; y++) { 301 311 psFree(myPoly->coeff[x][y]); 302 312 psFree(myPoly->coeffErr[x][y]); … … 313 323 } 314 324 315 static void polynomial4DFree(psPolynomial4D * myPoly)325 static void polynomial4DFree(psPolynomial4D * myPoly) 316 326 { 317 327 int w = 0; … … 319 329 int y = 0; 320 330 321 for (w =0;w<myPoly->nW;w++) {322 for (x =0;x<myPoly->nX;x++) {323 for (y =0;y<myPoly->nY;y++) {331 for (w = 0; w < myPoly->nW; w++) { 332 for (x = 0; x < myPoly->nX; x++) { 333 for (y = 0; y < myPoly->nY; y++) { 324 334 psFree(myPoly->coeff[w][x][y]); 325 335 psFree(myPoly->coeffErr[w][x][y]); … … 343 353 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 344 354 *****************************************************************************/ 345 float 346 psPolynomial1DEval(float x, 347 const psPolynomial1D *myPoly) 355 float psPolynomial1DEval(float x, const psPolynomial1D * myPoly) 348 356 { 349 357 int loop_x = 0; … … 355 363 } 356 364 357 358 365 // NOTE: Do we want to flag this case? 359 366 if (myPoly->n == 0) { 360 return (1.0);367 return (1.0); 361 368 } 362 369 … … 365 372 } 366 373 367 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 368 polySum+= xSum * myPoly->coeff[loop_x]; 369 xSum*=x; 370 } 371 372 return(polySum); 373 } 374 375 376 float 377 psPolynomial2DEval(float x, 378 float y, 379 const psPolynomial2D *myPoly) 374 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 375 polySum += xSum * myPoly->coeff[loop_x]; 376 xSum *= x; 377 } 378 379 return (polySum); 380 } 381 382 float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly) 380 383 { 381 384 int loop_x = 0; … … 385 388 float ySum = 1.0; 386 389 387 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {390 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 388 391 ySum = xSum; 389 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 390 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 391 ySum*=y; 392 } 393 xSum*=x; 394 } 395 396 return(polySum); 397 } 398 399 float 400 psPolynomial3DEval(float x, 401 float y, 402 float z, 403 const psPolynomial3D *myPoly) 392 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 393 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 394 ySum *= y; 395 } 396 xSum *= x; 397 } 398 399 return (polySum); 400 } 401 402 float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly) 404 403 { 405 404 int loop_x = 0; … … 411 410 float zSum = 1.0; 412 411 413 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {412 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 414 413 ySum = xSum; 415 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {414 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 416 415 zSum = ySum; 417 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 418 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 419 zSum*=z; 420 } 421 ySum*=y; 422 } 423 xSum*=x; 424 } 425 426 return(polySum); 427 } 428 429 float 430 psPolynomial4DEval(float w, 431 float x, 432 float y, 433 float z, 434 const psPolynomial4D *myPoly) 416 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 417 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 418 zSum *= z; 419 } 420 ySum *= y; 421 } 422 xSum *= x; 423 } 424 425 return (polySum); 426 } 427 428 float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly) 435 429 { 436 430 int loop_w = 0; … … 444 438 float zSum = 1.0; 445 439 446 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {440 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 447 441 xSum = wSum; 448 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {442 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 449 443 ySum = xSum; 450 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {444 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 451 445 zSum = ySum; 452 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 453 polySum+= zSum * 454 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 455 zSum*=z; 446 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 447 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 448 zSum *= z; 456 449 } 457 ySum*=y; 458 } 459 xSum*=x; 460 } 461 wSum*=w; 462 } 463 464 return(polySum); 465 } 466 467 468 450 ySum *= y; 451 } 452 xSum *= x; 453 } 454 wSum *= w; 455 } 456 457 return (polySum); 458 } 469 459 470 460 psDPolynomial1D *psDPolynomial1DAlloc(int n) … … 474 464 475 465 newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D)); 476 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial1DFree);466 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree); 477 467 newPoly->n = n; 478 newPoly->coeff = (double *)psAlloc(n * sizeof(double));479 newPoly->coeffErr = (double *) psAlloc(n * sizeof(double));480 newPoly->mask = (char *)psAlloc(n * sizeof(char));481 for (i =0;i<n;i++) {468 newPoly->coeff = (double *)psAlloc(n * sizeof(double)); 469 newPoly->coeffErr = (double *)psAlloc(n * sizeof(double)); 470 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 471 for (i = 0; i < n; i++) { 482 472 newPoly->coeff[i] = 0.0; 483 473 newPoly->coeffErr[i] = 0.0; … … 485 475 } 486 476 487 return (newPoly);477 return (newPoly); 488 478 } 489 479 … … 495 485 496 486 newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D)); 497 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial2DFree);487 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree); 498 488 newPoly->nX = nX; 499 489 newPoly->nY = nY; 500 490 501 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *));502 newPoly->coeffErr = (double **) psAlloc(nX * sizeof(double *));503 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));504 for (x =0;x<nX;x++) {505 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double));506 newPoly->coeffErr[x] = (double *) psAlloc(nY * sizeof(double));507 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));508 } 509 for (x =0;x<nX;x++) {510 for (y =0;y<nY;y++) {491 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *)); 492 newPoly->coeffErr = (double **)psAlloc(nX * sizeof(double *)); 493 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 494 for (x = 0; x < nX; x++) { 495 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double)); 496 newPoly->coeffErr[x] = (double *)psAlloc(nY * sizeof(double)); 497 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 498 } 499 for (x = 0; x < nX; x++) { 500 for (y = 0; y < nY; y++) { 511 501 newPoly->coeff[x][y] = 0.0; 512 502 newPoly->coeffErr[x][y] = 0.0; … … 515 505 } 516 506 517 return (newPoly);507 return (newPoly); 518 508 } 519 509 … … 526 516 527 517 newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D)); 528 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial3DFree);518 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree); 529 519 newPoly->nX = nX; 530 520 newPoly->nY = nY; 531 521 newPoly->nZ = nZ; 532 522 533 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **));534 newPoly->coeffErr = (double ***) psAlloc(nX * sizeof(double **));535 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));536 for (x =0;x<nX;x++) {537 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *));538 newPoly->coeffErr[x] = (double **) psAlloc(nY * sizeof(double *));539 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));540 for (y =0;y<nY;y++) {541 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double));542 newPoly->coeffErr[x][y] = (double *) psAlloc(nZ * sizeof(double));543 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));544 } 545 } 546 for (x =0;x<nX;x++) {547 for (y =0;y<nY;y++) {548 for (z =0;z<nZ;z++) {523 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **)); 524 newPoly->coeffErr = (double ***)psAlloc(nX * sizeof(double **)); 525 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 526 for (x = 0; x < nX; x++) { 527 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *)); 528 newPoly->coeffErr[x] = (double **)psAlloc(nY * sizeof(double *)); 529 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 530 for (y = 0; y < nY; y++) { 531 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double)); 532 newPoly->coeffErr[x][y] = (double *)psAlloc(nZ * sizeof(double)); 533 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 534 } 535 } 536 for (x = 0; x < nX; x++) { 537 for (y = 0; y < nY; y++) { 538 for (z = 0; z < nZ; z++) { 549 539 newPoly->coeff[x][y][z] = 0.0; 550 540 newPoly->coeffErr[x][y][z] = 0.0; … … 554 544 } 555 545 556 return (newPoly);546 return (newPoly); 557 547 } 558 548 … … 566 556 567 557 newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D)); 568 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial4DFree);558 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree); 569 559 newPoly->nW = nW; 570 560 newPoly->nX = nX; … … 572 562 newPoly->nZ = nZ; 573 563 574 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***));575 newPoly->coeffErr = (double ****) psAlloc(nW * sizeof(double ***));576 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));577 for (w =0;w<nW;w++) {578 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **));579 newPoly->coeffErr[w] = (double ***) psAlloc(nX * sizeof(double **));580 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));581 for (x =0;x<nX;x++) {582 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *));583 newPoly->coeffErr[w][x] = (double **) psAlloc(nY * sizeof(double *));584 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));585 for (y =0;y<nY;y++) {586 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double));587 newPoly->coeffErr[w][x][y] = (double *) psAlloc(nZ * sizeof(double));588 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));589 } 590 } 591 } 592 for (w =0;w<nW;w++) {593 for (x =0;x<nX;x++) {594 for (y =0;y<nY;y++) {595 for (z =0;z<nZ;z++) {564 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***)); 565 newPoly->coeffErr = (double ****)psAlloc(nW * sizeof(double ***)); 566 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 567 for (w = 0; w < nW; w++) { 568 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **)); 569 newPoly->coeffErr[w] = (double ***)psAlloc(nX * sizeof(double **)); 570 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 571 for (x = 0; x < nX; x++) { 572 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *)); 573 newPoly->coeffErr[w][x] = (double **)psAlloc(nY * sizeof(double *)); 574 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 575 for (y = 0; y < nY; y++) { 576 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 577 newPoly->coeffErr[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 578 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 579 } 580 } 581 } 582 for (w = 0; w < nW; w++) { 583 for (x = 0; x < nX; x++) { 584 for (y = 0; y < nY; y++) { 585 for (z = 0; z < nZ; z++) { 596 586 newPoly->coeff[w][x][y][z] = 0.0; 597 587 newPoly->coeffErr[w][x][y][z] = 0.0; … … 602 592 } 603 593 604 return (newPoly);605 } 606 607 static void dPolynomial1DFree(psDPolynomial1D * myPoly)594 return (newPoly); 595 } 596 597 static void dPolynomial1DFree(psDPolynomial1D * myPoly) 608 598 { 609 599 psFree(myPoly->coeff); … … 612 602 } 613 603 614 static void dPolynomial2DFree(psDPolynomial2D * myPoly)615 { 616 int x = 0; 617 618 for (x =0;x<myPoly->nX;x++) {604 static void dPolynomial2DFree(psDPolynomial2D * myPoly) 605 { 606 int x = 0; 607 608 for (x = 0; x < myPoly->nX; x++) { 619 609 psFree(myPoly->coeff[x]); 620 610 psFree(myPoly->coeffErr[x]); … … 626 616 } 627 617 628 static void dPolynomial3DFree(psDPolynomial3D * myPoly)629 { 630 int x = 0; 631 int y = 0; 632 633 for (x =0;x<myPoly->nX;x++) {634 for (y =0;y<myPoly->nY;y++) {618 static void dPolynomial3DFree(psDPolynomial3D * myPoly) 619 { 620 int x = 0; 621 int y = 0; 622 623 for (x = 0; x < myPoly->nX; x++) { 624 for (y = 0; y < myPoly->nY; y++) { 635 625 psFree(myPoly->coeff[x][y]); 636 626 psFree(myPoly->coeffErr[x][y]); … … 647 637 } 648 638 649 static void dPolynomial4DFree(psDPolynomial4D * myPoly)639 static void dPolynomial4DFree(psDPolynomial4D * myPoly) 650 640 { 651 641 int w = 0; … … 653 643 int y = 0; 654 644 655 for (w =0;w<myPoly->nW;w++) {656 for (x =0;x<myPoly->nX;x++) {657 for (y =0;y<myPoly->nY;y++) {645 for (w = 0; w < myPoly->nW; w++) { 646 for (x = 0; x < myPoly->nX; x++) { 647 for (y = 0; y < myPoly->nY; y++) { 658 648 psFree(myPoly->coeff[w][x][y]); 659 649 psFree(myPoly->coeffErr[w][x][y]); … … 677 667 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 678 668 *****************************************************************************/ 679 double 680 psDPolynomial1DEval(double x, 681 const psDPolynomial1D *myPoly) 669 double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly) 682 670 { 683 671 int loop_x = 0; … … 687 675 // NOTE: Do we want to flag this case? 688 676 if (myPoly->n == 0) { 689 return(1.0); 690 } 691 692 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 693 polySum+= xSum * myPoly->coeff[loop_x]; 694 xSum*=x; 695 } 696 697 return(polySum); 698 } 699 700 701 double 702 psDPolynomial2DEval(double x, 703 double y, 704 const psDPolynomial2D *myPoly) 677 return (1.0); 678 } 679 680 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 681 polySum += xSum * myPoly->coeff[loop_x]; 682 xSum *= x; 683 } 684 685 return (polySum); 686 } 687 688 double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly) 705 689 { 706 690 int loop_x = 0; … … 710 694 double ySum = 1.0; 711 695 712 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {696 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 713 697 ySum = xSum; 714 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 715 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 716 ySum*=y; 717 } 718 xSum*=x; 719 } 720 721 return(polySum); 722 } 723 724 double 725 psDPolynomial3DEval(double x, 726 double y, 727 double z, 728 const psDPolynomial3D *myPoly) 698 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 699 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 700 ySum *= y; 701 } 702 xSum *= x; 703 } 704 705 return (polySum); 706 } 707 708 double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly) 729 709 { 730 710 int loop_x = 0; … … 736 716 double zSum = 1.0; 737 717 738 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {718 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 739 719 ySum = xSum; 740 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {720 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 741 721 zSum = ySum; 742 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 743 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 744 zSum*=z; 745 } 746 ySum*=y; 747 } 748 xSum*=x; 749 } 750 751 return(polySum); 752 } 753 754 double 755 psDPolynomial4DEval(double w, 756 double x, 757 double y, 758 double z, 759 const psDPolynomial4D *myPoly) 722 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 723 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 724 zSum *= z; 725 } 726 ySum *= y; 727 } 728 xSum *= x; 729 } 730 731 return (polySum); 732 } 733 734 double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly) 760 735 { 761 736 int loop_w = 0; … … 769 744 double zSum = 1.0; 770 745 771 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {746 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 772 747 xSum = wSum; 773 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {748 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 774 749 ySum = xSum; 775 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {750 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 776 751 zSum = ySum; 777 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 778 polySum+= zSum * 779 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 780 zSum*=z; 752 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 753 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 754 zSum *= z; 781 755 } 782 ySum *=y;783 } 784 xSum *=x;785 } 786 wSum *=w;787 } 788 789 return (polySum);790 } 756 ySum *= y; 757 } 758 xSum *= x; 759 } 760 wSum *= w; 761 } 762 763 return (polySum); 764 } -
trunk/psLib/src/dataManip/psFunctions.h
r1406 r1407 1 1 2 /** @file psFunctions.h 2 3 * \brief Standard Mathematical Functions. … … 12 13 * @author George Gusciora, MHPCC 13 14 * 14 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #if !defined(PS_FUNCTIONS_H) 21 # define PS_FUNCTIONS_H22 23 # include <stdbool.h>24 25 # include "psVector.h"22 # define PS_FUNCTIONS_H 23 24 # include <stdbool.h> 25 26 # include "psVector.h" 26 27 27 28 /** \addtogroup Stats … … 33 34 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */ 34 35 35 float 36 psGaussian( float x, ///< Value at which to evaluate 37 float mean, ///< Mean for the Gaussian 38 float stddev, ///< Standard deviation for the Gaussian 39 bool normal ///< Indicates whether result should be normalized 40 ); 41 36 float psGaussian(float x, // /< Value at which to evaluate 37 float mean, // /< Mean for the Gaussian 38 float stddev, // /< Standard deviation for the Gaussian 39 bool normal // /< Indicates whether result should be normalized 40 ); 42 41 43 42 /** Produce a vector of random numbers from a Gaussian distribution with 44 43 the specified mean and sigma */ 45 psVector *psGaussianDev( float mean, ///< The mean of the Gaussian 46 float sigma, ///< The sigma of the Gaussian 47 int Npts ); ///< The size of the vector 48 49 50 51 44 psVector *psGaussianDev(float mean, // /< The mean of the Gaussian 45 float sigma, // /< The sigma of the Gaussian 46 int Npts); // /< The size of the vector 52 47 53 48 /** One-dimensional polynomial */ 54 49 typedef struct 55 50 { 56 int n; ///< Number of terms57 float *coeff; ///< Coefficients58 float *coeffErr; ///< Error in coefficients59 char *mask; ///< Coefficient mask51 int n; // /< Number of terms 52 float *coeff; // /< Coefficients 53 float *coeffErr; // /< Error in coefficients 54 char *mask; // /< Coefficient mask 60 55 } 61 56 psPolynomial1D; … … 64 59 typedef struct 65 60 { 66 int nX, nY; ///< Number of terms in x and y 67 float **coeff; ///< Coefficients 68 float **coeffErr; ///< Error in coefficients 69 char **mask; ///< Coefficients mask 61 int nX, 62 nY; // /< Number of terms in x and y 63 float **coeff; // /< Coefficients 64 float **coeffErr; // /< Error in coefficients 65 char **mask; // /< Coefficients mask 70 66 } 71 67 psPolynomial2D; … … 74 70 typedef struct 75 71 { 76 int nX, nY, nZ; ///< Number of terms in x, y and z 77 float ***coeff; ///< Coefficients 78 float ***coeffErr; ///< Error in coefficients 79 char ***mask; ///< Coefficients mask 72 int nX, 73 nY, 74 nZ; // /< Number of terms in x, y and z 75 float ***coeff; // /< Coefficients 76 float ***coeffErr; // /< Error in coefficients 77 char ***mask; // /< Coefficients mask 80 78 } 81 79 psPolynomial3D; … … 84 82 typedef struct 85 83 { 86 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 87 float ****coeff; ///< Coefficients 88 float ****coeffErr; ///< Error in coefficients 89 char ****mask; ///< Coefficients mask 84 int nW, 85 nX, 86 nY, 87 nZ; // /< Number of terms in w, x, y and z 88 float ****coeff; // /< Coefficients 89 float ****coeffErr; // /< Error in coefficients 90 char ****mask; // /< Coefficients mask 90 91 } 91 92 psPolynomial4D; 92 93 93 94 94 /** Functions **************************************************************/ 95 95 96 96 /** Constructor */ 97 psPolynomial1D *psPolynomial1DAlloc( int n ///< Number of terms 98 ); 99 /** Constructor */ 100 psPolynomial2D *psPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 101 ); 102 /** Constructor */ 103 psPolynomial3D *psPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 104 ); 105 /** Constructor */ 106 psPolynomial4D *psPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 97 psPolynomial1D *psPolynomial1DAlloc(int n // /< Number of terms 98 ); 99 100 /** Constructor */ 101 psPolynomial2D *psPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 102 ); 103 104 /** Constructor */ 105 psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 106 ); 107 108 /** Constructor */ 109 psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 110 // z 107 111 ); 108 112 109 113 /** Evaluate 1D polynomial */ 110 float 111 psPolynomial1DEval( float x, ///< Value at which to evaluate 112 const psPolynomial1D *myPoly ///< Coefficients for the polynomial 113 ); 114 float psPolynomial1DEval(float x, // /< Value at which to evaluate 115 const psPolynomial1D * myPoly // /< Coefficients for the polynomial 116 ); 114 117 115 118 /** Evaluate 2D polynomial */ 116 float 117 psPolynomial2DEval( float x, ///< Value x at which to evaluate 118 float y, ///< Value y at which to evaluate 119 const psPolynomial2D *myPoly ///< Coefficients for the polynomial 120 ); 119 float psPolynomial2DEval(float x, // /< Value x at which to evaluate 120 float y, // /< Value y at which to evaluate 121 const psPolynomial2D * myPoly // /< Coefficients for the polynomial 122 ); 121 123 122 124 /** Evaluate 3D polynomial */ 123 float 124 psPolynomial3DEval( float x, ///< Value x at which to evaluate 125 float y, ///< Value y at which to evaluate 126 float z, ///< Value z at which to evaluate 127 const psPolynomial3D *myPoly ///< Coefficients for the polynomial 128 ); 125 float psPolynomial3DEval(float x, // /< Value x at which to evaluate 126 float y, // /< Value y at which to evaluate 127 float z, // /< Value z at which to evaluate 128 const psPolynomial3D * myPoly // /< Coefficients for the polynomial 129 ); 129 130 130 131 /** Evaluate 4D polynomial */ 131 float 132 psPolynomial4DEval( float w, ///< Value w at which to evaluate 133 float x, ///< Value x at which to evaluate 134 float y, ///< Value y at which to evaluate 135 float z, ///< Value z at which to evaluate 136 const psPolynomial4D *myPoly ///< Coefficients for the polynomial 137 ); 132 float psPolynomial4DEval(float w, // /< Value w at which to evaluate 133 float x, // /< Value x at which to evaluate 134 float y, // /< Value y at which to evaluate 135 float z, // /< Value z at which to evaluate 136 const psPolynomial4D * myPoly // /< Coefficients for the polynomial 137 ); 138 138 139 139 /*****************************************************************************/ … … 144 144 typedef struct 145 145 { 146 int n; ///< Number of terms147 double *coeff; ///< Coefficients148 double *coeffErr; ///< Error in coefficients149 char *mask; ///< Coefficient mask146 int n; // /< Number of terms 147 double *coeff; // /< Coefficients 148 double *coeffErr; // /< Error in coefficients 149 char *mask; // /< Coefficient mask 150 150 } 151 151 psDPolynomial1D; … … 154 154 typedef struct 155 155 { 156 int nX, nY; ///< Number of terms in x and y 157 double **coeff; ///< Coefficients 158 double **coeffErr; ///< Error in coefficients 159 char **mask; ///< Coefficients mask 156 int nX, 157 nY; // /< Number of terms in x and y 158 double **coeff; // /< Coefficients 159 double **coeffErr; // /< Error in coefficients 160 char **mask; // /< Coefficients mask 160 161 } 161 162 psDPolynomial2D; … … 164 165 typedef struct 165 166 { 166 int nX, nY, nZ; ///< Number of terms in x, y and z 167 double ***coeff; ///< Coefficients 168 double ***coeffErr; ///< Error in coefficients 169 char ***mask; ///< Coefficient mask 167 int nX, 168 nY, 169 nZ; // /< Number of terms in x, y and z 170 double ***coeff; // /< Coefficients 171 double ***coeffErr; // /< Error in coefficients 172 char ***mask; // /< Coefficient mask 170 173 } 171 174 psDPolynomial3D; … … 174 177 typedef struct 175 178 { 176 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 177 double ****coeff; ///< Coefficients 178 double ****coeffErr; ///< Error in coefficients 179 char ****mask; ///< Coefficients mask 179 int nW, 180 nX, 181 nY, 182 nZ; // /< Number of terms in w, x, y and z 183 double ****coeff; // /< Coefficients 184 double ****coeffErr; // /< Error in coefficients 185 char ****mask; // /< Coefficients mask 180 186 } 181 187 psDPolynomial4D; 182 188 183 189 /** Constructor */ 184 psDPolynomial1D *psDPolynomial1DAlloc( int n ///< Number of terms 185 ); 186 /** Constructor */ 187 psDPolynomial2D *psDPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 188 ); 189 /** Constructor */ 190 psDPolynomial3D *psDPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 191 ); 192 /** Constructor */ 193 psDPolynomial4D *psDPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 190 psDPolynomial1D *psDPolynomial1DAlloc(int n // /< Number of terms 191 ); 192 193 /** Constructor */ 194 psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 195 ); 196 197 /** Constructor */ 198 psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 199 ); 200 201 /** Constructor */ 202 psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 203 // z 194 204 ); 195 205 196 206 /** Evaluate 1D polynomial (double precision) */ 197 double 198 psDPolynomial1DEval( double x, ///< Value at which to evaluate 199 const psDPolynomial1D *myPoly ///< Coefficients for the polynomial 200 ); 207 double psDPolynomial1DEval(double x, // /< Value at which to evaluate 208 const psDPolynomial1D * myPoly // /< Coefficients for the polynomial 209 ); 201 210 202 211 /** Evaluate 2D polynomial (double precision) */ 203 double 204 psDPolynomial2DEval( double x, ///< Value x at which to evaluate 205 double y, ///< Value y at which to evaluate 206 const psDPolynomial2D *myPoly ///< Coefficients for the polynomial 207 ); 212 double psDPolynomial2DEval(double x, // /< Value x at which to evaluate 213 double y, // /< Value y at which to evaluate 214 const psDPolynomial2D * myPoly // /< Coefficients for the polynomial 215 ); 208 216 209 217 /** Evaluate 3D polynomial (double precision) */ 210 double 211 psDPolynomial3DEval( double x, ///< Value x at which to evaluate 212 double y, ///< Value y at which to evaluate 213 double z, ///< Value z at which to evaluate 214 const psDPolynomial3D *myPoly ///< Coefficients for the polynomial 215 ); 218 double psDPolynomial3DEval(double x, // /< Value x at which to evaluate 219 double y, // /< Value y at which to evaluate 220 double z, // /< Value z at which to evaluate 221 const psDPolynomial3D * myPoly // /< Coefficients for the polynomial 222 ); 216 223 217 224 /** Evaluate 4D polynomial (double precision) */ 218 double 219 psDPolynomial4DEval( double w, ///< Value w at which to evaluate 220 double x, ///< Value x at which to evaluate 221 double y, ///< Value y at which to evaluate 222 double z, ///< Value z at which to evaluate 223 const psDPolynomial4D *myPoly ///< Coefficients for the polynomial 224 ); 225 226 /* \} */ // End of MathGroup Functions 225 double psDPolynomial4DEval(double w, // /< Value w at which to evaluate 226 double x, // /< Value x at which to evaluate 227 double y, // /< Value y at which to evaluate 228 double z, // /< Value z at which to evaluate 229 const psDPolynomial4D * myPoly // /< Coefficients for the polynomial 230 ); 231 232 /* \} */// End of MathGroup Functions 227 233 228 234 #endif -
trunk/psLib/src/dataManip/psMatrix.c
r1406 r1407 1 1 2 /** @file psMatrix.c 2 3 * … … 20 21 * @author Ross Harman, MHPCC 21 22 * 22 * @version $Revision: 1.1 0$ $Name: not supported by cvs2svn $23 * @date $Date: 2004-08-0 6 22:34:05$23 * @version $Revision: 1.11 $ $Name: not supported by cvs2svn $ 24 * @date $Date: 2004-08-07 00:06:06 $ 24 25 * 25 26 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 28 29 /******************************************************************************/ 30 29 31 /* INCLUDE FILES */ 32 30 33 /******************************************************************************/ 31 34 #include <string.h> … … 42 45 43 46 /******************************************************************************/ 47 44 48 /* DEFINE STATEMENTS */ 49 45 50 /******************************************************************************/ 46 51 … … 48 53 49 54 /******************************************************************************/ 55 50 56 /* TYPE DEFINITIONS */ 57 51 58 /******************************************************************************/ 52 59 … … 54 61 55 62 /*****************************************************************************/ 63 56 64 /* GLOBAL VARIABLES */ 65 57 66 /*****************************************************************************/ 58 67 … … 60 69 61 70 /*****************************************************************************/ 71 62 72 /* FILE STATIC VARIABLES */ 73 63 74 /*****************************************************************************/ 64 75 … … 66 77 67 78 /*****************************************************************************/ 79 68 80 /* FUNCTION IMPLEMENTATION - LOCAL */ 81 69 82 /*****************************************************************************/ 70 83 … … 142 155 143 156 /*****************************************************************************/ 157 144 158 /* FUNCTION IMPLEMENTATION - PUBLIC */ 145 /*****************************************************************************/ 146 147 psImage *psMatrixLUD(psImage *outImage, psVector *outPerm, psImage *inImage) 159 160 /*****************************************************************************/ 161 162 psImage *psMatrixLUD(psImage * outImage, psVector * outPerm, psImage * inImage) 148 163 { 149 164 int signum = 0; … … 169 184 numRows = inImage->numRows; 170 185 numCols = inImage->numCols; 171 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;186 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 172 187 173 188 // Initialize GSL data … … 190 205 } 191 206 192 psVector *psMatrixLUSolve(psVector * outVector, const psImage *inImage, const psVector *inVector, const193 psVector * inPerm)207 psVector *psMatrixLUSolve(psVector * outVector, const psImage * inImage, const psVector * inVector, const 208 psVector * inPerm) 194 209 { 195 210 int arraySize = 0; … … 219 234 numRows = inImage->numRows; 220 235 numCols = inImage->numCols; 221 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;236 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 222 237 223 238 // Initialize GSL data … … 243 258 } 244 259 245 psImage *psMatrixInvert(psImage * outImage, const psImage *inImage, float *restrict det)260 psImage *psMatrixInvert(psImage * outImage, const psImage * inImage, float *restrict det) 246 261 { 247 262 int signum = 0; … … 254 269 255 270 // Error checks 256 if (det == NULL) {271 if (det == NULL) { 257 272 psError(__func__, "Invalid operation: determinant argument is NULL."); 258 273 return outImage; … … 269 284 numRows = inImage->numRows; 270 285 numCols = inImage->numCols; 271 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;286 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 272 287 273 288 // Allocate GSL structs … … 297 312 } 298 313 299 float * psMatrixDeterminant(const psImage *restrict inImage)314 float *psMatrixDeterminant(const psImage * restrict inImage) 300 315 { 301 316 int signum = 0; … … 315 330 numRows = inImage->numRows; 316 331 numCols = inImage->numCols; 317 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;332 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 318 333 319 334 // Allocate GSL structs … … 328 343 329 344 // Calculate determinant 330 det = (float *)psAlloc(sizeof(float));345 det = (float *)psAlloc(sizeof(float)); 331 346 gsl_linalg_LU_decomp(lu, perm, &signum); 332 347 *det = (float)gsl_linalg_LU_det(lu, signum); … … 339 354 } 340 355 341 psImage * psMatrixMultiply(psImage *outImage, psImage *inImage1, psImage *inImage2)356 psImage *psMatrixMultiply(psImage * outImage, psImage * inImage1, psImage * inImage2) 342 357 { 343 358 int arraySize = 0; … … 364 379 numRows = inImage1->numRows; 365 380 numCols = inImage1->numCols; 366 arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) *numRows*numCols;381 arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) * numRows * numCols; 367 382 368 383 // Initialize GSL data … … 381 396 } 382 397 383 psImage * psMatrixTranspose(psImage *outImage, const psImage *inImage)398 psImage *psMatrixTranspose(psImage * outImage, const psImage * inImage) 384 399 { 385 400 int arraySize = 0; … … 400 415 numRows = inImage->numRows; 401 416 numCols = inImage->numCols; 402 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;417 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 403 418 404 419 // Initialize GSL data … … 418 433 } 419 434 420 psImage *psMatrixEigenvectors(psImage * outImage, psImage *inImage)435 psImage *psMatrixEigenvectors(psImage * outImage, psImage * inImage) 421 436 { 422 437 int numRows = 0; … … 462 477 } 463 478 464 psVector *psMatrixToVector(psVector * outVector, psImage *inImage)479 psVector *psMatrixToVector(psVector * outVector, psImage * inImage) 465 480 { 466 481 int size = 0; … … 471 486 PS_CHECK_SIZE_IMAGE(inImage, outVector); 472 487 473 if (inImage->numRows == 1) {488 if (inImage->numRows == 1) { 474 489 // Create transposed row vector 475 490 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numCols, inImage->type.type); 476 491 outVector->type.dimen = PS_DIMEN_TRANSV; 477 } else 478 if(inImage->numCols == 1) { 479 // Create non-transposed column vector 480 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numRows, inImage->type.type); 481 } else { 482 psError(__func__, "Image does not have dim with 1 col or 1 row: (%d x %d).", inImage->numRows, 483 inImage->numCols); 484 return outVector; 485 } 492 } else if (inImage->numCols == 1) { 493 // Create non-transposed column vector 494 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numRows, inImage->type.type); 495 } else { 496 psError(__func__, "Image does not have dim with 1 col or 1 row: (%d x %d).", inImage->numRows, 497 inImage->numCols); 498 return outVector; 499 } 486 500 487 501 PS_CHECK_NULL_VECTOR(outVector, outVector); 488 502 489 490 503 // More checks 491 if (outVector->type.dimen == PS_DIMEN_VECTOR) {504 if (outVector->type.dimen == PS_DIMEN_VECTOR) { 492 505 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector); 493 506 494 if (outVector->n == 0) {507 if (outVector->n == 0) { 495 508 outVector->n = inImage->numRows; 496 509 } 497 510 498 if (outVector->n != inImage->numRows) {511 if (outVector->n != inImage->numRows) { 499 512 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numRows, outVector->n); 500 513 return outVector; 501 514 } 502 515 503 size = PSELEMTYPE_SIZEOF(inImage->type.type)*inImage->numRows; 504 505 } else 506 if(outVector->type.dimen == PS_DIMEN_TRANSV) { 507 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_TRANSV, outVector); 508 509 if(outVector->n == 0) { 510 outVector->n = inImage->numCols; 511 } 512 513 if(outVector->n != inImage->numCols) { 514 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numCols, outVector->n); 515 return outVector; 516 } 517 518 size = PSELEMTYPE_SIZEOF(inImage->type.type)*inImage->numCols; 516 size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numRows; 517 518 } else if (outVector->type.dimen == PS_DIMEN_TRANSV) { 519 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_TRANSV, outVector); 520 521 if (outVector->n == 0) { 522 outVector->n = inImage->numCols; 519 523 } 520 524 525 if (outVector->n != inImage->numCols) { 526 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numCols, outVector->n); 527 return outVector; 528 } 529 530 size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numCols; 531 } 532 521 533 memcpy(outVector->data.V, inImage->data.V[0], size); 522 534 … … 524 536 } 525 537 526 psImage *psVectorToMatrix(psImage * outImage, psVector *inVector)538 psImage *psVectorToMatrix(psImage * outImage, psVector * inVector) 527 539 { 528 540 int size = 0; … … 531 543 PS_CHECK_NULL_VECTOR(inVector, outImage); 532 544 533 if (inVector->type.dimen == PS_DIMEN_VECTOR) {545 if (inVector->type.dimen == PS_DIMEN_VECTOR) { 534 546 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outImage); 535 547 PS_CHECK_SIZE_VECTOR(inVector, outImage); 536 548 PS_CHECK_ALLOC_IMAGE(outImage, 1, inVector->n, PS_TYPE_F64) 537 538 549 // More checks for PS_DIMEN_VECTOR 539 if (outImage->numCols > 1) {550 if (outImage->numCols > 1) { 540 551 psError(__func__, "Image has more than 1 column: numCols = %d.", outImage->numCols); 541 552 return outImage; 542 } else 543 if(outImage->numRows != inVector->n) { 544 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numRows, inVector->n); 545 return outImage; 546 } 547 548 size = PSELEMTYPE_SIZEOF(outImage->type.type)*outImage->numRows; 549 550 } else 551 if(inVector->type.dimen == PS_DIMEN_TRANSV) { 552 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_TRANSV, outImage); 553 PS_CHECK_SIZE_VECTOR(inVector, outImage); 554 PS_CHECK_ALLOC_IMAGE(outImage, inVector->n, 1, PS_TYPE_F64) 555 556 // More checks for PS_DIMEN_TRANSV 557 if(outImage->numRows > 1) { 558 psError(__func__, "Image has more than 1 row: numRows = %d.", outImage->numRows); 559 return outImage; 560 } else 561 if(outImage->numCols != inVector->n) { 562 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numCols, inVector->n); 563 return outImage; 564 } 565 566 size = PSELEMTYPE_SIZEOF(outImage->type.type)*outImage->numCols; 553 } else if (outImage->numRows != inVector->n) { 554 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numRows, inVector->n); 555 return outImage; 567 556 } 557 558 size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numRows; 559 560 } else if (inVector->type.dimen == PS_DIMEN_TRANSV) { 561 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_TRANSV, outImage); 562 PS_CHECK_SIZE_VECTOR(inVector, outImage); 563 PS_CHECK_ALLOC_IMAGE(outImage, inVector->n, 1, PS_TYPE_F64) 564 // More checks for PS_DIMEN_TRANSV 565 if (outImage->numRows > 1) { 566 psError(__func__, "Image has more than 1 row: numRows = %d.", outImage->numRows); 567 return outImage; 568 } else if (outImage->numCols != inVector->n) { 569 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numCols, inVector->n); 570 return outImage; 571 } 572 573 size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numCols; 574 } 568 575 569 576 PS_CHECK_NULL_IMAGE(outImage, outImage); … … 574 581 return outImage; 575 582 } 576 -
trunk/psLib/src/dataManip/psMatrix.h
r974 r1407 1 1 2 /** @file psMatrix.h 2 3 * … … 21 22 * @author Ross Harman, MHPCC 22 23 * 23 * @version $Revision: 1. 6$ $Name: not supported by cvs2svn $24 * @date $Date: 2004-0 6-10 01:58:06 $24 * @version $Revision: 1.7 $ $Name: not supported by cvs2svn $ 25 * @date $Date: 2004-08-07 00:06:06 $ 25 26 * 26 27 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 28 29 29 30 #ifndef PSMATRIX_H 30 # define PSMATRIX_H31 # define PSMATRIX_H 31 32 32 33 /// @addtogroup Matrix … … 42 43 * @return psImage*: Pointer to LU decomposed psImage. 43 44 */ 44 psImage *psMatrixLUD( 45 psImage *outImage, ///< Image to return, or NULL. 46 psVector *outPerm, ///< Output permutation vector used by psMatrixLUSolve. 47 psImage *inImage ///< Image to decompose. 48 ); 45 psImage *psMatrixLUD(psImage * outImage, // /< Image to return, or NULL. 46 psVector * outPerm, // /< Output permutation vector used by psMatrixLUSolve. 47 psImage * inImage // /< Image to decompose. 48 ); 49 49 50 50 /** LU Solution of psImage matrix. … … 57 57 * @return psVector*: Pointer to psVector solution of matrix equation. 58 58 */ 59 psVector *psMatrixLUSolve( 60 psVector *outVector, ///< Vector to return, or NULL.61 const psImage *luImage, ///< LU-decomposed matrix.62 const psVector *inVector, ///< Vector right-hand-side of equation.63 const psVector *inPerm ///< Permutation vector resulting from psMatrixLUDfunction.64 );59 psVector *psMatrixLUSolve(psVector * outVector, // /< Vector to return, or NULL. 60 const psImage * luImage, // /< LU-decomposed matrix. 61 const psVector * inVector, // /< Vector right-hand-side of equation. 62 const psVector * inPerm // /< Permutation vector resulting from psMatrixLUD 63 // function. 64 ); 65 65 66 66 /** Invert psImage matrix. … … 73 73 * @return psImage*: Pointer to inverted psImage. 74 74 */ 75 psImage *psMatrixInvert( 76 psImage *outImage, ///< Image to return, or NULL for in-place substitution. 77 const psImage *inImage, ///< Image to be inverted 78 float *restrict det ///< Determinant to return, or NULL 79 ); 75 psImage *psMatrixInvert(psImage * outImage, // /< Image to return, or NULL for in-place substitution. 76 const psImage * inImage, // /< Image to be inverted 77 float *restrict det // /< Determinant to return, or NULL 78 ); 80 79 81 80 /** Calculate psImage matrix determinant. … … 87 86 * @return float: Determinant from psImage. 88 87 */ 89 float* psMatrixDeterminant( 90 const psImage *restrict inMatrix ///< Image used to calculate determinant. 91 ); 88 float *psMatrixDeterminant(const psImage * restrict inMatrix // /< Image used to calculate determinant. 89 ); 92 90 93 91 /** Performs psImage matrix multiplication. … … 100 98 * @return psImage*: Pointer to resulting psImage. 101 99 */ 102 psImage *psMatrixMultiply( 103 psImage *outImage, ///< Matrix to return, or NULL. 104 psImage *inImage1, ///< First input image. 105 psImage *inImage2 ///< Second input image. 106 ); 100 psImage *psMatrixMultiply(psImage * outImage, // /< Matrix to return, or NULL. 101 psImage * inImage1, // /< First input image. 102 psImage * inImage2 // /< Second input image. 103 ); 107 104 108 105 /** Transpose matrix. … … 115 112 * @return psImage*: Pointer to transposed psImage. 116 113 */ 117 psImage *psMatrixTranspose( 118 psImage *outImage, ///< Image to return, or NULL 119 const psImage *inImage ///< Image to transpose 120 ); 114 psImage *psMatrixTranspose(psImage * outImage, // /< Image to return, or NULL 115 const psImage * inImage // /< Image to transpose 116 ); 121 117 122 118 /** Calculate matrix eigenvectors. … … 128 124 * @return psImage*: Pointer to matrix of Eigenvectors. 129 125 */ 130 psImage *psMatrixEigenvectors( 131 psImage *outImage, ///< Eigenvectors to return, or NULL. 132 psImage *inImage ///< Input image. 133 ); 126 psImage *psMatrixEigenvectors(psImage * outImage, // /< Eigenvectors to return, or NULL. 127 psImage * inImage // /< Input image. 128 ); 134 129 135 130 /** Convert matrix to vector. … … 142 137 * @return psVector*: Pointer to psVector. 143 138 */ 144 psVector *psMatrixToVector( 145 psVector *outVector, ///< Vector to return, or NULL. 146 psImage *inImage ///< Image to convert. 147 ); 139 psVector *psMatrixToVector(psVector * outVector, // /< Vector to return, or NULL. 140 psImage * inImage // /< Image to convert. 141 ); 148 142 149 143 /** Convert vector to matrix. … … 156 150 * @return psVector*: Pointer to psIamge. 157 151 */ 158 psImage *psVectorToMatrix( 159 psImage *outImage, ///< Matrix to return, or NULL. 160 psVector *inVector ///< Vector to convert. 161 ); 152 psImage *psVectorToMatrix(psImage * outImage, // /< Matrix to return, or NULL. 153 psVector * inVector // /< Vector to convert. 154 ); 162 155 163 156 /// @} -
trunk/psLib/src/dataManip/psMatrixVectorArithmetic.c
r1406 r1407 1 1 2 /** @file psMatrixVectorArithmetic.c 2 3 * … … 29 30 * @author Ross Harman, MHPCC 30 31 * 31 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $32 * @date $Date: 2004-08-0 6 22:34:05$32 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 33 * @date $Date: 2004-08-07 00:06:06 $ 33 34 * 34 35 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 36 37 37 38 /******************************************************************************/ 39 38 40 /* INCLUDE FILES */ 41 39 42 /******************************************************************************/ 40 43 #include <string.h> … … 49 52 50 53 /******************************************************************************/ 54 51 55 /* DEFINE STATEMENTS */ 56 52 57 /******************************************************************************/ 53 58 … … 55 60 56 61 /******************************************************************************/ 62 57 63 /* TYPE DEFINITIONS */ 64 58 65 /******************************************************************************/ 59 66 … … 61 68 62 69 /*****************************************************************************/ 70 63 71 /* GLOBAL VARIABLES */ 72 64 73 /*****************************************************************************/ 65 74 … … 67 76 68 77 /*****************************************************************************/ 78 69 79 /* FILE STATIC VARIABLES */ 80 70 81 /*****************************************************************************/ 71 82 … … 73 84 74 85 /*****************************************************************************/ 86 75 87 /* FUNCTION IMPLEMENTATION - LOCAL */ 88 76 89 /*****************************************************************************/ 77 90 … … 85 98 static complex double psNanDiv(complex double a, complex double b) 86 99 { 87 complex double out = 0+0i; 88 out = a/b; 89 if(isnan(creal(out)) || isnan(cimag(out))) { 100 complex double out = 0 + 0i; 101 102 out = a / b; 103 if (isnan(creal(out)) || isnan(cimag(out))) { 90 104 psError(__func__, ": Divide by zero"); 91 105 } … … 399 413 psType *psTypeOut = NULL; 400 414 401 psTypeOut = (psType *)out;402 if (psTypeOut == NULL) {415 psTypeOut = (psType *) out; 416 if (psTypeOut == NULL) { 403 417 psError(__func__, ": Line %d - Null out argument", __LINE__); 404 418 return out; 405 419 } 406 420 407 psType1 = (psType *)in1;408 if (psType1 == NULL) {421 psType1 = (psType *) in1; 422 if (psType1 == NULL) { 409 423 psError(__func__, ": Line %d - Null in1 argument", __LINE__); 410 424 return out; 411 425 } 412 426 413 psType2 = (psType *)in2;414 if (psType2 == NULL) {427 psType2 = (psType *) in2; 428 if (psType2 == NULL) { 415 429 psError(__func__, ": Line %d - Null in2 argument", __LINE__); 416 430 return out; 417 431 } 418 432 419 if (op == NULL) {433 if (op == NULL) { 420 434 psError(__func__, ": Line %d - Null op argument", __LINE__); 421 435 return out; … … 429 443 elTypeOut = psTypeOut->type; 430 444 431 if (elType1!=elType2 && elType1!=elTypeOut) {445 if (elType1 != elType2 && elType1 != elTypeOut) { 432 446 psError(__func__, ": Line %d - Element types for arguments inconsistent: (%d, %d, %d)", __LINE__, 433 447 elType1, elType2, elTypeOut); … … 435 449 } 436 450 437 if (dim1==PS_DIMEN_OTHER || dim2==PS_DIMEN_OTHER || dimOut==PS_DIMEN_OTHER) {451 if (dim1 == PS_DIMEN_OTHER || dim2 == PS_DIMEN_OTHER || dimOut == PS_DIMEN_OTHER) { 438 452 psError(__func__, ": Line %d - PS_DIMEN_OTHER not allowed for arguments: (%d, %d, %d)", __LINE__, 439 453 dim1, dim2, dimOut); … … 441 455 } 442 456 443 if (dim1 == PS_DIMEN_VECTOR) {444 if (((psVector*)in1)->n == 0) {457 if (dim1 == PS_DIMEN_VECTOR) { 458 if (((psVector *) in1)->n == 0) { 445 459 psError(__func__, ": Line %d - Vector contains zero elements"); 446 460 } 447 } else 448 if(dim1 == PS_DIMEN_IMAGE) { 449 if(((psImage*)in1)->numCols==0 || ((psImage*)in1)->numRows==0) { 450 psError(__func__, ": Line %d - Image contains zero length row or cols"); 451 } 452 } 453 454 if(dim2 == PS_DIMEN_VECTOR) { 455 if(((psVector*)in2)->n == 0) { 461 } else if (dim1 == PS_DIMEN_IMAGE) { 462 if (((psImage *) in1)->numCols == 0 || ((psImage *) in1)->numRows == 0) { 463 psError(__func__, ": Line %d - Image contains zero length row or cols"); 464 } 465 } 466 467 if (dim2 == PS_DIMEN_VECTOR) { 468 if (((psVector *) in2)->n == 0) { 456 469 psError(__func__, ": Line %d - Vector contains zero elements"); 457 470 } 458 } else 459 if(dim2 == PS_DIMEN_IMAGE) { 460 if(((psImage*)in2)->numCols==0 || ((psImage*)in2)->numRows==0) { 461 psError(__func__, ": Line %d - Image contains zero length row or cols"); 462 } 463 } 464 465 if(dim1 == PS_DIMEN_SCALAR) { 466 if(dim2 == PS_DIMEN_SCALAR) { 467 BINARY_OP(SCALAR,SCALAR,out,psType1,op,psType2); // scalar op scalar 468 } else 469 if(dim2==PS_DIMEN_VECTOR || dim2==PS_DIMEN_TRANSV) { 470 BINARY_OP(SCALAR,VECTOR,out,psType1,op,psType2); // scalar op vector 471 } else 472 if(dim2 == PS_DIMEN_IMAGE) { 473 BINARY_OP(SCALAR,IMAGE,out,psType1,op,psType2); // scalar op image 474 } else { 475 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 476 } 477 } else 478 if(dim1==PS_DIMEN_VECTOR || dim1==PS_DIMEN_TRANSV) { 479 if(dim2 == PS_DIMEN_SCALAR) { 480 BINARY_OP(VECTOR,SCALAR,out,psType1,op,psType2); // vector op scalar 481 } else 482 if(dim2==PS_DIMEN_VECTOR || dim2==PS_DIMEN_TRANSV) { 483 BINARY_OP(VECTOR,VECTOR,out,psType1,op,psType2); // vector op vector 484 } else 485 if(dim2 == PS_DIMEN_IMAGE) { 486 BINARY_OP(VECTOR,IMAGE,out,psType1,op,psType2); // vector op image 487 } else { 488 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 489 } 490 } else 491 if(dim1 == PS_DIMEN_IMAGE) { 492 if(dim2 == PS_DIMEN_SCALAR) { 493 BINARY_OP(IMAGE,SCALAR,out,psType1,op,psType2); // image op scalar 494 } else 495 if(dim2==PS_DIMEN_VECTOR || dim2==PS_DIMEN_TRANSV) { 496 BINARY_OP(IMAGE,VECTOR,out,psType1,op,psType2); // image op vector 497 } else 498 if(dim2 == PS_DIMEN_IMAGE) { 499 BINARY_OP(IMAGE,IMAGE,out,psType1,op,psType2); // image op image 500 } else { 501 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 502 } 503 } else { 504 psError(__func__, ": Line %d - Invalid dimensionality for in1 arg: %d", __LINE__, dim1); 505 } 471 } else if (dim2 == PS_DIMEN_IMAGE) { 472 if (((psImage *) in2)->numCols == 0 || ((psImage *) in2)->numRows == 0) { 473 psError(__func__, ": Line %d - Image contains zero length row or cols"); 474 } 475 } 476 477 if (dim1 == PS_DIMEN_SCALAR) { 478 if (dim2 == PS_DIMEN_SCALAR) { 479 BINARY_OP(SCALAR, SCALAR, out, psType1, op, psType2); // scalar op scalar 480 } else if (dim2 == PS_DIMEN_VECTOR || dim2 == PS_DIMEN_TRANSV) { 481 BINARY_OP(SCALAR, VECTOR, out, psType1, op, psType2); // scalar op vector 482 } else if (dim2 == PS_DIMEN_IMAGE) { 483 BINARY_OP(SCALAR, IMAGE, out, psType1, op, psType2); // scalar op image 484 } else { 485 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 486 } 487 } else if (dim1 == PS_DIMEN_VECTOR || dim1 == PS_DIMEN_TRANSV) { 488 if (dim2 == PS_DIMEN_SCALAR) { 489 BINARY_OP(VECTOR, SCALAR, out, psType1, op, psType2); // vector op scalar 490 } else if (dim2 == PS_DIMEN_VECTOR || dim2 == PS_DIMEN_TRANSV) { 491 BINARY_OP(VECTOR, VECTOR, out, psType1, op, psType2); // vector op vector 492 } else if (dim2 == PS_DIMEN_IMAGE) { 493 BINARY_OP(VECTOR, IMAGE, out, psType1, op, psType2); // vector op image 494 } else { 495 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 496 } 497 } else if (dim1 == PS_DIMEN_IMAGE) { 498 if (dim2 == PS_DIMEN_SCALAR) { 499 BINARY_OP(IMAGE, SCALAR, out, psType1, op, psType2); // image op scalar 500 } else if (dim2 == PS_DIMEN_VECTOR || dim2 == PS_DIMEN_TRANSV) { 501 BINARY_OP(IMAGE, VECTOR, out, psType1, op, psType2); // image op vector 502 } else if (dim2 == PS_DIMEN_IMAGE) { 503 BINARY_OP(IMAGE, IMAGE, out, psType1, op, psType2); // image op image 504 } else { 505 psError(__func__, ": Line %d - Invalid dimensionality for in2 arg: %d", __LINE__, dim2); 506 } 507 } else { 508 psError(__func__, ": Line %d - Invalid dimensionality for in1 arg: %d", __LINE__, dim1); 509 } 506 510 507 511 return out; … … 567 571 } \ 568 572 } 569 570 573 571 574 // Preprocessor macro function to create arithmetic function based on input type … … 596 599 } 597 600 598 599 601 // Preprocessor macro function to create arithmetic function operation name 600 602 #define UNARY_OP(DIM,OUT,IN,OP) \ … … 714 716 psType *psTypeOut = NULL; 715 717 716 psTypeOut = (psType *)out;717 if (psTypeOut == NULL) {718 psTypeOut = (psType *) out; 719 if (psTypeOut == NULL) { 718 720 psError(__func__, ": Line %d - Null out argument", __LINE__); 719 721 return out; 720 722 } 721 723 722 psTypeIn = (psType *)in;723 if (psTypeIn == NULL) {724 psTypeIn = (psType *) in; 725 if (psTypeIn == NULL) { 724 726 psError(__func__, ": Line %d - Null in argument", __LINE__); 725 727 return out; 726 728 } 727 729 728 if (op == NULL) {730 if (op == NULL) { 729 731 psError(__func__, ": Line %d - Null op argument", __LINE__); 730 732 return out; … … 736 738 elTypeOut = psTypeOut->type; 737 739 738 if (elTypeIn!=elTypeOut) {740 if (elTypeIn != elTypeOut) { 739 741 psError(__func__, ": Line %d - Element types for arguments inconsistent: (%d, %d)", __LINE__, 740 742 elTypeIn, elTypeOut); … … 742 744 } 743 745 744 if (dimIn!=dimOut) {746 if (dimIn != dimOut) { 745 747 psError(__func__, ": Line %d - Dimensionality for arguments inconsistent: (%d, %d)", __LINE__, 746 748 dimIn, dimOut); … … 748 750 } 749 751 750 if (dimIn==PS_DIMEN_OTHER || dimOut==PS_DIMEN_OTHER) {752 if (dimIn == PS_DIMEN_OTHER || dimOut == PS_DIMEN_OTHER) { 751 753 psError(__func__, ": Line %d - PS_DIMEN_OTHER not allowed for arguments: (%d, %d)", __LINE__, 752 754 dimIn, dimOut); … … 754 756 } 755 757 756 if (dimIn == PS_DIMEN_VECTOR) {757 if (((psVector*)in)->n == 0) {758 if (dimIn == PS_DIMEN_VECTOR) { 759 if (((psVector *) in)->n == 0) { 758 760 psError(__func__, ": Line %d - Vector contains zero elements"); 759 761 } 760 } else 761 if(dimIn == PS_DIMEN_IMAGE) { 762 if(((psImage*)in)->numCols==0 || ((psImage*)in)->numRows==0) { 763 psError(__func__, ": Line %d - Image contains zero length row or cols"); 764 } 765 } 766 767 if(dimOut == PS_DIMEN_VECTOR) { 768 if(((psVector*)out)->n == 0) { 762 } else if (dimIn == PS_DIMEN_IMAGE) { 763 if (((psImage *) in)->numCols == 0 || ((psImage *) in)->numRows == 0) { 764 psError(__func__, ": Line %d - Image contains zero length row or cols"); 765 } 766 } 767 768 if (dimOut == PS_DIMEN_VECTOR) { 769 if (((psVector *) out)->n == 0) { 769 770 psError(__func__, ": Line %d - Vector contains zero elements"); 770 771 } 771 } else 772 if(dimOut == PS_DIMEN_IMAGE) { 773 if(((psImage*)out)->numCols==0 || ((psImage*)out)->numRows==0) { 774 psError(__func__, ": Line %d - Image contains zero length row or cols"); 775 } 776 } 777 778 if(dimIn == PS_DIMEN_SCALAR) { 779 UNARY_OP(SCALAR,out,psTypeIn,op); // scalar 780 } else 781 if(dimIn==PS_DIMEN_VECTOR || dimIn==PS_DIMEN_TRANSV) { 782 UNARY_OP(VECTOR,out,psTypeIn,op); // vector 783 } else 784 if(dimIn == PS_DIMEN_IMAGE) { 785 UNARY_OP(IMAGE,out,psTypeIn,op); // image 786 } else { 787 psError(__func__, ": Line %d - Invalid dimensionality for in arg: %d", __LINE__, dimIn); 788 } 772 } else if (dimOut == PS_DIMEN_IMAGE) { 773 if (((psImage *) out)->numCols == 0 || ((psImage *) out)->numRows == 0) { 774 psError(__func__, ": Line %d - Image contains zero length row or cols"); 775 } 776 } 777 778 if (dimIn == PS_DIMEN_SCALAR) { 779 UNARY_OP(SCALAR, out, psTypeIn, op); // scalar 780 } else if (dimIn == PS_DIMEN_VECTOR || dimIn == PS_DIMEN_TRANSV) { 781 UNARY_OP(VECTOR, out, psTypeIn, op); // vector 782 } else if (dimIn == PS_DIMEN_IMAGE) { 783 UNARY_OP(IMAGE, out, psTypeIn, op); // image 784 } else { 785 psError(__func__, ": Line %d - Invalid dimensionality for in arg: %d", __LINE__, dimIn); 786 } 789 787 790 788 return out; -
trunk/psLib/src/dataManip/psMatrixVectorArithmetic.h
r1058 r1407 1 1 2 /** @file psMatrixVectorArithmetic.h 2 3 * … … 29 30 * @author Ross Harman, MHPCC 30 31 * 31 * @version $Revision: 1. 1$ $Name: not supported by cvs2svn $32 * @date $Date: 2004-0 6-18 00:54:43$32 * @version $Revision: 1.2 $ $Name: not supported by cvs2svn $ 33 * @date $Date: 2004-08-07 00:06:06 $ 33 34 * 34 35 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 36 37 37 38 #ifndef PSMATRIX_VECTOR_ARITHMETIC_H 38 # define PSMATRIX_VECTOR_ARITHMETIC_H39 # define PSMATRIX_VECTOR_ARITHMETIC_H 39 40 40 41 /// @addtogroup MatrixVectorArithmetic … … 54 55 * @return psType*: Pointer to either psImage or psVector. 55 56 */ 56 psType *psBinaryOp( 57 void *out, /// Output type, either psImage or psVector. 58 void *in1, /// First input, either psImage or psVector. 59 char *op, /// Operator. 60 void *in2 /// Second input, either psImage or psVector. 61 ); 57 psType *psBinaryOp(void *out, // / Output type, either psImage or psVector. 58 void *in1, // / First input, either psImage or psVector. 59 char *op, // / Operator. 60 void *in2 // / Second input, either psImage or psVector. 61 ); 62 62 63 63 /** Perform simple unary arithmetic with images or vectors … … 77 77 * @return psType*: Pointer to either psImage or psVector. 78 78 */ 79 psType *psUnaryOp( 80 void *out, /// Output type, either psImage or psVector. 81 void *in, /// Input, either psImage or psVector. 82 char *op /// Operator. 83 ); 79 psType *psUnaryOp(void *out, // / Output type, either psImage or psVector. 80 void *in, // / Input, either psImage or psVector. 81 char *op // / Operator. 82 ); 84 83 85 84 /// @} -
trunk/psLib/src/dataManip/psMinimize.c
r1406 r1407 1 1 2 /** @file psMinimize.c 2 3 * \brief basic minimization functions … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.2 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.28 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 /*****************************************************************************/ 17 18 /*****************************************************************************/ 19 17 20 /* INCLUDE FILES */ 21 18 22 /*****************************************************************************/ 19 23 #include <stdlib.h> … … 40 44 #include "psMinimize.h" 41 45 #include "psMatrix.h" 42 /*****************************************************************************/ 46 47 /*****************************************************************************/ 48 43 49 /* DEFINE STATEMENTS */ 50 44 51 /*****************************************************************************/ 45 52 #define MAX_LMM_ITERATIONS 100 … … 83 90 } 84 91 85 86 /*****************************************************************************/ 92 /*****************************************************************************/ 93 87 94 /* TYPE DEFINITIONS */ 95 88 96 /*****************************************************************************/ 89 97 typedef struct 90 98 { 91 size_t n; // Number of data points points in domain.92 int paramCount; // Number of non-masked parameters.93 psVector *restrict initialGuess;94 const psImage *restrict domain;99 size_t n; // Number of data points points in domain. 100 int paramCount; // Number of non-masked parameters. 101 psVector *restrict initialGuess; 102 const psImage *restrict domain; 95 103 const psVector *restrict data; 96 const psVector *restrict errors;104 const psVector *restrict errors; 97 105 const psVector *restrict paramMask; 98 106 float (*evalModel) (const psVector *, const psVector *); … … 103 111 typedef struct 104 112 { 105 int paramCount; // Number of non-masked parameters.106 psVector *restrict initialGuess;107 const psVector *restrict coord;113 int paramCount; // Number of non-masked parameters. 114 psVector *restrict initialGuess; 115 const psVector *restrict coord; 108 116 const psVector *restrict paramMask; 109 117 float (*evalModel) (const psVector *, const psVector *); … … 113 121 114 122 /*****************************************************************************/ 123 115 124 /* GLOBAL VARIABLES */ 125 116 126 /*****************************************************************************/ 117 127 … … 119 129 120 130 /*****************************************************************************/ 131 121 132 /* FILE STATIC VARIABLES */ 133 122 134 /*****************************************************************************/ 123 135 … … 125 137 126 138 /*****************************************************************************/ 139 127 140 /* FUNCTION IMPLEMENTATION - LOCAL */ 141 128 142 /*****************************************************************************/ 129 143 … … 143 157 guess at the parameters, an option parameter mask, etc. 144 158 *****************************************************************************/ 145 double p_psMinFunc(const gsl_vector *params, 146 void *funcData) 147 { 148 int i; // Loop index variable. 149 int j; // Loop index variable. 150 float tmpf; // Temporary floating point variable. 151 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 152 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 153 psVector *restrict initialGuess = ((psMinimizeData *)funcData)->initialGuess; 154 float (*evalModel)(const psVector *, const psVector *) = 155 ((psMinimizeData *) funcData)->evalModel; 159 double p_psMinFunc(const gsl_vector * params, void *funcData) 160 { 161 int i; // Loop index variable. 162 int j; // Loop index variable. 163 float tmpf; // Temporary floating point variable. 164 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 165 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 166 psVector *restrict initialGuess = ((psMinimizeData *) funcData)->initialGuess; 167 float (*evalModel) (const psVector *, const psVector *) = ((psMinimizeData *) funcData)->evalModel; 156 168 psVector *inputParameterList = NULL; 157 169 … … 163 175 if (mask != NULL) { 164 176 j = 0; 165 for (i =0;i<mask->n;i++) {177 for (i = 0; i < mask->n; i++) { 166 178 if (mask->data.U8[i] != 0) { 167 179 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 171 183 } 172 184 } else { 173 for (i =0;i<initialGuess->n;i++) {185 for (i = 0; i < initialGuess->n; i++) { 174 186 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 175 187 } … … 181 193 // Free allocated memory and return the value of the function. 182 194 psFree(inputParameterList); 183 return (tmpf);195 return (tmpf); 184 196 } 185 197 … … 199 211 in "params" and return those derivatives in this psVector. 200 212 *****************************************************************************/ 201 void p_psMinFuncDeriv(const gsl_vector *params, 202 void *funcData, 203 gsl_vector *df) 204 { 205 int i; // Loop index variable. 206 int j; // Loop index variable. 207 float tmpf; // Temporary floating point variable. 208 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 209 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 210 psVector *restrict initialGuess = ((psMinimizeData *)funcData)->initialGuess; 211 float (*d_evalModel)(const psVector *, const psVector *, int) = 213 void p_psMinFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * df) 214 { 215 int i; // Loop index variable. 216 int j; // Loop index variable. 217 float tmpf; // Temporary floating point variable. 218 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 219 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 220 psVector *restrict initialGuess = ((psMinimizeData *) funcData)->initialGuess; 221 float (*d_evalModel) (const psVector *, const psVector *, int) = 212 222 ((psMinimizeData *) funcData)->d_evalModel; 213 223 psVector *inputParameterList = NULL; … … 220 230 if (mask != NULL) { 221 231 j = 0; 222 for (i =0;i<mask->n;i++) {232 for (i = 0; i < mask->n; i++) { 223 233 if (mask->data.U8[i] != 0) { 224 234 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 228 238 } 229 239 } else { 230 for (i =0;i<initialGuess->n;i++) {240 for (i = 0; i < initialGuess->n; i++) { 231 241 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 232 242 } … … 235 245 // Evaluate the derivative w.r.t. each parameter. 236 246 // NOTE: we can probably remove the calls for masked parameters. 237 for (i =0;i<initialGuess->n;i++) {247 for (i = 0; i < initialGuess->n; i++) { 238 248 tmpf = d_evalModel(inputParameterList, coord, i); 239 249 gsl_vector_set(df, i, tmpf); … … 247 257 Compute both p_psMinFunc and p_psMinFuncDeriv together. 248 258 *****************************************************************************/ 249 void p_psMinFuncFuncDeriv(const gsl_vector *params, 250 void *funcData, 251 double *f, 252 gsl_vector *df) 259 void p_psMinFuncFuncDeriv(const gsl_vector * params, void *funcData, double *f, gsl_vector * df) 253 260 { 254 261 *f = p_psMinFunc(params, funcData); … … 281 288 expected value and divide by the error. 282 289 *****************************************************************************/ 283 int p_psMinChi2Func(const gsl_vector *params, 284 void *funcData, 285 gsl_vector *outData) 286 { 287 int i; // Loop index variable. 288 int j; // Loop index variable. 289 float tmpf; // Temporary floating point variable. 290 const psImage *restrict domain = ((psMinChi2Data *)funcData)->domain; 291 const psVector *restrict data = ((psMinChi2Data *)funcData)->data; 292 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 293 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 294 psVector *restrict initialGuess = ((psMinChi2Data *)funcData)->initialGuess; 295 float (*evalModel)(const psVector *, const psVector *) = ((psMinChi2Data *) funcData)->evalModel; 290 int p_psMinChi2Func(const gsl_vector * params, void *funcData, gsl_vector * outData) 291 { 292 int i; // Loop index variable. 293 int j; // Loop index variable. 294 float tmpf; // Temporary floating point variable. 295 const psImage *restrict domain = ((psMinChi2Data *) funcData)->domain; 296 const psVector *restrict data = ((psMinChi2Data *) funcData)->data; 297 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 298 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 299 psVector *restrict initialGuess = ((psMinChi2Data *) funcData)->initialGuess; 300 float (*evalModel) (const psVector *, const psVector *) = ((psMinChi2Data *) funcData)->evalModel; 296 301 psVector *inputParameterList = NULL; 297 302 psVector *tmpVecPtr = NULL; … … 307 312 if (mask != NULL) { 308 313 j = 0; 309 for (i =0;i<mask->n;i++) {314 for (i = 0; i < mask->n; i++) { 310 315 if (mask->data.U8[i] != 0) { 311 316 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 315 320 } 316 321 } else { 317 for (i =0;i<initialGuess->n;i++) {322 for (i = 0; i < initialGuess->n; i++) { 318 323 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 319 324 } … … 321 326 322 327 // Evaluate the function at each data point. 323 for (i =0;i<domain->numRows;i++) {324 for (j =0;j<domain->numCols;j++) {328 for (i = 0; i < domain->numRows; i++) { 329 for (j = 0; j < domain->numCols; j++) { 325 330 tmpVecPtr->data.F32[j] = domain->data.F32[i][j]; 326 331 } 327 332 tmpf = evalModel(tmpVecPtr, inputParameterList); 328 333 329 gsl_vector_set(outData, i, (tmpf - data->data.F32[i])/ 330 errors->data.F32[i]); 334 gsl_vector_set(outData, i, (tmpf - data->data.F32[i]) / errors->data.F32[i]); 331 335 } 332 336 … … 354 358 and returned in this data structure. 355 359 *****************************************************************************/ 356 int p_psMinChi2FuncDeriv(const gsl_vector *params, 357 void *funcData, 358 gsl_matrix *J) 359 { 360 const psImage *restrict domain = ((psMinChi2Data *)funcData)->domain; 361 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 362 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 363 psVector *restrict initialGuess = ((psMinChi2Data *)funcData)->initialGuess; 360 int p_psMinChi2FuncDeriv(const gsl_vector * params, void *funcData, gsl_matrix * J) 361 { 362 const psImage *restrict domain = ((psMinChi2Data *) funcData)->domain; 363 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 364 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 365 psVector *restrict initialGuess = ((psMinChi2Data *) funcData)->initialGuess; 364 366 psVector *inputParameterList = NULL; 365 367 psVector *tmpVecPtr = NULL; 366 float (*d_evalModel)(const psVector *, const psVector *, int) = ((psMinChi2Data *) funcData)->d_evalModel; 368 float (*d_evalModel) (const psVector *, const psVector *, int) = 369 ((psMinChi2Data *) funcData)->d_evalModel; 367 370 368 371 size_t i; … … 380 383 if (mask != NULL) { 381 384 j = 0; 382 for (i =0;i<mask->n;i++) {385 for (i = 0; i < mask->n; i++) { 383 386 if (mask->data.U8[i] != 0) { 384 387 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 388 391 } 389 392 } else { 390 for (i =0;i<initialGuess->n;i++) {393 for (i = 0; i < initialGuess->n; i++) { 391 394 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 392 395 } … … 394 397 395 398 // Evaluate the derivtaive at each data point, and w.r.t. each parameter. 396 for (i =0;i<domain->numRows;i++) {397 for (j =0;j<tmpVecPtr->n;j++) {399 for (i = 0; i < domain->numRows; i++) { 400 for (j = 0; j < tmpVecPtr->n; j++) { 398 401 tmpVecPtr->data.F32[j] = domain->data.F32[i][j]; 399 402 } 400 403 401 for (j =0;j<inputParameterList->n;j++) {404 for (j = 0; j < inputParameterList->n; j++) { 402 405 tmpf = d_evalModel(tmpVecPtr, inputParameterList, j); 403 gsl_matrix_set(J, i, j, (tmpf /errors->data.F32[i]));406 gsl_matrix_set(J, i, j, (tmpf / errors->data.F32[i])); 404 407 } 405 408 } … … 410 413 } 411 414 412 413 int p_psMinChi2FuncFuncDeriv(const gsl_vector *params, 414 void *funcData, 415 gsl_vector *f, 416 gsl_matrix *J) 415 int p_psMinChi2FuncFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * f, gsl_matrix * J) 417 416 { 418 417 p_psMinChi2Func(params, funcData, f); … … 421 420 return GSL_SUCCESS; 422 421 } 423 424 422 425 423 /****************************************************************************** … … 428 426 returned as a psVector sums. 429 427 *****************************************************************************/ 430 void p_psBuildSums1D(double x, 431 int polyOrder, 432 psVector *sums) 433 { 434 int i = 0; 435 double xSum = 0.0; 428 void p_psBuildSums1D(double x, int polyOrder, psVector * sums) 429 { 430 int i = 0; 431 double xSum = 0.0; 436 432 437 433 xSum = 1.0; 438 for (i=0;i<=polyOrder;i++) {434 for (i = 0; i <= polyOrder; i++) { 439 435 sums->data.F64[i] = xSum; 440 xSum*= x; 441 } 442 } 443 436 xSum *= x; 437 } 438 } 444 439 445 440 /****************************************************************************** … … 448 443 *****************************************************************************/ 449 444 psVector *psBuildImageScalingFactors(int x) 450 451 445 { 452 446 int i = 0; // loop index variable. 453 447 psVector *imageScalingFactors = NULL; 454 448 455 456 449 imageScalingFactors = psVectorAlloc(x, PS_TYPE_F32); 457 450 458 for (i =0;i<x;i++) {459 imageScalingFactors->data.F32[i] = (((float) 2*i) / ((float)x)) - 1.0;460 } 461 462 return (imageScalingFactors);451 for (i = 0; i < x; i++) { 452 imageScalingFactors->data.F32[i] = (((float)2 * i) / ((float)x)) - 1.0; 453 } 454 455 return (imageScalingFactors); 463 456 } 464 457 … … 481 474 *flag Set this to 1 if we must recalculate the coefficients. 482 475 *****************************************************************************/ 483 void p_psPolyOrderCheck(float **A, 484 int N, 485 int *indx, 486 float *B, 487 int polyOrder, 488 int *flag) 489 { 490 float **y = NULL; // This 2-D matrix will hold A^-1 491 float *col = NULL; // misc NumerRecipes data structure 492 float *error=NULL; // will hold the sqrt() of the 476 void p_psPolyOrderCheck(float **A, int N, int *indx, float *B, int polyOrder, int *flag) 477 { 478 float **y = NULL; // This 2-D matrix will hold A^-1 479 float *col = NULL; // misc NumerRecipes data structure 480 float *error = NULL; // will hold the sqrt() of the 481 493 482 // diagonal of y[][]. 494 int i=0; // loop-index variable 495 int j=0; // loop-index variable 496 int numPolyTerms = 0; // The number of terms in the 483 int i = 0; // loop-index variable 484 int j = 0; // loop-index variable 485 int numPolyTerms = 0; // The number of terms in the 486 497 487 // polynomial. 498 int lastTerm = 0; // The index location of the first 488 int lastTerm = 0; // The index location of the first 489 499 490 // n-th order term in array B[]. 500 int firstTerm = 0; // Index location of last such term.491 int firstTerm = 0; // Index location of last such term. 501 492 502 493 // Allocate the necessary data structures for this procedure... 503 error = (float *) psAlloc((N + 1) * sizeof(float));504 col = (float *) psAlloc((N + 1) * sizeof(float));505 y = (float **) psAlloc((N + 1) * sizeof(float *));506 for (i=1;i<=N;i++) {507 y[i] = (float *) psAlloc((N + 1) * sizeof(float));494 error = (float *)psAlloc((N + 1) * sizeof(float)); 495 col = (float *)psAlloc((N + 1) * sizeof(float)); 496 y = (float **)psAlloc((N + 1) * sizeof(float *)); 497 for (i = 1; i <= N; i++) { 498 y[i] = (float *)psAlloc((N + 1) * sizeof(float)); 508 499 } 509 500 510 501 // Invert the matrix A and put the result in y[][]. This code is taken 511 502 // from Numerical Recipes in C page 48. 512 for (j=1;j<=N;j++) {513 for (i=1;i<=N;i++) {503 for (j = 1; j <= N; j++) { 504 for (i = 1; i <= N; i++) { 514 505 col[i] = 0.0; 515 506 } 516 507 col[j] = 1.0; 517 508 // NOTE: substitue the LUD rotine 518 // lubksb(A, N, indx, col);519 for (i=1;i<=N;i++) {509 // lubksb(A, N, indx, col); 510 for (i = 1; i <= N; i++) { 520 511 y[i][j] = col[i]; 521 512 } … … 527 518 // terms and check if they are consistent with zero. 528 519 529 numPolyTerms = (((polyOrder +1) * (polyOrder + 2)) / 2);520 numPolyTerms = (((polyOrder + 1) * (polyOrder + 2)) / 2); 530 521 lastTerm = numPolyTerms + 1; 531 522 firstTerm = lastTerm - polyOrder; 532 523 *flag = 1; 533 for (i =firstTerm; i<=lastTerm; i++) {524 for (i = firstTerm; i <= lastTerm; i++) { 534 525 #ifdef DARWIN 535 526 error[i] = (float)sqrt(y[i][i]); … … 539 530 #endif 540 531 541 if (!((B[i] <= (2.0f * error[i])) && 542 ((-2.0f * error[i]) <= B[i]))) { 532 if (!((B[i] <= (2.0f * error[i])) && ((-2.0f * error[i]) <= B[i]))) { 543 533 *flag = 0; 544 534 } … … 548 538 psFree(error); 549 539 psFree(col); 550 for (j=1;j<=N;j++) {540 for (j = 1; j <= N; j++) { 551 541 psFree(y[j]); 552 542 } … … 554 544 } 555 545 556 557 558 559 /*****************************************************************************/ 546 /*****************************************************************************/ 547 560 548 /* FUNCTION IMPLEMENTATION - PUBLIC */ 561 /*****************************************************************************/ 562 563 549 550 /*****************************************************************************/ 564 551 565 552 /****************************************************************************** … … 569 556 parameters of that function such that the ... 570 557 *****************************************************************************/ 571 psVector * 572 psMinimize(psVector *restrict initialGuess, 573 float (*myFunction)(const psVector *restrict, const psVector *restrict), 574 float (*myFunctionDeriv)(const psVector *restrict, const psVector *restrict, int), 575 const psVector *restrict coord, 576 const psVector *restrict paramMask) 558 psVector *psMinimize(psVector * restrict initialGuess, 559 float (*myFunction) (const psVector * restrict, const psVector * restrict), 560 float (*myFunctionDeriv) (const psVector * restrict, const psVector * restrict, int), 561 const psVector * restrict coord, const psVector * restrict paramMask) 577 562 { 578 563 int status; … … 607 592 // for the parameters. 608 593 if (paramMask != NULL) { 609 for (i =0;i<paramMask->n;i++) {594 for (i = 0; i < paramMask->n; i++) { 610 595 if (paramMask->data.U8[i] != 0) { 611 596 inputData.paramCount++; … … 613 598 } 614 599 } else { 615 inputData.paramCount = initialGuess->n;600 inputData.paramCount = initialGuess->n; 616 601 } 617 602 … … 622 607 if (paramMask != NULL) { 623 608 j = 0; 624 for (i =0;i<initialGuess->n;i++) {609 for (i = 0; i < initialGuess->n; i++) { 625 610 if (paramMask->data.U8[i] == 0) { 626 611 gsl_vector_set(x, j++, initialGuess->data.F32[i]); … … 628 613 } 629 614 } else { 630 for (i =0;i<initialGuess->n;i++) {615 for (i = 0; i < initialGuess->n; i++) { 631 616 gsl_vector_set(x, i, initialGuess->data.F32[i]); 632 617 } … … 651 636 652 637 if (status == GSL_SUCCESS) 653 printf ("Minimum found at:\n");638 printf("Minimum found at:\n"); 654 639 655 640 } while (status == GSL_CONTINUE && iter < MAX_MINIMIZE_ITERATIONS); … … 660 645 if (paramMask != NULL) { 661 646 j = 0; 662 for (i =0;i<initialGuess->n;i++) {647 for (i = 0; i < initialGuess->n; i++) { 663 648 if (paramMask->data.U8[i] == 0) { 664 649 initialGuess->data.F32[i] = gsl_vector_get(s->x, j++); … … 668 653 } 669 654 } else { 670 for (i =0;i<initialGuess->n;i++) {655 for (i = 0; i < initialGuess->n; i++) { 671 656 initialGuess->data.F32[i] = gsl_vector_get(s->x, i); 672 657 } 673 658 } 674 return(initialGuess); 675 } 676 677 678 679 680 659 return (initialGuess); 660 } 681 661 682 662 /****************************************************************************** … … 684 664 such that they best fit the supplied data points. 685 665 *****************************************************************************/ 686 psVector * 687 psMinimizeChi2(float (*evalModel)(const psVector *restrict, const psVector *restrict), 688 float (*DevalModel)(const psVector *restrict, const psVector *restrict, int), 689 const psImage *restrict domain, 690 const psVector *restrict data, 691 const psVector *restrict errors, 692 psVector *restrict initialGuess, 693 const psVector *restrict paramMask, 694 float *chiSq) 695 { 696 int numData = domain->numRows; // Number of data points 697 int status; // Return status for the GSL solver. 698 int i = 0; // Loop index variable. 699 int j = 0; // Loop index variable. 700 int iter = 0; // Iteration counter. 701 gsl_multifit_function_fdf f; // GSL structure that contains the 666 psVector *psMinimizeChi2(float (*evalModel) (const psVector * restrict, const psVector * restrict), 667 float (*DevalModel) (const psVector * restrict, const psVector * restrict, int), 668 const psImage * restrict domain, 669 const psVector * restrict data, 670 const psVector * restrict errors, 671 psVector * restrict initialGuess, const psVector * restrict paramMask, float *chiSq) 672 { 673 int numData = domain->numRows; // Number of data points 674 int status; // Return status for the GSL solver. 675 int i = 0; // Loop index variable. 676 int j = 0; // Loop index variable. 677 int iter = 0; // Iteration counter. 678 gsl_multifit_function_fdf f; // GSL structure that contains the 679 702 680 // functions/derivative to be solved. 703 double *xInit = NULL; // The initial guess at the parameters 681 double *xInit = NULL; // The initial guess at the parameters 682 704 683 // with masked parameters removed. 705 684 const gsl_multifit_fdfsolver_type *T; 685 706 686 // This tells GSL to use the Levenberg- 707 687 // Marquardt algorithm for chi2 708 688 // minimization. 709 gsl_multifit_fdfsolver *s; // GSL data structure.689 gsl_multifit_fdfsolver *s; // GSL data structure. 710 690 psMinChi2Data inputData; 711 691 float chiSqOld = 0.0; … … 721 701 PS_CHECK_VECTOR_SIZE_EQUAL(data, errors); 722 702 if (domain->numRows != data->n) { 723 psAbort(__func__, "Number of data points and data values not equal.");703 psAbort(__func__, "Number of data points and data values not equal."); 724 704 } 725 705 if (paramMask != NULL) { … … 743 723 // for the parameters. 744 724 if (paramMask != NULL) { 745 for (i =0;i<paramMask->n;i++) {725 for (i = 0; i < paramMask->n; i++) { 746 726 if (paramMask->data.U8[i] != 0) { 747 727 inputData.paramCount++; … … 749 729 } 750 730 } else { 751 inputData.paramCount = initialGuess->n;731 inputData.paramCount = initialGuess->n; 752 732 } 753 733 … … 755 735 // the vector inputParameterList. If the paramMask is not NULL, then those 756 736 // parameters are masked out. 757 xInit = (double *) psAlloc(inputData.paramCount * sizeof(double));737 xInit = (double *)psAlloc(inputData.paramCount * sizeof(double)); 758 738 if (paramMask != NULL) { 759 739 j = 0; 760 for (i =0;i<initialGuess->n;i++) {740 for (i = 0; i < initialGuess->n; i++) { 761 741 if (paramMask->data.U8[i] == 0) { 762 742 xInit[j++] = initialGuess->data.F32[i]; … … 764 744 } 765 745 } else { 766 for (i =0;i<initialGuess->n;i++) {746 for (i = 0; i < initialGuess->n; i++) { 767 747 xInit[i] = initialGuess->data.F32[i]; 768 748 } … … 771 751 const gsl_rng_type *type; 772 752 gsl_rng *r; 753 773 754 gsl_rng_env_setup(); 774 755 … … 789 770 790 771 gsl_vector_view x = gsl_vector_view_array(xInit, inputData.paramCount); 772 791 773 T = gsl_multifit_fdfsolver_lmsder; 792 774 s = gsl_multifit_fdfsolver_alloc(T, numData, inputData.paramCount); … … 796 778 do { 797 779 iter++; 798 for (i =0;i<initialGuess->n;i++) {780 for (i = 0; i < initialGuess->n; i++) { 799 781 printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i)); 800 782 } … … 802 784 status = gsl_multifit_fdfsolver_iterate(s); 803 785 printf("gsl_multifit_fdfsolver_iterate() status is %s\n", gsl_strerror(status)); 804 for (i =0;i<initialGuess->n;i++) {786 for (i = 0; i < initialGuess->n; i++) { 805 787 printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i)); 806 788 } … … 810 792 psAbort(__func__, "gsl_multifit_fdfsolver_iterate(%s)\n", gsl_strerror(status)); 811 793 } 812 813 794 // Test if the parameters changed by a small enough amount. 814 795 // NOTE: This wasn't working right when the parameters fit exactly. 815 796 // Figure out why. 816 // status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4);797 // status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4); 817 798 818 799 // We test for convergence if chiSquared changes by less than 1.0 … … 829 810 } while (status == GSL_CONTINUE && iter < MAX_LMM_ITERATIONS); 830 811 831 832 812 // In the above steps we had removed the masked elements from the 833 813 // the solver. This next code blocks puts those masked elements … … 835 815 if (paramMask != NULL) { 836 816 j = 0; 837 for (i =0;i<initialGuess->n;i++) {817 for (i = 0; i < initialGuess->n; i++) { 838 818 if (paramMask->data.U8[i] == 0) { 839 819 initialGuess->data.F32[i] = gsl_vector_get(s->x, j++); … … 843 823 } 844 824 } else { 845 for (i =0;i<initialGuess->n;i++) {825 for (i = 0; i < initialGuess->n; i++) { 846 826 initialGuess->data.F32[i] = gsl_vector_get(s->x, i); 847 827 } … … 857 837 858 838 // Bye bye. 859 return(initialGuess); 860 } 861 839 return (initialGuess); 840 } 862 841 863 842 /****************************************************************************** … … 868 847 NOTE: yErr is currently ignored. 869 848 *****************************************************************************/ 870 psPolynomial1D * 871 psVectorFitPolynomial1D(psPolynomial1D *myPoly, 872 const psVector *restrict x, 873 const psVector *restrict y, 874 const psVector *restrict yErr) 849 psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly, 850 const psVector * restrict x, 851 const psVector * restrict y, const psVector * restrict yErr) 875 852 { 876 853 int polyOrder = myPoly->n; … … 879 856 psVector *B = NULL; 880 857 psVector *outPerm = NULL; 881 psVector *X = NULL; // NOTE: do we need this?858 psVector *X = NULL; // NOTE: do we need this? 882 859 psVector *coeffs = NULL; 883 860 int i = 0; … … 886 863 psVector *xSums = NULL; 887 864 888 // printf("psVectorFitPolynomial1D()\n");889 // for (i=0;i<x->n;i++) {890 // printf("(x, y, yErr) is (%f, %f, %f)\n", x->data.F64[i], y->data.F64[i], yErr->data.F64[i]);891 // }865 // printf("psVectorFitPolynomial1D()\n"); 866 // for (i=0;i<x->n;i++) { 867 // printf("(x, y, yErr) is (%f, %f, %f)\n", x->data.F64[i], y->data.F64[i], yErr->data.F64[i]); 868 // } 892 869 893 870 PS_CHECK_NULL_1DPOLY(myPoly); … … 901 878 PS_CHECK_VECTOR_SIZE_EQUAL(y, yErr); 902 879 903 A = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64);904 ALUD = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64);905 B = psVectorAlloc(polyOrder, PS_TYPE_F64);906 coeffs = psVectorAlloc(polyOrder, PS_TYPE_F64);907 X = psVectorAlloc(x->n, PS_TYPE_F64);880 A = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64); 881 ALUD = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64); 882 B = psVectorAlloc(polyOrder, PS_TYPE_F64); 883 coeffs = psVectorAlloc(polyOrder, PS_TYPE_F64); 884 X = psVectorAlloc(x->n, PS_TYPE_F64); 908 885 outPerm = psVectorAlloc(polyOrder, PS_TYPE_F64); 909 xSums = psVectorAlloc(1+2*polyOrder, PS_TYPE_F64);886 xSums = psVectorAlloc(1 + 2 * polyOrder, PS_TYPE_F64); 910 887 911 888 // Initialize data structures. 912 for (i=0;i<(polyOrder);i++) {889 for (i = 0; i < (polyOrder); i++) { 913 890 B->data.F64[i] = 0.0; 914 891 coeffs->data.F64[i] = 0.0; 915 892 outPerm->data.F64[i] = 0.0; 916 for (j=0;j<(polyOrder);j++) {893 for (j = 0; j < (polyOrder); j++) { 917 894 A->data.F64[i][j] = 0.0; 918 895 ALUD->data.F64[i][j] = 0.0; 919 896 } 920 897 } 921 for (i =0;i<X->n;i++) {898 for (i = 0; i < X->n; i++) { 922 899 X->data.F64[i] = x->data.F64[i]; 923 900 } 924 901 925 902 // Build the B and A data structs. 926 for (i =0;i<X->n;i++) {927 p_psBuildSums1D(X->data.F64[i], 2 *polyOrder, xSums);928 929 for (k=0;k<(polyOrder);k++) {930 B->data.F64[k] += y->data.F64[i] * xSums->data.F64[k];931 } 932 933 for (k=0;k<(polyOrder);k++) {934 for (j=0;j<(polyOrder);j++) {935 A->data.F64[k][j] += xSums->data.F64[k+j];903 for (i = 0; i < X->n; i++) { 904 p_psBuildSums1D(X->data.F64[i], 2 * polyOrder, xSums); 905 906 for (k = 0; k < (polyOrder); k++) { 907 B->data.F64[k] += y->data.F64[i] * xSums->data.F64[k]; 908 } 909 910 for (k = 0; k < (polyOrder); k++) { 911 for (j = 0; j < (polyOrder); j++) { 912 A->data.F64[k][j] += xSums->data.F64[k + j]; 936 913 } 937 914 } … … 941 918 coeffs = psMatrixLUSolve(coeffs, ALUD, B, outPerm); 942 919 943 for (k=0;k<(polyOrder);k++) {920 for (k = 0; k < (polyOrder); k++) { 944 921 myPoly->coeff[k] = coeffs->data.F64[k]; 945 // printf("myPoly->coeff[%d] is %f\n", k, myPoly->coeff[k]);946 } 947 948 949 // for (i=0;i<x->n;i++) {950 // printf("HMMM: psEvalPolynomial1D(%f) is %f\n", x->data.F64[i], psEvalPolynomial1D(x->data.F64[i],myPoly));951 // }922 // printf("myPoly->coeff[%d] is %f\n", k, myPoly->coeff[k]); 923 } 924 925 // for (i=0;i<x->n;i++) { 926 // printf("HMMM: psEvalPolynomial1D(%f) is %f\n", x->data.F64[i], psEvalPolynomial1D(x->data.F64[i], 927 // myPoly)); 928 // } 952 929 953 930 psFree(A); … … 959 936 psFree(xSums); 960 937 961 return (myPoly);962 } 938 return (myPoly); 939 } -
trunk/psLib/src/dataManip/psMinimize.h
r1406 r1407 1 1 #if !defined(PS_MINIMIZE_H) 2 # define PS_MINIMIZE_H2 # define PS_MINIMIZE_H 3 3 4 #include "psFunctions.h" 4 # include "psFunctions.h" 5 5 6 /** \file psMinimize.h 6 7 * \brief minimization operations … … 9 10 10 11 /** Functions **************************************************************/ 12 11 13 /** \addtogroup Stats 12 14 * \{ … … 14 16 15 17 /** This routine must minimize a non-linear function */ 16 psVector * 17 psMinimize(psVector *restrict initialGuess, 18 float (*myFunction)(const psVector *restrict, const psVector *restrict), 19 float (*myFunctionDeriv)(const psVector *restrict, const psVector *restrict, int), 20 const psVector *restrict coord, 21 const psVector *restrict paramMask); 22 18 psVector *psMinimize(psVector * restrict initialGuess, 19 float (*myFunction) (const psVector * restrict, const psVector * restrict), 20 float (*myFunctionDeriv) (const psVector * restrict, const psVector * restrict, int), 21 const psVector * restrict coord, const psVector * restrict paramMask); 23 22 24 23 /** Minimize chi^2 for input data */ 25 psVector * 26 psMinimizeChi2(float (*evalModel)(const psVector *restrict, 27 const psVector *restrict), ///< Model to fit; (domain and params) 28 float (*DevalModel)(const psVector *restrict, 29 const psVector *restrict, 30 int), ///< Derivative of model to fit; (domain and params) 31 const psImage *restrict domain, ///< The domain values for the corresponding measurements 32 const psVector *restrict data, ///< Data to fit 33 const psVector *restrict errors, ///< Errors in the data 34 psVector *restrict initialGuess, ///< Initial guess 35 const psVector *restrict paramMask, ///< 1 = fit for parameter, 0 = hold parameter constant 36 float *chiSq 37 ); 24 psVector *psMinimizeChi2(float (*evalModel) (const psVector * restrict, const psVector * restrict), // /< 25 // Model 26 // to 27 // fit; 28 // (domain 29 // and 30 // params) 31 float (*DevalModel) (const psVector * restrict, const psVector * restrict, int), // /< 32 // Derivative 33 // of 34 // model 35 // to 36 // fit; 37 // (domain 38 // and 39 // params) 40 const psImage * restrict domain, // /< The domain values for the corresponding 41 // measurements 42 const psVector * restrict data, // /< Data to fit 43 const psVector * restrict errors, // /< Errors in the data 44 psVector * restrict initialGuess, // /< Initial guess 45 const psVector * restrict paramMask, // /< 1 = fit for parameter, 0 = hold 46 // parameter constant 47 float *chiSq); 38 48 39 49 /** Derive a polynomial fit by chi^2 minimisation (analytically) */ 40 psPolynomial1D * 41 psVectorFitPolynomial1D(psPolynomial1D *myPoly, ///< Polynomial to fit 42 const psVector *restrict x, ///< Ordinates (or NULL to just usethe indices)43 const psVector *restrict y, ///< Coordinates44 const psVector *restrict yErr ///< Errors in coordinates, or NULL45 );50 psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly, // /< Polynomial to fit 51 const psVector * restrict x, // /< Ordinates (or NULL to just use 52 // the indices) 53 const psVector * restrict y, // /< Coordinates 54 const psVector * restrict yErr // /< Errors in coordinates, or NULL 55 ); 46 56 47 /* \} */ // End of MathGroup Functions57 /* \} */// End of MathGroup Functions 48 58 49 59 #endif -
trunk/psLib/src/dataManip/psStats.c
r1406 r1407 1 1 2 /** @file psStats.c 2 3 * \brief basic statistical operations … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.5 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.52 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 21 22 #include <float.h> 22 23 #include <math.h> 24 23 25 /*****************************************************************************/ 26 24 27 /* INCLUDE FILES */ 28 25 29 /*****************************************************************************/ 26 30 #include "psMemory.h" … … 35 39 36 40 /*****************************************************************************/ 41 37 42 /* DEFINE STATEMENTS */ 43 38 44 /*****************************************************************************/ 39 45 // will use robust statistical methods. 40 #define GAUSS_WIDTH 20 // The width of the Gaussian or boxcar smoothing.46 #define GAUSS_WIDTH 20 // The width of the Gaussian or boxcar smoothing. 41 47 #define CLIPPED_NUM_ITER_LB 1 42 48 #define CLIPPED_NUM_ITER_UB 10 … … 48 54 #define MAX_ITERATIONS 10 49 55 50 void p_psVectorRobustStats( const psVector *restrict myVector, 51 const psVector *restrict maskVector, 52 unsigned int maskVal, 53 psStats *stats ); 56 void p_psVectorRobustStats(const psVector * restrict myVector, 57 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats); 54 58 55 59 /** Preprocessor macro to generate error on an incorrect type */ … … 83 87 printf("\n"); \ 84 88 89 85 90 /*****************************************************************************/ 91 86 92 /* TYPE DEFINITIONS */ 93 87 94 /*****************************************************************************/ 88 95 89 96 /*****************************************************************************/ 97 90 98 /* GLOBAL VARIABLES */ 99 91 100 /*****************************************************************************/ 92 101 … … 94 103 95 104 /*****************************************************************************/ 105 96 106 /* FILE STATIC VARIABLES */ 107 97 108 /*****************************************************************************/ 98 109 … … 100 111 101 112 /*****************************************************************************/ 113 102 114 /* FUNCTION IMPLEMENTATION - LOCAL */ 115 103 116 /*****************************************************************************/ 104 117 105 bool p_psGetStatValue( const psStats* stats, double* value ) 106 { 107 108 switch ( stats->options & 109 ~ ( PS_STAT_USE_RANGE | PS_STAT_USE_BINSIZE | PS_STAT_ROBUST_FOR_SAMPLE ) ) { 118 bool p_psGetStatValue(const psStats * stats, double *value) 119 { 120 121 switch (stats->options & ~(PS_STAT_USE_RANGE | PS_STAT_USE_BINSIZE | PS_STAT_ROBUST_FOR_SAMPLE)) { 110 122 case PS_STAT_SAMPLE_MEAN: 111 123 *value = stats->sampleMean; … … 163 175 *****************************************************************************/ 164 176 165 void p_psVectorPrint( psVector *myVector, 166 psVector *maskVector, 167 unsigned int maskVal, 168 psStats *stats ) 169 { 170 int i = 0; // Loop index variable. 171 172 for ( i = 0;i < myVector->n;i++ ) { 173 if ( maskVector != NULL ) 174 printf( "Element %d is %f (mask is %d)\n", i, myVector->data.F32[ i ], maskVector->data.U8[ i ] ); 177 void p_psVectorPrint(psVector * myVector, psVector * maskVector, unsigned int maskVal, psStats * stats) 178 { 179 int i = 0; // Loop index variable. 180 181 for (i = 0; i < myVector->n; i++) { 182 if (maskVector != NULL) 183 printf("Element %d is %f (mask is %d)\n", i, myVector->data.F32[i], maskVector->data.U8[i]); 175 184 else 176 printf( "Element %d is %f\n", i, myVector->data.F32[ i ]);185 printf("Element %d is %f\n", i, myVector->data.F32[i]); 177 186 } 178 187 } … … 195 204 *****************************************************************************/ 196 205 197 198 206 /****************************************************************************** 199 207 p_psVectorSampleMean(myVector, maskVector, maskVal, stats): calculates the … … 210 218 *****************************************************************************/ 211 219 212 void p_psVectorSampleMean( const psVector *restrict myVector, 213 const psVector *restrict maskVector, 214 unsigned int maskVal, 215 psStats *stats ) 216 { 217 int i = 0; // Loop index variable 218 float mean = 0.0; // The mean 219 int count = 0; // # of points in this mean? 220 float rangeMin = 0.0; // Exclude data below this 221 float rangeMax = 0.0; // Exclude date above this 220 void p_psVectorSampleMean(const psVector * restrict myVector, 221 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 222 { 223 int i = 0; // Loop index variable 224 float mean = 0.0; // The mean 225 int count = 0; // # of points in this mean? 226 float rangeMin = 0.0; // Exclude data below this 227 float rangeMax = 0.0; // Exclude date above this 222 228 223 229 // If PS_STAT_USE_RANGE is requested, then we enter a slightly different 224 230 // loop. 225 if ( stats->options & PS_STAT_USE_RANGE) {231 if (stats->options & PS_STAT_USE_RANGE) { 226 232 rangeMin = stats->min; 227 233 rangeMax = stats->max; 228 if ( maskVector != NULL) {229 for ( i = 0;i < myVector->n;i++) {234 if (maskVector != NULL) { 235 for (i = 0; i < myVector->n; i++) { 230 236 // Check if the data is with the specified range 231 if ( !( maskVal & maskVector->data.U8[ i ] ) && 232 ( rangeMin <= myVector->data.F32[ i ] ) && 233 ( myVector->data.F32[ i ] <= rangeMax ) ) { 234 mean += myVector->data.F32[ i ]; 237 if (!(maskVal & maskVector->data.U8[i]) && 238 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 239 mean += myVector->data.F32[i]; 235 240 count++; 236 241 } 237 242 } 238 mean /= ( float )count;243 mean /= (float)count; 239 244 } else { 240 for ( i = 0;i < myVector->n;i++ ) { 241 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 242 ( myVector->data.F32[ i ] <= rangeMax ) ) { 243 mean += myVector->data.F32[ i ]; 245 for (i = 0; i < myVector->n; i++) { 246 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 247 mean += myVector->data.F32[i]; 244 248 count++; 245 249 } 246 250 } 247 mean /= ( float )count;251 mean /= (float)count; 248 252 } 249 253 } else { 250 if ( maskVector != NULL) {251 for ( i = 0;i < myVector->n;i++) {252 if ( !( maskVal & maskVector->data.U8[ i ] )) {253 mean += myVector->data.F32[ i];254 if (maskVector != NULL) { 255 for (i = 0; i < myVector->n; i++) { 256 if (!(maskVal & maskVector->data.U8[i])) { 257 mean += myVector->data.F32[i]; 254 258 count++; 255 259 } 256 260 } 257 mean /= ( float )count;261 mean /= (float)count; 258 262 } else { 259 for ( i = 0;i < myVector->n;i++) {260 mean += myVector->data.F32[ i];261 } 262 mean /= ( float )myVector->n;263 for (i = 0; i < myVector->n; i++) { 264 mean += myVector->data.F32[i]; 265 } 266 mean /= (float)myVector->n; 263 267 } 264 268 } … … 278 282 NULL 279 283 *****************************************************************************/ 280 void p_psVectorMax( const psVector *restrict myVector, 281 const psVector *restrict maskVector, 282 unsigned int maskVal, 283 psStats *stats ) 284 { 285 int i = 0; // Loop index variable 286 float max = -MY_MAX_FLOAT; // The calculated maximum 287 float rangeMin = 0.0; // Exclude data below this 288 float rangeMax = 0.0; // Exclude date above this 284 void p_psVectorMax(const psVector * restrict myVector, 285 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 286 { 287 int i = 0; // Loop index variable 288 float max = -MY_MAX_FLOAT; // The calculated maximum 289 float rangeMin = 0.0; // Exclude data below this 290 float rangeMax = 0.0; // Exclude date above this 289 291 290 292 // If PS_STAT_USE_RANGE is requested, then we enter a different loop. 291 if ( stats->options & PS_STAT_USE_RANGE) {293 if (stats->options & PS_STAT_USE_RANGE) { 292 294 rangeMin = stats->min; 293 295 rangeMax = stats->max; 294 if ( maskVector != NULL ) { 295 for ( i = 0;i < myVector->n;i++ ) { 296 if ( !( maskVal & maskVector->data.U8[ i ] ) ) { 297 if ( ( myVector->data.F32[ i ] > max ) && 298 ( rangeMin <= myVector->data.F32[ i ] ) && 299 ( myVector->data.F32[ i ] <= rangeMax ) ) { 300 max = myVector->data.F32[ i ]; 296 if (maskVector != NULL) { 297 for (i = 0; i < myVector->n; i++) { 298 if (!(maskVal & maskVector->data.U8[i])) { 299 if ((myVector->data.F32[i] > max) && 300 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 301 max = myVector->data.F32[i]; 301 302 } 302 303 } 303 304 } 304 305 } else { 305 for ( i = 0;i < myVector->n;i++ ) { 306 if ( ( myVector->data.F32[ i ] > max ) && 307 ( rangeMin <= myVector->data.F32[ i ] ) && 308 ( myVector->data.F32[ i ] <= rangeMax ) ) { 309 max = myVector->data.F32[ i ]; 306 for (i = 0; i < myVector->n; i++) { 307 if ((myVector->data.F32[i] > max) && 308 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 309 max = myVector->data.F32[i]; 310 310 } 311 311 } 312 312 } 313 313 } else { 314 if ( maskVector != NULL) {315 for ( i = 0;i < myVector->n;i++) {316 if ( !( maskVal & maskVector->data.U8[ i ] )) {317 if ( myVector->data.F32[ i ] > max) {318 max = myVector->data.F32[ i];314 if (maskVector != NULL) { 315 for (i = 0; i < myVector->n; i++) { 316 if (!(maskVal & maskVector->data.U8[i])) { 317 if (myVector->data.F32[i] > max) { 318 max = myVector->data.F32[i]; 319 319 } 320 320 } 321 321 } 322 322 } else { 323 for ( i = 0;i < myVector->n;i++) {324 if ( myVector->data.F32[ i ] > max) {325 max = myVector->data.F32[ i];323 for (i = 0; i < myVector->n; i++) { 324 if (myVector->data.F32[i] > max) { 325 max = myVector->data.F32[i]; 326 326 } 327 327 } … … 343 343 NULL 344 344 *****************************************************************************/ 345 void p_psVectorMin( const psVector *restrict myVector, 346 const psVector *restrict maskVector, 347 unsigned int maskVal, 348 psStats *stats ) 349 { 350 int i = 0; // Loop index variable 351 float min = MY_MAX_FLOAT; // The calculated maximum 352 float rangeMin = 0.0; // Exclude data below this 353 float rangeMax = 0.0; // Exclude date above this 354 355 if ( stats->options & PS_STAT_USE_RANGE ) { 345 void p_psVectorMin(const psVector * restrict myVector, 346 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 347 { 348 int i = 0; // Loop index variable 349 float min = MY_MAX_FLOAT; // The calculated maximum 350 float rangeMin = 0.0; // Exclude data below this 351 float rangeMax = 0.0; // Exclude date above this 352 353 if (stats->options & PS_STAT_USE_RANGE) { 356 354 rangeMin = stats->min; 357 355 rangeMax = stats->max; 358 if ( maskVector != NULL ) { 359 for ( i = 0;i < myVector->n;i++ ) { 360 if ( !( maskVal & maskVector->data.U8[ i ] ) ) { 361 if ( ( myVector->data.F32[ i ] < min ) && 362 ( rangeMin <= myVector->data.F32[ i ] ) && 363 ( myVector->data.F32[ i ] <= rangeMax ) ) { 364 min = myVector->data.F32[ i ]; 356 if (maskVector != NULL) { 357 for (i = 0; i < myVector->n; i++) { 358 if (!(maskVal & maskVector->data.U8[i])) { 359 if ((myVector->data.F32[i] < min) && 360 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 361 min = myVector->data.F32[i]; 365 362 } 366 363 } 367 364 } 368 365 } else { 369 for ( i = 0;i < myVector->n;i++ ) { 370 if ( ( myVector->data.F32[ i ] < min ) && 371 ( rangeMin <= myVector->data.F32[ i ] ) && 372 ( myVector->data.F32[ i ] <= rangeMax ) ) { 373 min = myVector->data.F32[ i ]; 366 for (i = 0; i < myVector->n; i++) { 367 if ((myVector->data.F32[i] < min) && 368 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 369 min = myVector->data.F32[i]; 374 370 } 375 371 } 376 372 } 377 373 } else { 378 if ( maskVector != NULL) {379 for ( i = 0;i < myVector->n;i++) {380 if ( !( maskVal & maskVector->data.U8[ i ] )) {381 if ( myVector->data.F32[ i ] < min) {382 min = myVector->data.F32[ i];374 if (maskVector != NULL) { 375 for (i = 0; i < myVector->n; i++) { 376 if (!(maskVal & maskVector->data.U8[i])) { 377 if (myVector->data.F32[i] < min) { 378 min = myVector->data.F32[i]; 383 379 } 384 380 } 385 381 } 386 382 } else { 387 for ( i = 0;i < myVector->n;i++) {388 if ( myVector->data.F32[ i ] < min) {389 min = myVector->data.F32[ i];383 for (i = 0; i < myVector->n; i++) { 384 if (myVector->data.F32[i] < min) { 385 min = myVector->data.F32[i]; 390 386 } 391 387 } … … 408 404 NULL 409 405 *****************************************************************************/ 410 int p_psVectorNValues( const psVector *restrict myVector, 411 const psVector *restrict maskVector, 412 unsigned int maskVal, 413 psStats *stats ) 414 { 415 int i = 0; // Loop index variable 416 int numData = 0; // The number of data points 417 float rangeMin = 0.0; // Exclude data below this 418 float rangeMax = 0.0; // Exclude date above this 419 420 if ( stats->options & PS_STAT_USE_RANGE ) { 406 int p_psVectorNValues(const psVector * restrict myVector, 407 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 408 { 409 int i = 0; // Loop index variable 410 int numData = 0; // The number of data points 411 float rangeMin = 0.0; // Exclude data below this 412 float rangeMax = 0.0; // Exclude date above this 413 414 if (stats->options & PS_STAT_USE_RANGE) { 421 415 rangeMin = stats->min; 422 416 rangeMax = stats->max; 423 if ( maskVector != NULL ) { 424 for ( i = 0;i < myVector->n;i++ ) { 425 if ( !( maskVal & maskVector->data.U8[ i ] ) && 426 ( rangeMin <= myVector->data.F32[ i ] ) && 427 ( myVector->data.F32[ i ] <= rangeMax ) ) { 417 if (maskVector != NULL) { 418 for (i = 0; i < myVector->n; i++) { 419 if (!(maskVal & maskVector->data.U8[i]) && 420 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 428 421 numData++; 429 422 } 430 423 } 431 424 } else { 432 for ( i = 0;i < myVector->n;i++ ) { 433 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 434 ( myVector->data.F32[ i ] <= rangeMax ) ) { 425 for (i = 0; i < myVector->n; i++) { 426 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 435 427 numData++; 436 428 } … … 440 432 rangeMin = stats->min; 441 433 rangeMax = stats->max; 442 if ( maskVector != NULL) {443 for ( i = 0;i < myVector->n;i++) {444 if ( !( maskVal & maskVector->data.U8[ i ] )) {434 if (maskVector != NULL) { 435 for (i = 0; i < myVector->n; i++) { 436 if (!(maskVal & maskVector->data.U8[i])) { 445 437 numData++; 446 438 } … … 450 442 } 451 443 } 452 return ( numData ); 453 } 454 455 444 return (numData); 445 } 456 446 457 447 /****************************************************************************** … … 466 456 NULL 467 457 *****************************************************************************/ 468 void p_psVectorSampleMedian( const psVector *restrict myVector, 469 const psVector *restrict maskVector, 470 unsigned int maskVal, 471 psStats *stats ) 472 { 473 psVector * unsortedVector = NULL; // Temporary vector 474 psVector *sortedVector = NULL; // Temporary vector 475 int i = 0; // Loop index variable 476 int count = 0; // # of points in this mean? 477 int nValues = 0; // # of points in vector 478 float rangeMin = 0.0; // Exclude data below this 479 float rangeMax = 0.0; // Exclude date above this 480 458 void p_psVectorSampleMedian(const psVector * restrict myVector, 459 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 460 { 461 psVector *unsortedVector = NULL; // Temporary vector 462 psVector *sortedVector = NULL; // Temporary vector 463 int i = 0; // Loop index variable 464 int count = 0; // # of points in this mean? 465 int nValues = 0; // # of points in vector 466 float rangeMin = 0.0; // Exclude data below this 467 float rangeMax = 0.0; // Exclude date above this 481 468 482 469 // Determine if the number of data points exceed a threshold which will … … 485 472 // regardless of the vector size. 486 473 /* 487 if (myVector->n > stats->sampleLimit) { 488 psAbort(__func__, "Robust Statistic Algorithms have not yet been defined or implemented."); 489 490 // Calculate the robust quartiles. 491 stats2 = psStatsAlloc(PS_STAT_ROBUST_MEDIAN); 492 p_psVectorRobustStats(myVector, maskVector, maskVal, stats2); 493 494 // Store the robust quartiles into the sample quartile members. 495 stats->sampleMedian = stats2->robustMedian; 496 497 // Free temporary data buffers. 498 psFree(stats2); 499 500 // Set the PS_STAT_ROBUST_FOR_SAMPLE bit in the stats structure. 501 stats->options = stats->options | PS_STAT_ROBUST_FOR_SAMPLE; 502 503 return; 504 } 505 */ 474 * if (myVector->n > stats->sampleLimit) { psAbort(__func__, "Robust Statistic Algorithms have not yet 475 * been defined or implemented."); 476 * 477 * // Calculate the robust quartiles. stats2 = psStatsAlloc(PS_STAT_ROBUST_MEDIAN); 478 * p_psVectorRobustStats(myVector, maskVector, maskVal, stats2); 479 * 480 * // Store the robust quartiles into the sample quartile members. stats->sampleMedian = 481 * stats2->robustMedian; 482 * 483 * // Free temporary data buffers. psFree(stats2); 484 * 485 * // Set the PS_STAT_ROBUST_FOR_SAMPLE bit in the stats structure. stats->options = stats->options | 486 * PS_STAT_ROBUST_FOR_SAMPLE; 487 * 488 * return; } */ 506 489 507 490 // Determine how many data points fit inside this min/max range 508 491 // and are not masked, IF the maskVector is not NULL> 509 nValues = p_psVectorNValues( myVector, maskVector, maskVal, stats);492 nValues = p_psVectorNValues(myVector, maskVector, maskVal, stats); 510 493 511 494 // Allocate temporary vectors for the data. 512 unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32);495 unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 513 496 unsortedVector->n = unsortedVector->nalloc; 514 497 515 sortedVector = psVectorAlloc( nValues, PS_TYPE_F32);498 sortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 516 499 sortedVector->n = sortedVector->nalloc; 517 500 518 501 // Determine if we must only use data points within a min/max range. 519 if ( stats->options & PS_STAT_USE_RANGE) {502 if (stats->options & PS_STAT_USE_RANGE) { 520 503 rangeMin = stats->min; 521 504 rangeMax = stats->max; … … 524 507 // into the temporary vectors. 525 508 count = 0; 526 if ( maskVector != NULL ) { 527 for ( i = 0;i < myVector->n;i++ ) { 528 if ( !( maskVal & maskVector->data.U8[ i ] ) && 529 ( rangeMin <= myVector->data.F32[ i ] ) && 530 ( myVector->data.F32[ i ] <= rangeMax ) ) { 531 unsortedVector->data.F32[ count++ ] = maskVector->data.F32[ i ]; 509 if (maskVector != NULL) { 510 for (i = 0; i < myVector->n; i++) { 511 if (!(maskVal & maskVector->data.U8[i]) && 512 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 513 unsortedVector->data.F32[count++] = maskVector->data.F32[i]; 532 514 } 533 515 } 534 516 } else { 535 for ( i = 0;i < myVector->n;i++ ) { 536 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 537 ( myVector->data.F32[ i ] <= rangeMax ) ) { 538 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 517 for (i = 0; i < myVector->n; i++) { 518 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 519 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 539 520 } 540 521 } … … 543 524 // Store all non-masked data points into the temporary vectors. 544 525 count = 0; 545 if ( maskVector != NULL) {546 for ( i = 0;i < myVector->n;i++) {547 if ( !( maskVal & maskVector->data.U8[ i ] )) {548 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i];526 if (maskVector != NULL) { 527 for (i = 0; i < myVector->n; i++) { 528 if (!(maskVal & maskVector->data.U8[i])) { 529 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 549 530 } 550 531 } 551 532 } else { 552 for ( i = 0;i < myVector->n;i++) {553 unsortedVector->data.F32[ i ] = myVector->data.F32[ i];533 for (i = 0; i < myVector->n; i++) { 534 unsortedVector->data.F32[i] = myVector->data.F32[i]; 554 535 } 555 536 } 556 537 } 557 538 // Sort the temporary vectors. 558 psVectorSort( sortedVector, unsortedVector);539 psVectorSort(sortedVector, unsortedVector); 559 540 560 541 // Calculate the median exactly. 561 542 // XXX: Is this the correct action? 562 if ( 0 == ( nValues % 2 )) {563 stats->sampleMedian = 0.5 * ( sortedVector->data.F32[ ( nValues / 2 ) - 1] +564 sortedVector->data.F32[ nValues / 2 ]);543 if (0 == (nValues % 2)) { 544 stats->sampleMedian = 0.5 * (sortedVector->data.F32[(nValues / 2) - 1] + 545 sortedVector->data.F32[nValues / 2]); 565 546 } else { 566 stats->sampleMedian = sortedVector->data.F32[ nValues / 2];547 stats->sampleMedian = sortedVector->data.F32[nValues / 2]; 567 548 } 568 549 569 550 // Free the temporary data structures. 570 psFree( unsortedVector);571 psFree( sortedVector);551 psFree(unsortedVector); 552 psFree(sortedVector); 572 553 } 573 554 … … 584 565 XXX: use a static variable for gaussianCoefs[] and compute them once. 585 566 *****************************************************************************/ 586 psVector *p_psVectorsmoothHistGaussian( psHistogram *robustHistogram, 587 float sigma ) 588 { 589 int i = 0; // Loop index variable 590 int j = 0; // Loop index variable 591 float denom = 0.0; // Temporary variable 592 float expo = 0.0; // Temporary variable 593 float gaussianCoefs[ 1 + ( 2 * GAUSS_WIDTH ) ]; // The Gaussian Coefficients 594 psVector *smooth = psVectorAlloc( robustHistogram->nums->n, PS_TYPE_F32 ); 595 596 for ( i = 0;i < ( 1 + ( 2 * GAUSS_WIDTH ) );i++ ) { 597 if ( fabs( sigma ) >= FLT_EPSILON ) { 567 psVector *p_psVectorsmoothHistGaussian(psHistogram * robustHistogram, float sigma) 568 { 569 int i = 0; // Loop index variable 570 int j = 0; // Loop index variable 571 float denom = 0.0; // Temporary variable 572 float expo = 0.0; // Temporary variable 573 float gaussianCoefs[1 + (2 * GAUSS_WIDTH)]; // The Gaussian Coefficients 574 psVector *smooth = psVectorAlloc(robustHistogram->nums->n, PS_TYPE_F32); 575 576 for (i = 0; i < (1 + (2 * GAUSS_WIDTH)); i++) { 577 if (fabs(sigma) >= FLT_EPSILON) { 598 578 // If sigma does not equal zero, then we use Gaussian smoothing. 599 579 #ifdef DARWIN 600 denom = ( float ) sqrt( 2.0 * M_PI * sigma * sigma);580 denom = (float)sqrt(2.0 * M_PI * sigma * sigma); 601 581 #else 602 582 603 denom = sqrtf( 2.0 * M_PI * sigma * sigma);583 denom = sqrtf(2.0 * M_PI * sigma * sigma); 604 584 #endif 605 585 606 expo = - ( float ) ( ( i - GAUSS_WIDTH ) * ( i - GAUSS_WIDTH ));607 expo /= ( 2.0 * sigma * sigma);608 gaussianCoefs[ i ] = exp( expo / denom);586 expo = -(float)((i - GAUSS_WIDTH) * (i - GAUSS_WIDTH)); 587 expo /= (2.0 * sigma * sigma); 588 gaussianCoefs[i] = exp(expo / denom); 609 589 610 590 // NOTE: Gaussian smoothing just isn't working with low sigma … … 612 592 // all zero, except for the middle coefficient, which is exactly 613 593 // one. Therefore, I'm using boxcar smoothing. 614 gaussianCoefs[ i ] = 1.0 / ( 1.0 + ( 2.0 * ( float ) GAUSS_WIDTH ));615 // printf("gaussianCoefs[%d] is %f\n", i, gaussianCoefs[i]);594 gaussianCoefs[i] = 1.0 / (1.0 + (2.0 * (float)GAUSS_WIDTH)); 595 // printf("gaussianCoefs[%d] is %f\n", i, gaussianCoefs[i]); 616 596 } else { 617 /* If sigma equals zero (all pixels have the same value) 618 * the above code will divide by zero. Therefore, we don't need 619 * to smooth the data. 620 */ 621 for ( i = 0;i < robustHistogram->nums->n;i++ ) { 622 smooth->data.F32[ i ] = ( float ) robustHistogram->nums->data.S32[ i ]; 623 } 624 return ( smooth ); 597 /* If sigma equals zero (all pixels have the same value) the above code will divide by zero. 598 * Therefore, we don't need to smooth the data. */ 599 for (i = 0; i < robustHistogram->nums->n; i++) { 600 smooth->data.F32[i] = (float)robustHistogram->nums->data.S32[i]; 601 } 602 return (smooth); 625 603 } 626 604 } 627 605 628 606 // Perform the actual smoothing. 629 for ( i = 0;i < robustHistogram->nums->n;i++) {630 smooth->data.F32[ i] = 0.0;631 for ( j = -GAUSS_WIDTH;j <= + GAUSS_WIDTH;j++) {632 if ( ( ( j + i ) >= 0 ) && ( ( j + i ) < smooth->n )) {633 smooth->data.F32[ i ] += ( gaussianCoefs[ j + GAUSS_WIDTH] *634 ( float ) robustHistogram->nums->data.S32[ j + i ]);635 } 636 } 637 } 638 return ( smooth);607 for (i = 0; i < robustHistogram->nums->n; i++) { 608 smooth->data.F32[i] = 0.0; 609 for (j = -GAUSS_WIDTH; j <= +GAUSS_WIDTH; j++) { 610 if (((j + i) >= 0) && ((j + i) < smooth->n)) { 611 smooth->data.F32[i] += (gaussianCoefs[j + GAUSS_WIDTH] * 612 (float)robustHistogram->nums->data.S32[j + i]); 613 } 614 } 615 } 616 return (smooth); 639 617 } 640 618 … … 650 628 NULL 651 629 *****************************************************************************/ 652 void p_psVectorSampleQuartiles( const psVector *restrict myVector, 653 const psVector *restrict maskVector, 654 unsigned int maskVal, 655 psStats *stats ) 656 { 657 psVector * unsortedVector = NULL; // Temporary vector 658 psVector *sortedVector = NULL; // Temporary vector 659 int i = 0; // Loop index variable 660 int count = 0; // # of points in this mean? 661 int nValues = 0; // # data points 662 float rangeMin = 0.0; // Exclude data below this 663 float rangeMax = 0.0; // Exclude date above this 630 void p_psVectorSampleQuartiles(const psVector * restrict myVector, 631 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 632 { 633 psVector *unsortedVector = NULL; // Temporary vector 634 psVector *sortedVector = NULL; // Temporary vector 635 int i = 0; // Loop index variable 636 int count = 0; // # of points in this mean? 637 int nValues = 0; // # data points 638 float rangeMin = 0.0; // Exclude data below this 639 float rangeMax = 0.0; // Exclude date above this 664 640 665 641 // Determine how many data points fit inside this min/max range 666 642 // and are not maxed, IF the maskVector is not NULL> 667 nValues = p_psVectorNValues( myVector, maskVector, maskVal, stats);643 nValues = p_psVectorNValues(myVector, maskVector, maskVal, stats); 668 644 669 645 // Allocate temporary vectors for the data. 670 unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32);646 unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 671 647 unsortedVector->n = unsortedVector->nalloc; 672 sortedVector = psVectorAlloc( nValues, PS_TYPE_F32);648 sortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 673 649 sortedVector->n = sortedVector->nalloc; 674 650 675 651 // Determine if we must only use data points within a min/max range. 676 if ( stats->options & PS_STAT_USE_RANGE) {652 if (stats->options & PS_STAT_USE_RANGE) { 677 653 rangeMin = stats->min; 678 654 rangeMax = stats->max; … … 680 656 // into the temporary vectors. 681 657 count = 0; 682 if ( maskVector != NULL ) { 683 for ( i = 0;i < myVector->n;i++ ) { 684 if ( !( maskVal & maskVector->data.U8[ i ] ) && 685 ( rangeMin <= myVector->data.F32[ i ] ) && 686 ( myVector->data.F32[ i ] <= rangeMax ) ) { 687 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 658 if (maskVector != NULL) { 659 for (i = 0; i < myVector->n; i++) { 660 if (!(maskVal & maskVector->data.U8[i]) && 661 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 662 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 688 663 } 689 664 } 690 665 } else { 691 for ( i = 0;i < myVector->n;i++ ) { 692 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 693 ( myVector->data.F32[ i ] <= rangeMax ) ) { 694 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 666 for (i = 0; i < myVector->n; i++) { 667 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 668 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 695 669 } 696 670 } … … 699 673 // Store all non-masked data points into the temporary vectors. 700 674 count = 0; 701 if ( maskVector != NULL) {702 for ( i = 0;i < myVector->n;i++) {703 if ( !( maskVal & maskVector->data.U8[ i ] )) {704 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i];675 if (maskVector != NULL) { 676 for (i = 0; i < myVector->n; i++) { 677 if (!(maskVal & maskVector->data.U8[i])) { 678 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 705 679 } 706 680 } 707 681 } else { 708 for ( i = 0;i < myVector->n;i++) {709 unsortedVector->data.F32[ i ] = myVector->data.F32[ i];682 for (i = 0; i < myVector->n; i++) { 683 unsortedVector->data.F32[i] = myVector->data.F32[i]; 710 684 } 711 685 } … … 713 687 714 688 // Sort the temporary vectors. 715 psVectorSort( sortedVector, unsortedVector);689 psVectorSort(sortedVector, unsortedVector); 716 690 717 691 // Calculate the quartile points exactly. 718 stats->sampleUQ = sortedVector->data.F32[ 3 * ( nValues / 4 )];719 stats->sampleLQ = sortedVector->data.F32[ nValues / 4];692 stats->sampleUQ = sortedVector->data.F32[3 * (nValues / 4)]; 693 stats->sampleLQ = sortedVector->data.F32[nValues / 4]; 720 694 721 695 // Free the temporary data structures. 722 psFree( unsortedVector ); 723 psFree( sortedVector ); 724 } 725 696 psFree(unsortedVector); 697 psFree(sortedVector); 698 } 726 699 727 700 /****************************************************************************** … … 737 710 738 711 *****************************************************************************/ 739 void p_psVectorSampleStdev( const psVector *restrict myVector, 740 const psVector *restrict maskVector, 741 unsigned int maskVal, 742 psStats *stats ) 743 { 744 int i = 0; // Loop index variable 745 int countInt = 0; // # of data points being used 746 float countFloat = 0.0; // # of data points being used 747 float mean = 0.0; // The mean 748 float diff = 0.0; // Used in calculating stdev 749 float sumSquares = 0.0; // temporary variable 750 float sumDiffs = 0.0; // temporary variable 751 float rangeMin = 0.0; // Exclude data below this 752 float rangeMax = 0.0; // Exclude date above this 712 void p_psVectorSampleStdev(const psVector * restrict myVector, 713 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 714 { 715 int i = 0; // Loop index variable 716 int countInt = 0; // # of data points being used 717 float countFloat = 0.0; // # of data points being used 718 float mean = 0.0; // The mean 719 float diff = 0.0; // Used in calculating stdev 720 float sumSquares = 0.0; // temporary variable 721 float sumDiffs = 0.0; // temporary variable 722 float rangeMin = 0.0; // Exclude data below this 723 float rangeMax = 0.0; // Exclude date above this 753 724 754 725 // This procedure requires the mean. If it has not been already 755 726 // calculated, then call p_psVectorSampleMean() 756 if ( 0 != isnan( stats->sampleMean )) {757 p_psVectorSampleMean( myVector, maskVector, maskVal, stats);727 if (0 != isnan(stats->sampleMean)) { 728 p_psVectorSampleMean(myVector, maskVector, maskVal, stats); 758 729 } 759 730 mean = stats->sampleMean; 760 731 761 if ( stats->options & PS_STAT_USE_RANGE ) { 762 if ( maskVector != NULL ) { 763 for ( i = 0;i < myVector->n;i++ ) { 764 if ( !( maskVal & maskVector->data.U8[ i ] ) && 765 ( rangeMin <= myVector->data.F32[ i ] ) && 766 ( myVector->data.F32[ i ] <= rangeMax ) ) { 767 diff = myVector->data.F32[ i ] - mean; 768 sumSquares += ( diff * diff ); 732 if (stats->options & PS_STAT_USE_RANGE) { 733 if (maskVector != NULL) { 734 for (i = 0; i < myVector->n; i++) { 735 if (!(maskVal & maskVector->data.U8[i]) && 736 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 737 diff = myVector->data.F32[i] - mean; 738 sumSquares += (diff * diff); 769 739 sumDiffs += diff; 770 740 countInt++; … … 772 742 } 773 743 } else { 774 for ( i = 0;i < myVector->n;i++ ) { 775 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 776 ( myVector->data.F32[ i ] <= rangeMax ) ) { 777 diff = myVector->data.F32[ i ] - mean; 778 sumSquares += ( diff * diff ); 744 for (i = 0; i < myVector->n; i++) { 745 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 746 diff = myVector->data.F32[i] - mean; 747 sumSquares += (diff * diff); 779 748 sumDiffs += diff; 780 749 countInt++; … … 784 753 } 785 754 } else { 786 if ( maskVector != NULL) {787 for ( i = 0;i < myVector->n;i++) {788 if ( !( maskVal & maskVector->data.U8[ i ] )) {789 diff = myVector->data.F32[ i] - mean;790 sumSquares += ( diff * diff);755 if (maskVector != NULL) { 756 for (i = 0; i < myVector->n; i++) { 757 if (!(maskVal & maskVector->data.U8[i])) { 758 diff = myVector->data.F32[i] - mean; 759 sumSquares += (diff * diff); 791 760 sumDiffs += diff; 792 761 countInt++; … … 794 763 } 795 764 } else { 796 for ( i = 0;i < myVector->n;i++) {797 diff = myVector->data.F32[ i] - mean;798 sumSquares += ( diff * diff);765 for (i = 0; i < myVector->n; i++) { 766 diff = myVector->data.F32[i] - mean; 767 sumSquares += (diff * diff); 799 768 sumDiffs += diff; 800 769 countInt++; … … 803 772 } 804 773 } 805 countFloat = ( float )countInt;774 countFloat = (float)countInt; 806 775 807 776 #ifdef DARWIN 808 777 809 stats->sampleStdev = ( float ) sqrt( ( sumSquares - ( sumDiffs * 810 sumDiffs / countFloat ) ) / ( countFloat - 1 ) ); 778 stats->sampleStdev = (float)sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 811 779 #else 812 780 813 stats->sampleStdev = sqrtf( ( sumSquares - ( sumDiffs * 814 sumDiffs / countFloat ) ) / ( countFloat - 1 ) ); 781 stats->sampleStdev = sqrtf((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 815 782 #endif 816 783 } … … 828 795 NULL 829 796 *****************************************************************************/ 830 void p_psVectorClippedStats( const psVector *restrict myVector, 831 const psVector *restrict maskVector, 832 unsigned int maskVal, 833 psStats *stats ) 834 { 835 int i = 0; // Loop index variable 836 int j = 0; // Loop index variable 837 float clippedMean = 0.0; // self-explanatory 838 float clippedStdev = 0.0; // self-explanatory 839 float oldStanMean = 0.0; // Temporary variable 840 float oldStanStdev = 0.0; // Temporary variable 841 psVector *tmpMask = NULL; // Temporary vector 797 void p_psVectorClippedStats(const psVector * restrict myVector, 798 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 799 { 800 int i = 0; // Loop index variable 801 int j = 0; // Loop index variable 802 float clippedMean = 0.0; // self-explanatory 803 float clippedStdev = 0.0; // self-explanatory 804 float oldStanMean = 0.0; // Temporary variable 805 float oldStanStdev = 0.0; // Temporary variable 806 psVector *tmpMask = NULL; // Temporary vector 842 807 843 808 // Endure that stats->clipIter is within the proper range. 844 if ( !( ( CLIPPED_NUM_ITER_LB <= stats->clipIter ) && 845 ( stats->clipIter <= CLIPPED_NUM_ITER_UB ) ) ) { 846 psAbort( __func__, "Unallowed value for clipIter (%d).\n", 847 stats->clipIter ); 848 } 849 809 if (!((CLIPPED_NUM_ITER_LB <= stats->clipIter) && (stats->clipIter <= CLIPPED_NUM_ITER_UB))) { 810 psAbort(__func__, "Unallowed value for clipIter (%d).\n", stats->clipIter); 811 } 850 812 // Endure that stats->clipSigma is within the proper range. 851 if ( !( ( CLIPPED_SIGMA_LB <= stats->clipSigma ) && 852 ( stats->clipSigma <= CLIPPED_SIGMA_UB ) ) ) { 853 psAbort( __func__, "Unallowed value for clipSigma (%f).\n", 854 stats->clipSigma ); 855 } 856 813 if (!((CLIPPED_SIGMA_LB <= stats->clipSigma) && (stats->clipSigma <= CLIPPED_SIGMA_UB))) { 814 psAbort(__func__, "Unallowed value for clipSigma (%f).\n", stats->clipSigma); 815 } 857 816 // We allocate a temporary mask vector since during the iterative 858 817 // steps that follow, we will be masking off additional data points. 859 818 // However, we do no want to modify the original mask vector. 860 tmpMask = psVectorAlloc( myVector->n, PS_TYPE_U8);819 tmpMask = psVectorAlloc(myVector->n, PS_TYPE_U8); 861 820 tmpMask->n = myVector->n; 862 821 863 822 // If we were called with a mask vector, then initialize the temporary 864 823 // mask vector with those values. 865 if ( maskVector != NULL ) { 866 for ( i = 0;i < tmpMask->n;i++ ) { 867 tmpMask->data.U8[ i ] = maskVector->data.U8[ i ]; 868 } 869 } 870 824 if (maskVector != NULL) { 825 for (i = 0; i < tmpMask->n; i++) { 826 tmpMask->data.U8[i] = maskVector->data.U8[i]; 827 } 828 } 871 829 // 1. Compute the sample median. 872 830 // NOTE: This seems odd. Verify with IfA that we want to calculate the 873 831 // median here, not the mean. 874 p_psVectorSampleMedian( myVector, maskVector, maskVal, stats);832 p_psVectorSampleMedian(myVector, maskVector, maskVal, stats); 875 833 876 834 // 2. Compute the sample standard deviation. 877 p_psVectorSampleStdev( myVector, maskVector, maskVal, stats);835 p_psVectorSampleStdev(myVector, maskVector, maskVal, stats); 878 836 879 837 // 3. Use the sample median as the first estimator of the mean X. … … 889 847 890 848 // 5. Repeat N times: 891 for ( i = 0;i < stats->clipIter;i++) {892 for ( j = 0;j < myVector->n;j++) {849 for (i = 0; i < stats->clipIter; i++) { 850 for (j = 0; j < myVector->n; j++) { 893 851 // a) Exclude all values x_i for which |x_i - x| > K * stdev 894 if ( fabs( myVector->data.F32[ j ] - clippedMean ) > 895 ( stats->clipSigma * clippedStdev ) ) { 896 tmpMask->data.U8[ i ] = 0xff; 852 if (fabs(myVector->data.F32[j] - clippedMean) > (stats->clipSigma * clippedStdev)) { 853 tmpMask->data.U8[i] = 0xff; 897 854 } 898 855 // b) compute new mean and stdev 899 p_psVectorSampleMedian( myVector, tmpMask, maskVal, stats);900 p_psVectorSampleStdev( myVector, tmpMask, maskVal, stats);856 p_psVectorSampleMedian(myVector, tmpMask, maskVal, stats); 857 p_psVectorSampleStdev(myVector, tmpMask, maskVal, stats); 901 858 902 859 // c) Use the new mean for x … … 912 869 913 870 // 7. The last calcuated value of x is the cliped mean. 914 if ( stats->options & PS_STAT_CLIPPED_MEAN) {871 if (stats->options & PS_STAT_CLIPPED_MEAN) { 915 872 stats->clippedMean = clippedMean; 916 873 } 917 918 874 // 8. The last calcuated value of stdev is the cliped stdev. 919 if ( stats->options & PS_STAT_CLIPPED_STDEV) {875 if (stats->options & PS_STAT_CLIPPED_STDEV) { 920 876 stats->clippedStdev = clippedStdev; 921 877 } 922 878 923 psFree( tmpMask);879 psFree(tmpMask); 924 880 } 925 881 … … 928 884 elements of a vector to a range between 0.0 and 1.0. 929 885 *****************************************************************************/ 930 void p_psNormalizeVector( psVector *myData)931 { 932 float min = ( float )HUGE;933 float max = ( float ) -HUGE;886 void p_psNormalizeVector(psVector * myData) 887 { 888 float min = (float)HUGE; 889 float max = (float)-HUGE; 934 890 float range = 0.0; 935 891 int i = 0; 936 892 937 for ( i = 0;i < myData->n;i++) {938 if ( myData->data.F32[ i ] < min) {939 min = myData->data.F32[ i];940 } 941 if ( myData->data.F32[ i ] > max) {942 max = myData->data.F32[ i];893 for (i = 0; i < myData->n; i++) { 894 if (myData->data.F32[i] < min) { 895 min = myData->data.F32[i]; 896 } 897 if (myData->data.F32[i] > max) { 898 max = myData->data.F32[i]; 943 899 } 944 900 } 945 901 946 902 range = max - min; 947 for ( i = 0;i < myData->n;i++ ) { 948 myData->data.F32[ i ] = ( myData->data.F32[ i ] - min ) / range; 949 } 950 } 951 903 for (i = 0; i < myData->n; i++) { 904 myData->data.F32[i] = (myData->data.F32[i] - min) / range; 905 } 906 } 952 907 953 908 /***************************************************************************** … … 956 911 specified data point. 957 912 *****************************************************************************/ 958 float p_psGaussian( const psVector *restrict myData,959 const psVector *restrict myParams ) 960 { 961 float x = myData->data.F32[ 0];962 float mean = myParams->data.F32[ 0];963 float stdev = myParams->data.F32[ 1 ];964 float tmp = exp( -( ( x - mean ) * ( x - mean ) ) / ( 2.0 * stdev * stdev ) ); 965 tmp /= ( ( float ) sqrt( 2.0 * M_PI * ( stdev * stdev ) ));966 967 // printf("p_psGaussian((%.2f), %.2f, %.2f) is %.2f\n", x, mean, stdev, tmp);968 return ( tmp);913 float p_psGaussian(const psVector * restrict myData, const psVector * restrict myParams) 914 { 915 float x = myData->data.F32[0]; 916 float mean = myParams->data.F32[0]; 917 float stdev = myParams->data.F32[1]; 918 float tmp = exp(-((x - mean) * (x - mean)) / (2.0 * stdev * stdev)); 919 920 tmp /= ((float)sqrt(2.0 * M_PI * (stdev * stdev))); 921 922 // printf("p_psGaussian((%.2f), %.2f, %.2f) is %.2f\n", x, mean, stdev, tmp); 923 return (tmp); 969 924 } 970 925 … … 973 928 calculates the specified partial derivative of the above Gaussian function. 974 929 *****************************************************************************/ 975 float p_psGaussianDeriv( const psVector *restrict myData, 976 const psVector *restrict myParams, 977 int whichParam ) 978 { 979 float x = myData->data.F32[ 0 ]; 980 float mean = myParams->data.F32[ 0 ]; 981 float stdev = myParams->data.F32[ 1 ]; 930 float p_psGaussianDeriv(const psVector * restrict myData, const psVector * restrict myParams, int whichParam) 931 { 932 float x = myData->data.F32[0]; 933 float mean = myParams->data.F32[0]; 934 float stdev = myParams->data.F32[1]; 982 935 float tmp = 0.0; 983 936 984 if ( whichParam == 0) {937 if (whichParam == 0) { 985 938 // Return the derivative w.r.t. the mean. 986 tmp = ( x - mean ) * p_psGaussian( myData, myParams ); 987 tmp /= ( stdev * stdev ); 988 } else 989 if ( whichParam == 1 ) { 990 // Return the derivative w.r.t. the stdev. 991 tmp = ( x - mean ) * ( x - mean ) * p_psGaussian( myData, myParams ); 992 tmp /= ( stdev * stdev * stdev ); 993 } 994 printf( "p_psGaussianDeriv((%.2f), %.2f, %.2f, (%d)) is %.2f\n", x, mean, stdev, whichParam, tmp ); 995 996 return ( tmp ); 997 } 998 939 tmp = (x - mean) * p_psGaussian(myData, myParams); 940 tmp /= (stdev * stdev); 941 } else if (whichParam == 1) { 942 // Return the derivative w.r.t. the stdev. 943 tmp = (x - mean) * (x - mean) * p_psGaussian(myData, myParams); 944 tmp /= (stdev * stdev * stdev); 945 } 946 printf("p_psGaussianDeriv((%.2f), %.2f, %.2f, (%d)) is %.2f\n", x, mean, stdev, whichParam, tmp); 947 948 return (tmp); 949 } 999 950 1000 951 /***************************************************************************** … … 1003 954 specified data point. 1004 955 *****************************************************************************/ 1005 float p_psQuadratic( const psVector *restrict myParams, 1006 const psVector *restrict myCoords ) 1007 { 1008 float x = myCoords->data.F32[ 0 ]; 1009 float A = myParams->data.F32[ 0 ]; 1010 float B = myParams->data.F32[ 1 ]; 1011 float C = myParams->data.F32[ 2 ]; 956 float p_psQuadratic(const psVector * restrict myParams, const psVector * restrict myCoords) 957 { 958 float x = myCoords->data.F32[0]; 959 float A = myParams->data.F32[0]; 960 float B = myParams->data.F32[1]; 961 float C = myParams->data.F32[2]; 1012 962 float tmp = 0.0; 1013 963 1014 tmp = ( A * x * x ) + ( B * x) + C;1015 return ( tmp);964 tmp = (A * x * x) + (B * x) + C; 965 return (tmp); 1016 966 } 1017 967 … … 1020 970 calculates the specified partial derivative of the above quadratic function. 1021 971 *****************************************************************************/ 1022 float p_psQuadraticDeriv( const psVector *restrict myParams, 1023 const psVector *restrict myCoords, 1024 int whichParamDeriv ) 1025 { 1026 float x = myCoords->data.F32[ 0 ]; 972 float p_psQuadraticDeriv(const psVector * restrict myParams, 973 const psVector * restrict myCoords, int whichParamDeriv) 974 { 975 float x = myCoords->data.F32[0]; 1027 976 float tmp = 0.0; 1028 977 1029 if ( whichParamDeriv == 0) {978 if (whichParamDeriv == 0) { 1030 979 tmp = x * x; 1031 } else 1032 if ( whichParamDeriv == 1 ) { 1033 tmp = x; 1034 } else 1035 if ( whichParamDeriv == 2 ) { 1036 tmp = 1.0; 1037 } 1038 1039 return ( tmp ); 980 } else if (whichParamDeriv == 1) { 981 tmp = x; 982 } else if (whichParamDeriv == 2) { 983 tmp = 1.0; 984 } 985 986 return (tmp); 1040 987 } 1041 988 … … 1049 996 decreasing within that range. 1050 997 *****************************************************************************/ 1051 float p_ps1DPolyMedian( psPolynomial1D *myPoly, 1052 float rangeLow, 1053 float rangeHigh, 1054 float getThisValue ) 998 float p_ps1DPolyMedian(psPolynomial1D * myPoly, float rangeLow, float rangeHigh, float getThisValue) 1055 999 { 1056 1000 int numIterations = 0; … … 1059 1003 float f = 0.0; 1060 1004 1061 // printf("p_ps1DPolyMedian(%f, %f, %f) \n", rangeLow, rangeHigh, getThisValue);1062 1063 while ( numIterations < MAX_ITERATIONS) {1064 midpoint = ( rangeHigh + rangeLow) / 2.0;1065 if ( fabs( midpoint - oldMidpoint ) <= FLT_EPSILON) {1066 return ( midpoint);1005 // printf("p_ps1DPolyMedian(%f, %f, %f) \n", rangeLow, rangeHigh, getThisValue); 1006 1007 while (numIterations < MAX_ITERATIONS) { 1008 midpoint = (rangeHigh + rangeLow) / 2.0; 1009 if (fabs(midpoint - oldMidpoint) <= FLT_EPSILON) { 1010 return (midpoint); 1067 1011 } 1068 1012 oldMidpoint = midpoint; 1069 1013 1070 f = psPolynomial1DEval( midpoint, myPoly);1071 // printf("p_ps1DPolyMedian() iteration %d. f(%f) is %f\n", numIterations, midpoint, f);1072 if ( fabs( f - getThisValue ) <= FLT_EPSILON) {1073 return ( midpoint);1074 } 1075 1076 if ( f > getThisValue) {1014 f = psPolynomial1DEval(midpoint, myPoly); 1015 // printf("p_ps1DPolyMedian() iteration %d. f(%f) is %f\n", numIterations, midpoint, f); 1016 if (fabs(f - getThisValue) <= FLT_EPSILON) { 1017 return (midpoint); 1018 } 1019 1020 if (f > getThisValue) { 1077 1021 rangeHigh = midpoint; 1078 1022 } else { … … 1081 1025 numIterations++; 1082 1026 } 1083 return ( midpoint);1027 return (midpoint); 1084 1028 } 1085 1029 … … 1092 1036 XXX: This function is currently not being used. 1093 1037 *****************************************************************************/ 1094 float p_psFitQuadratic( psHistogram *histogram, 1095 psVector *cumulativeSums, 1096 int binNum, 1097 float fitFloat ) 1098 { 1099 psVector * x = psVectorAlloc( 3, PS_TYPE_F64 ); 1100 psVector *y = psVectorAlloc( 3, PS_TYPE_F64 ); 1101 psVector *yErr = psVectorAlloc( 3, PS_TYPE_F64 ); 1102 psPolynomial1D *myPoly = psPolynomial1DAlloc( 2 ); 1103 1104 if ( ( binNum > 0 ) && 1105 ( binNum < ( histogram->nums->n + 1 ) ) ) { 1106 x->data.F64[ 0 ] = ( double ) 0.5 * 1107 ( histogram->bounds->data.F32[ binNum - 1 ] + 1108 histogram->bounds->data.F32[ binNum ] ); 1109 x->data.F64[ 1 ] = ( double ) 0.5 * 1110 ( histogram->bounds->data.F32[ binNum ] + 1111 histogram->bounds->data.F32[ binNum + 1 ] ); 1112 x->data.F64[ 2 ] = ( double ) 0.5 * 1113 ( histogram->bounds->data.F32[ binNum + 1 ] + 1114 histogram->bounds->data.F32[ binNum + 2 ] ); 1115 1116 y->data.F64[ 0 ] = cumulativeSums->data.F32[ binNum - 1 ]; 1117 y->data.F64[ 1 ] = cumulativeSums->data.F32[ binNum ]; 1118 y->data.F64[ 2 ] = cumulativeSums->data.F32[ binNum + 1 ]; 1119 1120 if ( !( ( y->data.F64[ 0 ] <= fitFloat ) && 1121 ( fitFloat <= y->data.F64[ 2 ] ) ) ) { 1122 psAbort( __func__, "p_psVectorRobustStats(0): midpoint not within y-range\n" ); 1123 } 1124 1125 yErr->data.F64[ 0 ] = 1.0; 1126 yErr->data.F64[ 1 ] = 1.0; 1127 yErr->data.F64[ 2 ] = 1.0; 1128 1129 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1130 return ( p_ps1DPolyMedian( myPoly, x->data.F64[ 0 ], x->data.F64[ 2 ], 1131 fitFloat ) ); 1038 float p_psFitQuadratic(psHistogram * histogram, psVector * cumulativeSums, int binNum, float fitFloat) 1039 { 1040 psVector *x = psVectorAlloc(3, PS_TYPE_F64); 1041 psVector *y = psVectorAlloc(3, PS_TYPE_F64); 1042 psVector *yErr = psVectorAlloc(3, PS_TYPE_F64); 1043 psPolynomial1D *myPoly = psPolynomial1DAlloc(2); 1044 1045 if ((binNum > 0) && (binNum < (histogram->nums->n + 1))) { 1046 x->data.F64[0] = (double)0.5 * 1047 (histogram->bounds->data.F32[binNum - 1] + histogram->bounds->data.F32[binNum]); 1048 x->data.F64[1] = (double)0.5 * 1049 (histogram->bounds->data.F32[binNum] + histogram->bounds->data.F32[binNum + 1]); 1050 x->data.F64[2] = (double)0.5 * 1051 (histogram->bounds->data.F32[binNum + 1] + histogram->bounds->data.F32[binNum + 2]); 1052 1053 y->data.F64[0] = cumulativeSums->data.F32[binNum - 1]; 1054 y->data.F64[1] = cumulativeSums->data.F32[binNum]; 1055 y->data.F64[2] = cumulativeSums->data.F32[binNum + 1]; 1056 1057 if (!((y->data.F64[0] <= fitFloat) && (fitFloat <= y->data.F64[2]))) { 1058 psAbort(__func__, "p_psVectorRobustStats(0): midpoint not within y-range\n"); 1059 } 1060 1061 yErr->data.F64[0] = 1.0; 1062 yErr->data.F64[1] = 1.0; 1063 yErr->data.F64[2] = 1.0; 1064 1065 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1066 return (p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], fitFloat)); 1132 1067 } else { 1133 return ( 0.5 * ( histogram->bounds->data.F32[ binNum + 1 ] + 1134 histogram->bounds->data.F32[ binNum ] ) ); 1135 } 1136 1137 psFree( x ); 1138 psFree( y ); 1139 psFree( yErr ); 1140 psFree( myPoly ); 1141 return ( 0.0 ); 1068 return (0.5 * (histogram->bounds->data.F32[binNum + 1] + histogram->bounds->data.F32[binNum])); 1069 } 1070 1071 psFree(x); 1072 psFree(y); 1073 psFree(yErr); 1074 psFree(myPoly); 1075 return (0.0); 1142 1076 } 1143 1077 … … 1166 1100 NULL 1167 1101 *****************************************************************************/ 1168 void p_psVectorRobustStats( const psVector *restrict myVector, 1169 const psVector *restrict maskVector, 1170 unsigned int maskVal, 1171 psStats *stats ) 1172 { 1173 psHistogram * robustHistogram = NULL; 1102 void p_psVectorRobustStats(const psVector * restrict myVector, 1103 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 1104 { 1105 psHistogram *robustHistogram = NULL; 1174 1106 psVector *robustHistogramVector = NULL; 1175 float binSize = 0.0; // Size of the histogram bins1176 int LQBinNum = -1; // Bin num for lower quartile1177 int UQBinNum = -1; // Bin num for upper quartile1178 int i = 0; // Loop index variable1107 float binSize = 0.0; // Size of the histogram bins 1108 int LQBinNum = -1; // Bin num for lower quartile 1109 int UQBinNum = -1; // Bin num for upper quartile 1110 int i = 0; // Loop index variable 1179 1111 int maxBinNum = 0; 1180 1112 float maxBinCount = 0.0; 1181 1113 float dL = 0.0; 1182 1114 int numBins = 0; 1183 psStats *tmpStats = psStatsAlloc( PS_STAT_CLIPPED_STDEV | PS_STAT_CLIPPED_MEAN ); 1184 // psImage *domain; 1185 // psVector *errors; 1186 // psVector *data; 1187 // psVector *initialGuess; 1188 // psVector *theParams; 1189 // float chiSq=0.0; 1190 // float max = -HUGE; 1191 // float max_pos; 1115 psStats *tmpStats = psStatsAlloc(PS_STAT_CLIPPED_STDEV | PS_STAT_CLIPPED_MEAN); 1116 1117 // psImage *domain; 1118 // psVector *errors; 1119 // psVector *data; 1120 // psVector *initialGuess; 1121 // psVector *theParams; 1122 // float chiSq=0.0; 1123 // float max = -HUGE; 1124 // float max_pos; 1192 1125 float myMean = 0.0; 1193 1126 float myStdev = 0.0; … … 1196 1129 float sumSquares = 0.0; 1197 1130 float sumDiffs = 0.0; 1198 psVector *x = psVectorAlloc( 3, PS_TYPE_F64);1199 psVector *y = psVectorAlloc( 3, PS_TYPE_F64);1200 psVector *yErr = psVectorAlloc( 3, PS_TYPE_F64);1201 psPolynomial1D *myPoly = psPolynomial1DAlloc( 2);1131 psVector *x = psVectorAlloc(3, PS_TYPE_F64); 1132 psVector *y = psVectorAlloc(3, PS_TYPE_F64); 1133 psVector *yErr = psVectorAlloc(3, PS_TYPE_F64); 1134 psPolynomial1D *myPoly = psPolynomial1DAlloc(2); 1202 1135 psVector *cumulativeRobustSumsFullRange = NULL; 1203 1136 psVector *cumulativeRobustSumsDlRange = NULL; … … 1210 1143 // by computing the clipped standard deviation of the vector, and dividing 1211 1144 // that by 10.0; 1212 p_psVectorClippedStats( myVector, maskVector, maskVal, tmpStats);1145 p_psVectorClippedStats(myVector, maskVector, maskVal, tmpStats); 1213 1146 binSize = tmpStats->clippedStdev / 10.0f; 1214 1147 1215 1148 // If stats->clippedStdev == 0.0, then all data elements have the same 1216 1149 // value. Therefore, we can set the appropiate results and return. 1217 if ( fabs( binSize ) <= FLT_EPSILON) {1218 if ( stats->options & PS_STAT_ROBUST_MEAN) {1150 if (fabs(binSize) <= FLT_EPSILON) { 1151 if (stats->options & PS_STAT_ROBUST_MEAN) { 1219 1152 stats->robustMean = stats->clippedMean; 1220 1153 } 1221 if ( stats->options & PS_STAT_ROBUST_MEDIAN) {1154 if (stats->options & PS_STAT_ROBUST_MEDIAN) { 1222 1155 stats->robustMedian = stats->clippedMean; 1223 1156 } 1224 if ( stats->options & PS_STAT_ROBUST_MODE) {1157 if (stats->options & PS_STAT_ROBUST_MODE) { 1225 1158 stats->robustMode = stats->clippedMean; 1226 1159 } 1227 if ( stats->options & PS_STAT_ROBUST_STDEV) {1160 if (stats->options & PS_STAT_ROBUST_STDEV) { 1228 1161 stats->robustStdev = 0.0; 1229 1162 } 1230 if ( stats->options & PS_STAT_ROBUST_QUARTILE) {1163 if (stats->options & PS_STAT_ROBUST_QUARTILE) { 1231 1164 stats->robustUQ = stats->clippedMean; 1232 1165 stats->robustLQ = stats->clippedMean; … … 1235 1168 stats->robustNfit = 0.0; 1236 1169 stats->robustN50 = 0.0; 1237 psFree( tmpStats ); 1238 return ; 1239 } 1240 1170 psFree(tmpStats); 1171 return; 1172 } 1241 1173 // Determine minimum and maximum values in the data vector. 1242 if ( isnan( stats->min ) ) { 1243 p_psVectorMin( myVector, maskVector, maskVal, stats ); 1244 } 1245 if ( isnan( stats->max ) ) { 1246 p_psVectorMax( myVector, maskVector, maskVal, stats ); 1247 } 1248 1174 if (isnan(stats->min)) { 1175 p_psVectorMin(myVector, maskVector, maskVal, stats); 1176 } 1177 if (isnan(stats->max)) { 1178 p_psVectorMax(myVector, maskVector, maskVal, stats); 1179 } 1249 1180 // Create the histogram structure. NOTE: we can not specify the bin size 1250 1181 // precisely since the argument to psHistogramAlloc() is the number of 1251 1182 // bins, not the binSize. Also, if we get here, we know that 1252 1183 // binSize != 0.0. 1253 numBins = ( int ) ( ( stats->max - stats->min ) / binSize ); 1254 robustHistogram = psHistogramAlloc( stats->min, 1255 stats->max, 1256 numBins ); 1184 numBins = (int)((stats->max - stats->min) / binSize); 1185 robustHistogram = psHistogramAlloc(stats->min, stats->max, numBins); 1257 1186 1258 1187 // Populate the histogram array. 1259 psVectorHistogram( robustHistogram, myVector, maskVector, maskVal);1188 psVectorHistogram(robustHistogram, myVector, maskVector, maskVal); 1260 1189 1261 1190 // Smooth the histogram. 1262 1191 // XXX: is that the right stdev? 1263 robustHistogramVector = p_psVectorsmoothHistGaussian( robustHistogram, 1264 tmpStats->clippedStdev / 4.0f ); 1192 robustHistogramVector = p_psVectorsmoothHistGaussian(robustHistogram, tmpStats->clippedStdev / 4.0f); 1265 1193 1266 1194 // The following was necessary to fit a gaussian to the data, since … … 1274 1202 // index position i is equal to the sum of bins 0:i. This will be used 1275 1203 // now and later in determining the lower/upper quartiles. 1276 cumulativeRobustSumsFullRange = psVectorAlloc( robustHistogramVector->n, PS_TYPE_F32 ); 1277 cumulativeRobustSumsFullRange->data.F32[ 0 ] = robustHistogramVector->data.F32[ 0 ]; 1278 for ( i = 1;i < robustHistogramVector->n;i++ ) { 1279 cumulativeRobustSumsFullRange->data.F32[ i ] = 1280 cumulativeRobustSumsFullRange->data.F32[ i - 1 ] + 1281 robustHistogramVector->data.F32[ i ]; 1282 } 1283 sumRobust = cumulativeRobustSumsFullRange->data.F32[ robustHistogramVector->n - 1 ]; 1204 cumulativeRobustSumsFullRange = psVectorAlloc(robustHistogramVector->n, PS_TYPE_F32); 1205 cumulativeRobustSumsFullRange->data.F32[0] = robustHistogramVector->data.F32[0]; 1206 for (i = 1; i < robustHistogramVector->n; i++) { 1207 cumulativeRobustSumsFullRange->data.F32[i] = 1208 cumulativeRobustSumsFullRange->data.F32[i - 1] + robustHistogramVector->data.F32[i]; 1209 } 1210 sumRobust = cumulativeRobustSumsFullRange->data.F32[robustHistogramVector->n - 1]; 1284 1211 1285 1212 // Determine the bin number containing the lower quartile point. 1286 1213 LQBinNum = -1; 1287 for ( i = 0;i < cumulativeRobustSumsFullRange->n;i++) {1288 if ( cumulativeRobustSumsFullRange->data.F32[ i ] >= ( sumRobust / 4.0 )) {1214 for (i = 0; i < cumulativeRobustSumsFullRange->n; i++) { 1215 if (cumulativeRobustSumsFullRange->data.F32[i] >= (sumRobust / 4.0)) { 1289 1216 LQBinNum = i; 1290 1217 break; … … 1294 1221 // Determine the bin number containing the upper quartile point. 1295 1222 UQBinNum = -1; 1296 for ( i = cumulativeRobustSumsFullRange->n - 1;i >= 0;i--) {1297 if ( cumulativeRobustSumsFullRange->data.F32[ i ] <= ( 3.0 * sumRobust / 4.0 )) {1223 for (i = cumulativeRobustSumsFullRange->n - 1; i >= 0; i--) { 1224 if (cumulativeRobustSumsFullRange->data.F32[i] <= (3.0 * sumRobust / 4.0)) { 1298 1225 UQBinNum = i; 1299 1226 break; … … 1301 1228 } 1302 1229 1303 if ( ( LQBinNum == -1 ) ||1304 ( UQBinNum == -1 ) ) {1305 psAbort( __func__, "Could not determine the robust lower/upper quartiles." );1306 } 1230 if ((LQBinNum == -1) || (UQBinNum == -1)) { 1231 psAbort(__func__, "Could not determine the robust lower/upper quartiles."); 1232 } 1233 1307 1234 /************************************************************************** 1308 1235 Determine the mode in the range LQ:UQ. … … 1310 1237 // Determine the bin with the peak value in the range LQ to UQ. 1311 1238 maxBinNum = LQBinNum; 1312 maxBinCount = robustHistogramVector->data.F32[ LQBinNum];1313 sumN50 = ( float ) robustHistogram->nums->data.S32[ LQBinNum];1314 for ( i = LQBinNum + 1;i <= UQBinNum;i++) {1315 if ( robustHistogramVector->data.F32[ i ] > maxBinCount) {1239 maxBinCount = robustHistogramVector->data.F32[LQBinNum]; 1240 sumN50 = (float)robustHistogram->nums->data.S32[LQBinNum]; 1241 for (i = LQBinNum + 1; i <= UQBinNum; i++) { 1242 if (robustHistogramVector->data.F32[i] > maxBinCount) { 1316 1243 maxBinNum = i; 1317 maxBinCount = robustHistogramVector->data.F32[ i];1318 } 1319 sumN50 += ( float ) robustHistogram->nums->data.S32[ i];1244 maxBinCount = robustHistogramVector->data.F32[i]; 1245 } 1246 sumN50 += (float)robustHistogram->nums->data.S32[i]; 1320 1247 } 1321 1248 1322 1249 // XXX: is dL defined as the value at the LQ/UQ, or the bin number? 1323 dL = ( UQBinNum - LQBinNum) / 4;1324 1325 printf( "(LQBinNum, UQBinNum, maxBinNum) is (%d, %d, %d)\n", LQBinNum, UQBinNum, maxBinNum);1250 dL = (UQBinNum - LQBinNum) / 4; 1251 1252 printf("(LQBinNum, UQBinNum, maxBinNum) is (%d, %d, %d)\n", LQBinNum, UQBinNum, maxBinNum); 1326 1253 1327 1254 /************************************************************************** 1328 1255 Determine the mean/stdev for the bins in the range mode-dL to mode+dL 1329 1256 **************************************************************************/ 1330 cumulativeRobustSumsDlRange = psVectorAlloc( robustHistogramVector->n, PS_TYPE_F32);1331 for ( i = 0;i < robustHistogramVector->n;i++) {1332 cumulativeRobustSumsDlRange->data.F32[ i] = 0.0;1257 cumulativeRobustSumsDlRange = psVectorAlloc(robustHistogramVector->n, PS_TYPE_F32); 1258 for (i = 0; i < robustHistogramVector->n; i++) { 1259 cumulativeRobustSumsDlRange->data.F32[i] = 0.0; 1333 1260 } 1334 1261 sumNfit = 0.0; 1335 1262 cumulativeMedian = 0.0; 1336 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++ ) { 1337 if ( ( 0 <= i ) && ( i < robustHistogramVector->n ) ) { 1338 cumulativeRobustSumsDlRange->data.F32[ i ] = 1339 cumulativeRobustSumsDlRange->data.F32[ i - 1 ] + 1340 robustHistogramVector->data.F32[ i ]; 1341 cumulativeMedian += robustHistogramVector->data.F32[ i ]; 1342 sumNfit += ( float ) robustHistogram->nums->data.S32[ i ]; 1263 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1264 if ((0 <= i) && (i < robustHistogramVector->n)) { 1265 cumulativeRobustSumsDlRange->data.F32[i] = 1266 cumulativeRobustSumsDlRange->data.F32[i - 1] + robustHistogramVector->data.F32[i]; 1267 cumulativeMedian += robustHistogramVector->data.F32[i]; 1268 sumNfit += (float)robustHistogram->nums->data.S32[i]; 1343 1269 } 1344 1270 } … … 1348 1274 // that bin (this is a non-exact approximation). 1349 1275 myMean = 0.0; 1350 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++ ) { 1351 if ( ( 0 <= i ) && ( i < robustHistogramVector->n ) ) { 1352 myMean += ( robustHistogramVector->data.F32[ i ] ) * 0.5 * 1353 ( robustHistogram->bounds->data.F32[ i + 1 ] + 1354 robustHistogram->bounds->data.F32[ i ] ); 1355 countFloat += robustHistogramVector->data.F32[ i ]; 1276 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1277 if ((0 <= i) && (i < robustHistogramVector->n)) { 1278 myMean += (robustHistogramVector->data.F32[i]) * 0.5 * 1279 (robustHistogram->bounds->data.F32[i + 1] + robustHistogram->bounds->data.F32[i]); 1280 countFloat += robustHistogramVector->data.F32[i]; 1356 1281 } 1357 1282 } … … 1361 1286 // mode-dL to mode+dL. We use the midpoint of each bin as the mean for 1362 1287 // that bin. 1363 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++) {1364 if ( ( 0 <= i ) && ( i < robustHistogramVector->n )) {1365 diff = ( 0.5 * ( robustHistogram->bounds->data.F32[ i + 1] +1366 robustHistogram->bounds->data.F32[ i ] )) - myMean;1367 sumSquares += diff * diff * robustHistogramVector->data.F32[ i];1368 sumDiffs += diff * robustHistogramVector->data.F32[ i];1369 } 1370 } 1371 myStdev = sqrt( ( sumSquares - ( sumDiffs * sumDiffs / countFloat ) ) / ( countFloat - 1 ));1288 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1289 if ((0 <= i) && (i < robustHistogramVector->n)) { 1290 diff = (0.5 * (robustHistogram->bounds->data.F32[i + 1] + 1291 robustHistogram->bounds->data.F32[i])) - myMean; 1292 sumSquares += diff * diff * robustHistogramVector->data.F32[i]; 1293 sumDiffs += diff * robustHistogramVector->data.F32[i]; 1294 } 1295 } 1296 myStdev = sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 1372 1297 1373 1298 /************************************************************************** 1374 1299 Set the appropriate members in the output stats struct. 1375 1300 **************************************************************************/ 1376 if ( stats->options & PS_STAT_ROBUST_MEAN) {1301 if (stats->options & PS_STAT_ROBUST_MEAN) { 1377 1302 stats->robustMean = myMean; 1378 1303 } 1379 1304 1380 if ( stats->options & PS_STAT_ROBUST_MODE) {1305 if (stats->options & PS_STAT_ROBUST_MODE) { 1381 1306 stats->robustMode = 0.5 * 1382 ( robustHistogram->bounds->data.F32[ maxBinNum ] + 1383 robustHistogram->bounds->data.F32[ maxBinNum + 1 ] ); 1384 } 1385 1386 if ( stats->options & PS_STAT_ROBUST_STDEV ) { 1307 (robustHistogram->bounds->data.F32[maxBinNum] + robustHistogram->bounds->data.F32[maxBinNum + 1]); 1308 } 1309 1310 if (stats->options & PS_STAT_ROBUST_STDEV) { 1387 1311 stats->robustStdev = myStdev; 1388 1312 } 1389 1390 1313 // To determine the median (and later, the lower/upper quartile), we fit 1391 1314 // a quadratic to the three bins surrounding the bin containing the median. … … 1394 1317 // this bin. We then solve the quadratic for 1395 1318 1396 if ( stats->options & PS_STAT_ROBUST_MEDIAN) {1397 if ( ( maxBinNum > 0 ) && ( maxBinNum < ( robustHistogram->nums->n - 1 ) )) {1398 x->data.F64[ 0 ] = ( double )0.5 *1399 ( robustHistogram->bounds->data.F32[ maxBinNum - 1] +1400 robustHistogram->bounds->data.F32[ maxBinNum ]);1401 x->data.F64[ 1 ] = ( double )0.5 *1402 ( robustHistogram->bounds->data.F32[ maxBinNum] +1403 robustHistogram->bounds->data.F32[ maxBinNum + 1 ]);1404 x->data.F64[ 2 ] = ( double )0.5 *1405 ( robustHistogram->bounds->data.F32[ maxBinNum + 1] +1406 robustHistogram->bounds->data.F32[ maxBinNum + 2 ]);1407 1408 y->data.F64[ 0 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum - 1];1409 y->data.F64[ 1 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum];1410 y->data.F64[ 2 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum + 1];1319 if (stats->options & PS_STAT_ROBUST_MEDIAN) { 1320 if ((maxBinNum > 0) && (maxBinNum < (robustHistogram->nums->n - 1))) { 1321 x->data.F64[0] = (double)0.5 * 1322 (robustHistogram->bounds->data.F32[maxBinNum - 1] + 1323 robustHistogram->bounds->data.F32[maxBinNum]); 1324 x->data.F64[1] = (double)0.5 * 1325 (robustHistogram->bounds->data.F32[maxBinNum] + 1326 robustHistogram->bounds->data.F32[maxBinNum + 1]); 1327 x->data.F64[2] = (double)0.5 * 1328 (robustHistogram->bounds->data.F32[maxBinNum + 1] + 1329 robustHistogram->bounds->data.F32[maxBinNum + 2]); 1330 1331 y->data.F64[0] = cumulativeRobustSumsDlRange->data.F32[maxBinNum - 1]; 1332 y->data.F64[1] = cumulativeRobustSumsDlRange->data.F32[maxBinNum]; 1333 y->data.F64[2] = cumulativeRobustSumsDlRange->data.F32[maxBinNum + 1]; 1411 1334 1412 1335 // Ensure that cumulativeMedian/2 is actually within the range of the bins 1413 1336 // we are using. 1414 1337 cumulativeMedian *= 0.5; 1415 if ( !( ( y->data.F64[ 0 ] <= cumulativeMedian ) && 1416 ( cumulativeMedian <= y->data.F64[ 2 ] ) ) ) { 1417 printf( "((%f), %f, %f)\n", cumulativeMedian, y->data.F64[ 0 ], y->data.F64[ 2 ] ); 1418 psAbort( __func__, "p_psVectorRobustStats(1): midpoint not within y-range\n" ); 1338 if (!((y->data.F64[0] <= cumulativeMedian) && (cumulativeMedian <= y->data.F64[2]))) { 1339 printf("((%f), %f, %f)\n", cumulativeMedian, y->data.F64[0], y->data.F64[2]); 1340 psAbort(__func__, "p_psVectorRobustStats(1): midpoint not within y-range\n"); 1419 1341 } 1420 1342 // XXX: yErr is not currently used by psVectorFitPolynomial1D(). We 1421 1343 // may have to set this meaningfully later. 1422 yErr->data.F64[ 0] = 1.0;1423 yErr->data.F64[ 1] = 1.0;1424 yErr->data.F64[ 2] = 1.0;1344 yErr->data.F64[0] = 1.0; 1345 yErr->data.F64[1] = 1.0; 1346 yErr->data.F64[2] = 1.0; 1425 1347 1426 1348 // Determine the coefficients of the polynomial. 1427 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr);1349 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1428 1350 // Call p_ps1DPolyMedian(), which does a binary search on the 1429 1351 // polynomial, looking for the value x such that 1430 1352 // f(x) = cumulativeMedian. 1431 stats->robustMedian = p_ps1DPolyMedian( myPoly, x->data.F64[ 0 ], 1432 x->data.F64[ 2 ], cumulativeMedian ); 1353 stats->robustMedian = p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], cumulativeMedian); 1433 1354 } else { 1434 1355 // If the mode is the first/last histogram bin, then simply use 1435 1356 // the midpoint of that bin. 1436 stats->robustMedian = 0.5 * ( robustHistogram->bounds->data.F32[ maxBinNum + 1 ] + 1437 robustHistogram->bounds->data.F32[ maxBinNum ] ); 1438 } 1439 } 1440 1357 stats->robustMedian = 0.5 * (robustHistogram->bounds->data.F32[maxBinNum + 1] + 1358 robustHistogram->bounds->data.F32[maxBinNum]); 1359 } 1360 } 1441 1361 // The lower/upper quartile calculations are very similar to the median 1442 1362 // calculations. We fit a quadratic to the array containing the … … 1444 1364 // f(x) equals the lower/upper quartile exactly. 1445 1365 // 1446 if ( stats->options & PS_STAT_ROBUST_QUARTILE ) { 1447 countFloat = cumulativeRobustSumsFullRange->data.F32[ robustHistogramVector->n - 1 ]; 1448 1449 if ( ( LQBinNum > 0 ) && ( LQBinNum < ( robustHistogram->nums->n - 1 ) ) ) { 1450 x->data.F64[ 0 ] = ( double ) 0.5 * 1451 ( robustHistogram->bounds->data.F32[ LQBinNum - 1 ] + 1452 robustHistogram->bounds->data.F32[ LQBinNum ] ); 1453 x->data.F64[ 1 ] = ( double ) 0.5 * 1454 ( robustHistogram->bounds->data.F32[ LQBinNum ] + 1455 robustHistogram->bounds->data.F32[ LQBinNum + 1 ] ); 1456 x->data.F64[ 2 ] = ( double ) 0.5 * 1457 ( robustHistogram->bounds->data.F32[ LQBinNum + 1 ] + 1458 robustHistogram->bounds->data.F32[ LQBinNum + 2 ] ); 1459 1460 y->data.F64[ 0 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum - 1 ]; 1461 y->data.F64[ 1 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum ]; 1462 y->data.F64[ 2 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum + 1 ]; 1463 1464 if ( !( ( y->data.F64[ 0 ] <= ( countFloat / 4.0 ) ) && 1465 ( ( countFloat / 4.0 ) <= y->data.F64[ 2 ] ) ) ) { 1466 psAbort( __func__, "p_psVectorRobustStats(2): midpoint not within y-range\n" ); 1467 } 1468 1469 yErr->data.F64[ 0 ] = 1.0; 1470 yErr->data.F64[ 1 ] = 1.0; 1471 yErr->data.F64[ 2 ] = 1.0; 1472 1473 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1474 stats->robustLQ = p_ps1DPolyMedian( myPoly, 1475 x->data.F64[ 0 ], 1476 x->data.F64[ 2 ], 1477 countFloat / 4.0 ); 1366 if (stats->options & PS_STAT_ROBUST_QUARTILE) { 1367 countFloat = cumulativeRobustSumsFullRange->data.F32[robustHistogramVector->n - 1]; 1368 1369 if ((LQBinNum > 0) && (LQBinNum < (robustHistogram->nums->n - 1))) { 1370 x->data.F64[0] = (double)0.5 * 1371 (robustHistogram->bounds->data.F32[LQBinNum - 1] + 1372 robustHistogram->bounds->data.F32[LQBinNum]); 1373 x->data.F64[1] = (double)0.5 * 1374 (robustHistogram->bounds->data.F32[LQBinNum] + 1375 robustHistogram->bounds->data.F32[LQBinNum + 1]); 1376 x->data.F64[2] = (double)0.5 * 1377 (robustHistogram->bounds->data.F32[LQBinNum + 1] + 1378 robustHistogram->bounds->data.F32[LQBinNum + 2]); 1379 1380 y->data.F64[0] = cumulativeRobustSumsFullRange->data.F32[LQBinNum - 1]; 1381 y->data.F64[1] = cumulativeRobustSumsFullRange->data.F32[LQBinNum]; 1382 y->data.F64[2] = cumulativeRobustSumsFullRange->data.F32[LQBinNum + 1]; 1383 1384 if (!((y->data.F64[0] <= (countFloat / 4.0)) && ((countFloat / 4.0) <= y->data.F64[2]))) { 1385 psAbort(__func__, "p_psVectorRobustStats(2): midpoint not within y-range\n"); 1386 } 1387 1388 yErr->data.F64[0] = 1.0; 1389 yErr->data.F64[1] = 1.0; 1390 yErr->data.F64[2] = 1.0; 1391 1392 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1393 stats->robustLQ = p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], countFloat / 4.0); 1478 1394 1479 1395 } else { 1480 1396 // If the LQ is the first/last histogram bin, then simply use 1481 1397 // the midpoint of that bin. 1482 stats->robustLQ = 0.5 * ( robustHistogram->bounds->data.F32[ LQBinNum + 1 ] + 1483 robustHistogram->bounds->data.F32[ LQBinNum ] ); 1484 } 1485 1486 if ( ( UQBinNum > 0 ) && ( UQBinNum < ( robustHistogram->nums->n - 1 ) ) ) { 1487 x->data.F64[ 0 ] = ( double ) 0.5 * 1488 ( robustHistogram->bounds->data.F32[ UQBinNum - 1 ] + 1489 robustHistogram->bounds->data.F32[ UQBinNum ] ); 1490 x->data.F64[ 1 ] = ( double ) 0.5 * 1491 ( robustHistogram->bounds->data.F32[ UQBinNum ] + 1492 robustHistogram->bounds->data.F32[ UQBinNum + 1 ] ); 1493 x->data.F64[ 2 ] = ( double ) 0.5 * 1494 ( robustHistogram->bounds->data.F32[ UQBinNum + 1 ] + 1495 robustHistogram->bounds->data.F32[ UQBinNum + 2 ] ); 1496 1497 y->data.F64[ 0 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum - 1 ]; 1498 y->data.F64[ 1 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum ]; 1499 y->data.F64[ 2 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum + 1 ]; 1500 1501 if ( !( ( y->data.F64[ 0 ] <= ( 3.0 * countFloat / 4.0 ) ) && 1502 ( ( 3.0 * countFloat / 4.0 ) <= y->data.F64[ 2 ] ) ) ) { 1503 psAbort( __func__, "p_psVectorRobustStats(3): midpoint not within y-range\n" ); 1504 } 1505 1506 yErr->data.F64[ 0 ] = 1.0; 1507 yErr->data.F64[ 1 ] = 1.0; 1508 yErr->data.F64[ 2 ] = 1.0; 1509 1510 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1511 stats->robustUQ = p_ps1DPolyMedian( myPoly, 1512 x->data.F64[ 0 ], 1513 x->data.F64[ 2 ], 1514 3.0 * countFloat / 4.0 ); 1398 stats->robustLQ = 0.5 * (robustHistogram->bounds->data.F32[LQBinNum + 1] + 1399 robustHistogram->bounds->data.F32[LQBinNum]); 1400 } 1401 1402 if ((UQBinNum > 0) && (UQBinNum < (robustHistogram->nums->n - 1))) { 1403 x->data.F64[0] = (double)0.5 * 1404 (robustHistogram->bounds->data.F32[UQBinNum - 1] + 1405 robustHistogram->bounds->data.F32[UQBinNum]); 1406 x->data.F64[1] = (double)0.5 * 1407 (robustHistogram->bounds->data.F32[UQBinNum] + 1408 robustHistogram->bounds->data.F32[UQBinNum + 1]); 1409 x->data.F64[2] = (double)0.5 * 1410 (robustHistogram->bounds->data.F32[UQBinNum + 1] + 1411 robustHistogram->bounds->data.F32[UQBinNum + 2]); 1412 1413 y->data.F64[0] = cumulativeRobustSumsFullRange->data.F32[UQBinNum - 1]; 1414 y->data.F64[1] = cumulativeRobustSumsFullRange->data.F32[UQBinNum]; 1415 y->data.F64[2] = cumulativeRobustSumsFullRange->data.F32[UQBinNum + 1]; 1416 1417 if (!((y->data.F64[0] <= (3.0 * countFloat / 4.0)) && 1418 ((3.0 * countFloat / 4.0) <= y->data.F64[2]))) { 1419 psAbort(__func__, "p_psVectorRobustStats(3): midpoint not within y-range\n"); 1420 } 1421 1422 yErr->data.F64[0] = 1.0; 1423 yErr->data.F64[1] = 1.0; 1424 yErr->data.F64[2] = 1.0; 1425 1426 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1427 stats->robustUQ = p_ps1DPolyMedian(myPoly, 1428 x->data.F64[0], x->data.F64[2], 3.0 * countFloat / 4.0); 1515 1429 } else { 1516 1430 // If the UQ is the first/last histogram bin, then simply use 1517 1431 // the midpoint of that bin. 1518 stats->robustUQ = 0.5 * ( robustHistogram->bounds->data.F32[ UQBinNum + 1] +1519 robustHistogram->bounds->data.F32[ UQBinNum ]);1432 stats->robustUQ = 0.5 * (robustHistogram->bounds->data.F32[UQBinNum + 1] + 1433 robustHistogram->bounds->data.F32[UQBinNum]); 1520 1434 } 1521 1435 } … … 1523 1437 stats->robustN50 = sumN50; 1524 1438 1525 psFree( x ); 1526 psFree( y ); 1527 psFree( yErr ); 1528 psFree( tmpStats ); 1529 psFree( robustHistogram ); 1530 psFree( myPoly ); 1531 psFree( cumulativeRobustSumsFullRange ); 1532 psFree( cumulativeRobustSumsDlRange ); 1533 } 1534 1535 1439 psFree(x); 1440 psFree(y); 1441 psFree(yErr); 1442 psFree(tmpStats); 1443 psFree(robustHistogram); 1444 psFree(myPoly); 1445 psFree(cumulativeRobustSumsFullRange); 1446 psFree(cumulativeRobustSumsDlRange); 1447 } 1536 1448 1537 1449 /* … … 1582 1494 */ 1583 1495 1584 1585 1496 /*****************************************************************************/ 1497 1586 1498 /* FUNCTION IMPLEMENTATION - PUBLIC */ 1499 1587 1500 /*****************************************************************************/ 1588 1501 1589 static void histogramFree( psHistogram *myHist);1502 static void histogramFree(psHistogram * myHist); 1590 1503 1591 1504 /****************************************************************************** 1592 1505 psStatsAlloc(): This routine must create a new psStats data structure. 1593 1506 *****************************************************************************/ 1594 psStats *psStatsAlloc( psStatsOptions options)1595 { 1596 psStats * newStruct = NULL;1597 1598 newStruct = ( psStats * ) psAlloc( sizeof( psStats ));1507 psStats *psStatsAlloc(psStatsOptions options) 1508 { 1509 psStats *newStruct = NULL; 1510 1511 newStruct = (psStats *) psAlloc(sizeof(psStats)); 1599 1512 newStruct->sampleMean = NAN; 1600 1513 newStruct->sampleMedian = NAN; … … 1620 1533 newStruct->options = options; 1621 1534 1622 return ( newStruct);1535 return (newStruct); 1623 1536 } 1624 1537 … … 1635 1548 The histogram structure 1636 1549 *****************************************************************************/ 1637 psHistogram *psHistogramAlloc( float lower, 1638 float upper, 1639 int n ) 1640 { 1641 int i = 0; // Loop index variable 1550 psHistogram *psHistogramAlloc(float lower, float upper, int n) 1551 { 1552 int i = 0; // Loop index variable 1642 1553 psHistogram *newHist = NULL; // The new histogram structure 1643 float binSize = 0.0; // The histogram bin size1554 float binSize = 0.0; // The histogram bin size 1644 1555 1645 1556 // NOTE: Verify that this is the correct action. 1646 if ( n == 0 ) { 1647 return ( NULL ); 1648 } 1649 if ( n < 0 ) { 1650 psAbort( __func__, "psHistogramAlloc() called with bin size %d.\n", n ); 1651 } 1652 1557 if (n == 0) { 1558 return (NULL); 1559 } 1560 if (n < 0) { 1561 psAbort(__func__, "psHistogramAlloc() called with bin size %d.\n", n); 1562 } 1653 1563 // NOTE: Verify that this is the correct action. 1654 if ( lower > upper ) { 1655 return ( NULL ); 1656 } 1657 1564 if (lower > upper) { 1565 return (NULL); 1566 } 1658 1567 // Allocate memory for the new histogram structure. If there are N 1659 1568 // bins, then there are N+1 bounds to those bins. 1660 newHist = ( psHistogram * ) psAlloc( sizeof( psHistogram ));1661 p_psMemSetDeallocator( newHist, ( psFreeFcn ) histogramFree);1662 newHist->bounds = psVectorAlloc( n + 1, PS_TYPE_F32);1569 newHist = (psHistogram *) psAlloc(sizeof(psHistogram)); 1570 p_psMemSetDeallocator(newHist, (psFreeFcn) histogramFree); 1571 newHist->bounds = psVectorAlloc(n + 1, PS_TYPE_F32); 1663 1572 newHist->bounds->n = newHist->bounds->nalloc; 1664 1573 1665 1574 // Calculate the bounds for each bin. 1666 binSize = ( upper - lower ) / ( float )n;1667 // NOTE: Is the following necessary? It prevents the max data point1575 binSize = (upper - lower) / (float)n; 1576 // NOTE: Is the following necessary? It prevents the max data point 1668 1577 // from being in a non-existant bin. 1669 1578 binSize += FLT_EPSILON; 1670 for ( i = 0;i < n + 1;i++) {1671 newHist->bounds->data.F32[ i ] = lower + ( binSize * ( float ) i);1579 for (i = 0; i < n + 1; i++) { 1580 newHist->bounds->data.F32[i] = lower + (binSize * (float)i); 1672 1581 } 1673 1582 1674 1583 // Allocate the bins, and initialize them to zero. 1675 newHist->nums = psVectorAlloc( n, PS_TYPE_U32);1584 newHist->nums = psVectorAlloc(n, PS_TYPE_U32); 1676 1585 newHist->nums->n = newHist->nums->nalloc; 1677 for ( i = 0;i < newHist->nums->n;i++) {1678 newHist->nums->data.U32[ i] = 0;1586 for (i = 0; i < newHist->nums->n; i++) { 1587 newHist->nums->data.U32[i] = 0; 1679 1588 } 1680 1589 … … 1684 1593 newHist->uniform = true; 1685 1594 1686 return ( newHist);1595 return (newHist); 1687 1596 } 1688 1597 … … 1696 1605 The histogram structure 1697 1606 *****************************************************************************/ 1698 psHistogram *psHistogramAllocGeneric( const psVector *restrict bounds)1699 { 1700 psHistogram * newHist = NULL; // The new histogram structure1701 int i; // Loop index variable1607 psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds) 1608 { 1609 psHistogram *newHist = NULL; // The new histogram structure 1610 int i; // Loop index variable 1702 1611 1703 1612 // NOTE: Verify that this is the correct action. 1704 if ( bounds == NULL) {1613 if (bounds == NULL) { 1705 1614 // psAbort(__func__, "psHistogram requested with NULL bounds"); 1706 return ( NULL ); 1707 } 1708 1615 return (NULL); 1616 } 1709 1617 // NOTE: Verify that this is the correct action. 1710 if ( bounds->n <= 1) {1618 if (bounds->n <= 1) { 1711 1619 // psAbort(__func__, "psHistogram requested with NULL bounds"); 1712 return ( NULL);1713 } 1714 1715 if ( bounds->type.type != PS_TYPE_F32) {1620 return (NULL); 1621 } 1622 1623 if (bounds->type.type != PS_TYPE_F32) { 1716 1624 // psAbort(__func__, "psHistogram request a bound which is not type F32"); 1717 return ( NULL ); 1718 } 1719 1625 return (NULL); 1626 } 1720 1627 // Allocate memory for the new histogram structure. 1721 newHist = ( psHistogram * ) psAlloc( sizeof( psHistogram ));1722 p_psMemSetDeallocator( newHist, ( psFreeFcn ) histogramFree);1723 newHist->bounds = psVectorAlloc( bounds->n, PS_TYPE_F32);1628 newHist = (psHistogram *) psAlloc(sizeof(psHistogram)); 1629 p_psMemSetDeallocator(newHist, (psFreeFcn) histogramFree); 1630 newHist->bounds = psVectorAlloc(bounds->n, PS_TYPE_F32); 1724 1631 newHist->bounds->n = newHist->bounds->nalloc; 1725 for ( i = 0;i < bounds->n;i++) {1726 newHist->bounds->data.F32[ i ] = bounds->data.F32[ i];1632 for (i = 0; i < bounds->n; i++) { 1633 newHist->bounds->data.F32[i] = bounds->data.F32[i]; 1727 1634 } 1728 1635 1729 1636 // Allocate the bins, and initialize them to zero. If there are N bounds, 1730 1637 // then there are N-1 bins. 1731 newHist->nums = psVectorAlloc( ( bounds->n ) - 1, PS_TYPE_U32);1638 newHist->nums = psVectorAlloc((bounds->n) - 1, PS_TYPE_U32); 1732 1639 newHist->nums->n = newHist->nums->nalloc; 1733 for ( i = 0;i < newHist->nums->n;i++) {1734 newHist->nums->data.U32[ i] = 0;1640 for (i = 0; i < newHist->nums->n; i++) { 1641 newHist->nums->data.U32[i] = 0; 1735 1642 } 1736 1643 … … 1740 1647 newHist->uniform = false; 1741 1648 1742 return ( newHist ); 1743 } 1744 1745 static void histogramFree( psHistogram *myHist ) 1746 { 1747 psFree( myHist->bounds ); 1748 psFree( myHist->nums ); 1749 } 1750 1649 return (newHist); 1650 } 1651 1652 static void histogramFree(psHistogram * myHist) 1653 { 1654 psFree(myHist->bounds); 1655 psFree(myHist->nums); 1656 } 1751 1657 1752 1658 /***************************************************************************** … … 1764 1670 The histogram structure "out". 1765 1671 *****************************************************************************/ 1766 psHistogram *psVectorHistogram( psHistogram *out, 1767 const psVector *restrict in, 1768 const psVector *restrict mask, 1769 unsigned int maskVal ) 1770 { 1771 int i = 0; // Loop index variable 1772 int j = 0; // Loop index variable 1773 float binSize = 0.0; // Histogram bin size 1774 int binNum = 0; // A temporary bin number 1775 int numBins = 0; // The total number of bins 1672 psHistogram *psVectorHistogram(psHistogram * out, 1673 const psVector * restrict in, 1674 const psVector * restrict mask, unsigned int maskVal) 1675 { 1676 int i = 0; // Loop index variable 1677 int j = 0; // Loop index variable 1678 float binSize = 0.0; // Histogram bin size 1679 int binNum = 0; // A temporary bin number 1680 int numBins = 0; // The total number of bins 1776 1681 1777 1682 // NOTE: Verify that this is the correct action. 1778 if ( out == NULL ) { 1779 return ( NULL ); 1780 } 1781 1683 if (out == NULL) { 1684 return (NULL); 1685 } 1782 1686 // Check the specified output histogram for type psF32 1783 if ( out->bounds->type.type != PS_TYPE_F32 ) { 1784 psAbort( __func__, 1785 "Only data type PS_TYPE_F32 for the output.bounds member." ); 1786 } 1787 1788 if ( out->nums->type.type != PS_TYPE_U32 ) { 1789 psAbort( __func__, 1790 "Only data type PS_TYPE_U32 for output.nums member." ); 1791 } 1792 1687 if (out->bounds->type.type != PS_TYPE_F32) { 1688 psAbort(__func__, "Only data type PS_TYPE_F32 for the output.bounds member."); 1689 } 1690 1691 if (out->nums->type.type != PS_TYPE_U32) { 1692 psAbort(__func__, "Only data type PS_TYPE_U32 for output.nums member."); 1693 } 1793 1694 // NOTE: Verify that this is the correct action. 1794 if ( in == NULL ) { 1795 return ( out ); 1796 } 1797 1798 if ( in->type.type != PS_TYPE_F32 ) { 1799 psAbort( __func__, 1800 "Only data type PS_TYPE_F32 is currently supported (0x%x).", 1801 in->type.type ); 1802 } 1803 1804 if ( mask != NULL ) { 1805 if ( in->n != mask->n ) { 1806 psAbort( __func__, 1807 "Vector data and vector mask are of different sizes." ); 1808 } 1809 if ( mask->type.type != PS_TYPE_U8 ) { 1810 psAbort( __func__, "Vector mask must be type PS_TYPE_U8" ); 1695 if (in == NULL) { 1696 return (out); 1697 } 1698 1699 if (in->type.type != PS_TYPE_F32) { 1700 psAbort(__func__, "Only data type PS_TYPE_F32 is currently supported (0x%x).", in->type.type); 1701 } 1702 1703 if (mask != NULL) { 1704 if (in->n != mask->n) { 1705 psAbort(__func__, "Vector data and vector mask are of different sizes."); 1706 } 1707 if (mask->type.type != PS_TYPE_U8) { 1708 psAbort(__func__, "Vector mask must be type PS_TYPE_U8"); 1811 1709 } 1812 1710 } … … 1815 1713 1816 1714 numBins = out->nums->n; 1817 for ( i = 0;i < in->n;i++) {1715 for (i = 0; i < in->n; i++) { 1818 1716 // Check if this pixel is masked, and if so, skip it. 1819 if ( ( mask == NULL ) || 1820 ( ( mask != NULL ) && ( !( mask->data.U8[ i ] & maskVal ) ) ) ) { 1717 if ((mask == NULL) || ((mask != NULL) && (!(mask->data.U8[i] & maskVal)))) { 1821 1718 // Check if this pixel is below the minimum value, and if so 1822 1719 // count it, then skip it. 1823 if ( in->data.F32[ i ] < out->bounds->data.F32[ 0 ]) {1720 if (in->data.F32[i] < out->bounds->data.F32[0]) { 1824 1721 out->minNum++; 1825 1722 // Check if this pixel is above the maximum value, and if so 1826 1723 // count it, then skip it. 1827 } else 1828 if ( in->data.F32[ i ] > out->bounds->data.F32[ numBins ] ) { 1829 out->maxNum++; 1724 } else if (in->data.F32[i] > out->bounds->data.F32[numBins]) { 1725 out->maxNum++; 1726 } else { 1727 // If this is a uniform histogram, determining the correct 1728 // number is trivial. 1729 if (out->uniform == true) { 1730 binSize = out->bounds->data.F32[1] - out->bounds->data.F32[0]; 1731 binNum = (int)((in->data.F32[i] - out->bounds->data.F32[0]) / binSize); 1732 1733 // NOTE: This next if-statement really shouldn't be necessary. 1734 // However, do to numerical lack of precision, we occasionally 1735 // produce a binNum outside the range of bins. 1736 if (binNum >= out->nums->n) { 1737 binNum = out->nums->n - 1; 1738 } 1739 1740 (out->nums->data.S32[binNum])++; 1741 1742 // If this is a non-uniform histogram, determining the correct 1743 // bin number requires a bit more work. 1830 1744 } else { 1831 // If this is a uniform histogram, determining the correct 1832 // number is trivial. 1833 if ( out->uniform == true ) { 1834 binSize = out->bounds->data.F32[ 1 ] - out->bounds->data.F32[ 0 ]; 1835 binNum = ( int ) ( ( in->data.F32[ i ] - out->bounds->data.F32[ 0 ] ) / 1836 binSize ); 1837 1838 // NOTE: This next if-statement really shouldn't be necessary. 1839 // However, do to numerical lack of precision, we occasionally 1840 // produce a binNum outside the range of bins. 1841 if ( binNum >= out->nums->n ) { 1842 binNum = out->nums->n - 1; 1843 } 1844 1845 ( out->nums->data.S32[ binNum ] ) ++; 1846 1847 // If this is a non-uniform histogram, determining the correct 1848 // bin number requires a bit more work. 1849 } else { 1850 // NOTE: This is slow. Put a smarter algorithm here to 1851 // find the correct bin number (bin search, probably) 1852 for ( j = 0;j < ( out->bounds->n ) - 1;j++ ) { 1853 if ( ( out->bounds->data.S32[ j ] <= in->data.F32[ i ] ) && 1854 ( in->data.F32[ i ] <= out->bounds->data.S32[ j + 1 ] ) ) { 1855 ( out->nums->data.S32[ j ] ) ++; 1856 } 1745 // NOTE: This is slow. Put a smarter algorithm here to 1746 // find the correct bin number (bin search, probably) 1747 for (j = 0; j < (out->bounds->n) - 1; j++) { 1748 if ((out->bounds->data.S32[j] <= in->data.F32[i]) && 1749 (in->data.F32[i] <= out->bounds->data.S32[j + 1])) { 1750 (out->nums->data.S32[j])++; 1857 1751 } 1858 1752 } 1859 1753 } 1860 } 1861 } 1862 return ( out ); 1754 } 1755 } 1756 } 1757 return (out); 1863 1758 } 1864 1759 … … 1872 1767 the various stat functions. 1873 1768 *****************************************************************************/ 1874 psVector *p_psConvertToF32( psStats *stats, 1875 psVector *in, 1876 psVector *mask, 1877 unsigned int maskVal ) 1769 psVector *p_psConvertToF32(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal) 1878 1770 { 1879 1771 int i = 0; 1880 1772 psVector *tmp = NULL; 1881 1773 1882 if ( in->type.type == PS_TYPE_S32 ) { 1883 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1884 for ( i = 0;i < in->n;i++ ) { 1885 tmp->data.F32[ i ] = ( float ) in->data.S32[ i ]; 1886 } 1887 } else 1888 if ( in->type.type == PS_TYPE_U32 ) { 1889 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1890 for ( i = 0;i < in->n;i++ ) { 1891 tmp->data.F32[ i ] = ( float ) in->data.U32[ i ]; 1892 } 1893 } else 1894 if ( in->type.type == PS_TYPE_F64 ) { 1895 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1896 for ( i = 0;i < in->n;i++ ) { 1897 tmp->data.F32[ i ] = ( float ) in->data.F64[ i ]; 1898 } 1899 } else 1900 if ( in->type.type == PS_TYPE_F32 ) { 1901 // do nothing 1902 } else { 1903 psAbort( __func__, "unsupported vector type 0x%x\n", in->type.type ); 1904 } 1905 return ( tmp ); 1906 } 1907 1774 if (in->type.type == PS_TYPE_S32) { 1775 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1776 for (i = 0; i < in->n; i++) { 1777 tmp->data.F32[i] = (float)in->data.S32[i]; 1778 } 1779 } else if (in->type.type == PS_TYPE_U32) { 1780 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1781 for (i = 0; i < in->n; i++) { 1782 tmp->data.F32[i] = (float)in->data.U32[i]; 1783 } 1784 } else if (in->type.type == PS_TYPE_F64) { 1785 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1786 for (i = 0; i < in->n; i++) { 1787 tmp->data.F32[i] = (float)in->data.F64[i]; 1788 } 1789 } else if (in->type.type == PS_TYPE_F32) { 1790 // do nothing 1791 } else { 1792 psAbort(__func__, "unsupported vector type 0x%x\n", in->type.type); 1793 } 1794 return (tmp); 1795 } 1908 1796 1909 1797 /****************************************************************************** … … 1924 1812 macro-ize everything and add PS_TYPE_U16 and PS_TYPE_F64. 1925 1813 *****************************************************************************/ 1926 psStats *psVectorStats( psStats *stats, 1927 psVector *in, 1928 psVector *mask, 1929 unsigned int maskVal ) 1930 { 1931 psVector * inF32; 1814 psStats *psVectorStats(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal) 1815 { 1816 psVector *inF32; 1932 1817 int mustFreeTmp = 1; 1933 1818 1934 1819 // NOTE: Verify that this is the correct action. 1935 if ( in == NULL) {1936 return ( stats);1937 } 1938 if ( stats == NULL) {1939 return ( NULL);1940 } 1941 1942 inF32 = p_psConvertToF32( stats, in, mask, maskVal);1943 if ( inF32 == NULL) {1820 if (in == NULL) { 1821 return (stats); 1822 } 1823 if (stats == NULL) { 1824 return (NULL); 1825 } 1826 1827 inF32 = p_psConvertToF32(stats, in, mask, maskVal); 1828 if (inF32 == NULL) { 1944 1829 inF32 = in; 1945 1830 mustFreeTmp = 0; 1946 1831 } 1947 1948 1832 // XXX: Should we abort if (stats->min == stats->max)? 1949 if ( ( stats->options & PS_STAT_USE_RANGE ) && 1950 ( stats->min >= stats->max ) ) { 1951 psAbort( __func__, "psVectorStats() called with range: %f to %f\n", 1952 stats->min, stats->max ); 1953 } 1954 1955 // PS_CHECK_VECTOR_TYPE(in, PS_TYPE_F32); 1956 if ( mask != NULL ) { 1957 PS_CHECK_NULL_VECTOR( mask ); 1958 PS_CHECK_EMPTY_VECTOR( mask ); 1959 PS_CHECK_VECTOR_SIZE_EQUAL( mask, in ); 1960 PS_CHECK_VECTOR_TYPE( mask, PS_TYPE_U8 ); 1961 } 1962 1833 if ((stats->options & PS_STAT_USE_RANGE) && (stats->min >= stats->max)) { 1834 psAbort(__func__, "psVectorStats() called with range: %f to %f\n", stats->min, stats->max); 1835 } 1836 // PS_CHECK_VECTOR_TYPE(in, PS_TYPE_F32); 1837 if (mask != NULL) { 1838 PS_CHECK_NULL_VECTOR(mask); 1839 PS_CHECK_EMPTY_VECTOR(mask); 1840 PS_CHECK_VECTOR_SIZE_EQUAL(mask, in); 1841 PS_CHECK_VECTOR_TYPE(mask, PS_TYPE_U8); 1842 } 1963 1843 // ************************************************************************ 1964 if ( stats->options & PS_STAT_SAMPLE_MEAN ) { 1965 p_psVectorSampleMean( in, mask, maskVal, stats ); 1966 } 1967 1844 if (stats->options & PS_STAT_SAMPLE_MEAN) { 1845 p_psVectorSampleMean(in, mask, maskVal, stats); 1846 } 1968 1847 // ************************************************************************ 1969 if ( stats->options & PS_STAT_SAMPLE_MEDIAN ) { 1970 p_psVectorSampleMedian( in, mask, maskVal, stats ); 1971 } 1972 1848 if (stats->options & PS_STAT_SAMPLE_MEDIAN) { 1849 p_psVectorSampleMedian(in, mask, maskVal, stats); 1850 } 1973 1851 // ************************************************************************ 1974 1852 // NOTE: The Stdev calculation requires the mean. Should we assume the 1975 // mean has already been calculated? Or should we always calculate it? 1976 if ( stats->options & PS_STAT_SAMPLE_STDEV ) { 1977 p_psVectorSampleMean( in, mask, maskVal, stats ); 1978 p_psVectorSampleStdev( in, mask, maskVal, stats ); 1979 } 1980 1853 // mean has already been calculated? Or should we always calculate it? 1854 if (stats->options & PS_STAT_SAMPLE_STDEV) { 1855 p_psVectorSampleMean(in, mask, maskVal, stats); 1856 p_psVectorSampleStdev(in, mask, maskVal, stats); 1857 } 1981 1858 // ************************************************************************ 1982 if ( stats->options & PS_STAT_SAMPLE_QUARTILE ) { 1983 p_psVectorSampleQuartiles( in, mask, maskVal, stats ); 1984 } 1985 1859 if (stats->options & PS_STAT_SAMPLE_QUARTILE) { 1860 p_psVectorSampleQuartiles(in, mask, maskVal, stats); 1861 } 1986 1862 // Since the various robust stats quantities share much computation, they 1987 1863 // are grouped together in a single private function: 1988 1864 // p_psVectorRobustStats() 1989 if ( ( stats->options & PS_STAT_ROBUST_MEAN ) || 1990 ( stats->options & PS_STAT_ROBUST_MEDIAN ) || 1991 ( stats->options & PS_STAT_ROBUST_MODE ) || 1992 ( stats->options & PS_STAT_ROBUST_STDEV ) || 1993 ( stats->options & PS_STAT_ROBUST_QUARTILE ) ) { 1994 p_psVectorRobustStats( in, mask, maskVal, stats ); 1995 } 1996 1997 if ( ( stats->options & PS_STAT_CLIPPED_MEAN ) || 1998 ( stats->options & PS_STAT_CLIPPED_STDEV ) ) { 1999 p_psVectorClippedStats( in, mask, maskVal, stats ); 2000 } 2001 1865 if ((stats->options & PS_STAT_ROBUST_MEAN) || 1866 (stats->options & PS_STAT_ROBUST_MEDIAN) || 1867 (stats->options & PS_STAT_ROBUST_MODE) || 1868 (stats->options & PS_STAT_ROBUST_STDEV) || (stats->options & PS_STAT_ROBUST_QUARTILE)) { 1869 p_psVectorRobustStats(in, mask, maskVal, stats); 1870 } 1871 1872 if ((stats->options & PS_STAT_CLIPPED_MEAN) || (stats->options & PS_STAT_CLIPPED_STDEV)) { 1873 p_psVectorClippedStats(in, mask, maskVal, stats); 1874 } 2002 1875 // ************************************************************************ 2003 if ( stats->options & PS_STAT_MAX ) { 2004 p_psVectorMax( in, mask, maskVal, stats ); 2005 } 2006 1876 if (stats->options & PS_STAT_MAX) { 1877 p_psVectorMax(in, mask, maskVal, stats); 1878 } 2007 1879 // ************************************************************************ 2008 if ( stats->options & PS_STAT_MIN) {2009 p_psVectorMin( in, mask, maskVal, stats);2010 } 2011 2012 if ( mustFreeTmp == 1) {2013 psFree( inF32);2014 } 2015 return ( stats);2016 } 1880 if (stats->options & PS_STAT_MIN) { 1881 p_psVectorMin(in, mask, maskVal, stats); 1882 } 1883 1884 if (mustFreeTmp == 1) { 1885 psFree(inF32); 1886 } 1887 return (stats); 1888 } -
trunk/psLib/src/dataManip/psStats.h
r1406 r1407 1 1 2 /** @file psStats.h 2 3 * \brief basic statistical operations … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_STATS_H) 17 # define PS_STATS_H18 # define PS_STATS_H 18 19 19 # include "psVector.h"20 # include "psVector.h" 20 21 21 22 /// @addtogroup Stats … … 26 27 *****************************************************************************/ 27 28 typedef enum { 28 PS_STAT_SAMPLE_MEAN = 0x000001,29 PS_STAT_SAMPLE_MEDIAN = 0x000002,30 PS_STAT_SAMPLE_STDEV = 0x000004,31 PS_STAT_SAMPLE_QUARTILE = 0x000008,32 PS_STAT_ROBUST_MEAN = 0x000010,33 PS_STAT_ROBUST_MEDIAN = 0x000020,34 PS_STAT_ROBUST_MODE = 0x000040,35 PS_STAT_ROBUST_STDEV = 0x000080,36 PS_STAT_ROBUST_QUARTILE = 0x000100,37 PS_STAT_CLIPPED_MEAN = 0x000200,38 PS_STAT_CLIPPED_STDEV = 0x000400,39 PS_STAT_MAX = 0x000800,40 PS_STAT_MIN = 0x001000,41 PS_STAT_USE_RANGE = 0x002000,42 PS_STAT_USE_BINSIZE = 0x004000,43 PS_STAT_ROBUST_FOR_SAMPLE = 0x00800029 PS_STAT_SAMPLE_MEAN = 0x000001, 30 PS_STAT_SAMPLE_MEDIAN = 0x000002, 31 PS_STAT_SAMPLE_STDEV = 0x000004, 32 PS_STAT_SAMPLE_QUARTILE = 0x000008, 33 PS_STAT_ROBUST_MEAN = 0x000010, 34 PS_STAT_ROBUST_MEDIAN = 0x000020, 35 PS_STAT_ROBUST_MODE = 0x000040, 36 PS_STAT_ROBUST_STDEV = 0x000080, 37 PS_STAT_ROBUST_QUARTILE = 0x000100, 38 PS_STAT_CLIPPED_MEAN = 0x000200, 39 PS_STAT_CLIPPED_STDEV = 0x000400, 40 PS_STAT_MAX = 0x000800, 41 PS_STAT_MIN = 0x001000, 42 PS_STAT_USE_RANGE = 0x002000, 43 PS_STAT_USE_BINSIZE = 0x004000, 44 PS_STAT_ROBUST_FOR_SAMPLE = 0x008000 44 45 } psStatsOptions; 45 46 46 47 47 /** This is the generic statistics structure. It contails the data members … … 50 50 typedef struct 51 51 { 52 double sampleMean; // /< formal mean of sample53 double sampleMedian; // /< formal median of sample54 double sampleStdev; // /< standard deviation of sample55 double sampleUQ; // /< upper quartile of sample56 double sampleLQ; // /< lower quartile of sample57 double sampleLimit; // /<58 double robustMean; // /< robust mean of array59 double robustMedian; // /< robust median of array60 double robustMode; // /< Robust mode of array61 double robustStdev; // /< robust standard deviation of array62 double robustUQ; // /< robust upper quartile63 double robustLQ; // /< robust lower quartile52 double sampleMean; // /< formal mean of sample 53 double sampleMedian; // /< formal median of sample 54 double sampleStdev; // /< standard deviation of sample 55 double sampleUQ; // /< upper quartile of sample 56 double sampleLQ; // /< lower quartile of sample 57 double sampleLimit; // /< 58 double robustMean; // /< robust mean of array 59 double robustMedian; // /< robust median of array 60 double robustMode; // /< Robust mode of array 61 double robustStdev; // /< robust standard deviation of array 62 double robustUQ; // /< robust upper quartile 63 double robustLQ; // /< robust lower quartile 64 64 double XXX; 65 double robustN50; // /<66 double robustNfit; // /<67 double clippedMean; // /< Nsigma clipped mean68 double clippedStdev; // /< standard deviation after clipping69 double clipSigma; // /< Nsigma used for clipping; user input70 int clipIter; ///< Number of clipping iterations; user input71 double min; // /< minimum data value in array72 double max; // /< maximum data value in array73 double binsize; // /<74 psStatsOptions options; // /< bitmask of calculated values65 double robustN50; // /< 66 double robustNfit; // /< 67 double clippedMean; // /< Nsigma clipped mean 68 double clippedStdev; // /< standard deviation after clipping 69 double clipSigma; // /< Nsigma used for clipping; user input 70 int clipIter; // /< Number of clipping iterations; user input 71 double min; // /< minimum data value in array 72 double max; // /< maximum data value in array 73 double binsize; // /< 74 psStatsOptions options; // /< bitmask of calculated values 75 75 } 76 76 psStats; 77 77 78 79 78 /** Do Statistics on an array. Returns a status value. \ingroup MathGroup */ 80 psStats * 81 psVectorStats(psStats *stats, ///< stats structure defines stats to be calculated and how 82 psVector *in, ///< Vector to be analysed: must be F32 83 psVector *mask, ///< Ignore elements where (maskVector & maskVal) != 0: must be INT or NULL 84 unsigned int maskVal ///< Only mask elements with one of these bits set in maskVector 85 ); 79 psStats *psVectorStats(psStats * stats, // /< stats structure defines stats to be calculated and how 80 psVector * in, // /< Vector to be analysed: must be F32 81 psVector * mask, // /< Ignore elements where (maskVector & maskVal) != 0: must be INT 82 // or NULL 83 unsigned int maskVal // /< Only mask elements with one of these bits set in 84 // maskVector 85 ); 86 86 87 87 /** A constructor for the stats structure.*/ 88 psStats *psStatsAlloc(psStatsOptions options); ///< Statistics to measure88 psStats *psStatsAlloc(psStatsOptions options); // /< Statistics to measure 89 89 90 90 /****************************************************************************** 91 91 Histogram functions and data structures. 92 92 *****************************************************************************/ 93 93 94 /** The basic histogram structure which contains bounds and bins. */ 94 95 typedef struct 95 96 { 96 psVector *bounds; ///< Bounds for the bins (type F32)97 psVector *nums; ///< Number in each of the bins (INT)98 int minNum; ///< Number below the minimum99 int maxNum; ///< Number above the maximum100 bool uniform; ///< Is it a uniform distribution?97 psVector *bounds; // /< Bounds for the bins (type F32) 98 psVector *nums; // /< Number in each of the bins (INT) 99 int minNum; // /< Number below the minimum 100 int maxNum; // /< Number above the maximum 101 bool uniform; // /< Is it a uniform distribution? 101 102 } 102 103 psHistogram; 103 104 104 105 105 /** Constructor \ingroup MathGroup */ 106 psHistogram * 107 psHistogramAlloc(float lower, ///< Lower limit for the bins 108 float upper, ///< Upper limit for the bins 109 int n); ///< Number of bins 110 106 psHistogram *psHistogramAlloc(float lower, // /< Lower limit for the bins 107 float upper, // /< Upper limit for the bins 108 int n); // /< Number of bins 111 109 112 110 /** Generic constructor \ingroup MathGroup */ 113 psHistogram * psHistogramAllocGeneric(const psVector *restrict bounds); ///< Bounds for the bins111 psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds); // /< Bounds for the bins 114 112 115 113 /** Calculate a histogram \ingroup MathGroup **/ 116 psHistogram *psVectorHistogram (psHistogram *out, ///< Histogram data117 const psVector *restrict in, ///< Vector to analyse118 const psVector *restrict mask, ///< Mask dat for input vector119 unsigned int maskVal); ///< Mask value114 psHistogram *psVectorHistogram(psHistogram * out, // /< Histogram data 115 const psVector * restrict in, // /< Vector to analyse 116 const psVector * restrict mask, // /< Mask dat for input vector 117 unsigned int maskVal); // /< Mask value 120 118 121 bool p_psGetStatValue( 122 const psStats* stats, 123 double* value 124 ); 119 bool p_psGetStatValue(const psStats * stats, double *value); 125 120 126 121 /// @} 127 122 128 123 #endif 129 -
trunk/psLib/src/dataManip/psVectorFFT.c
r1406 r1407 1 1 2 /** @file psFFT.c 2 3 * … … 5 6 * @author Robert DeSonia, MHPCC 6 7 * 7 * @version $Revision: 1.1 8$ $Name: not supported by cvs2svn $8 * @date $Date: 2004-08-0 6 22:34:05$8 * @version $Revision: 1.19 $ $Name: not supported by cvs2svn $ 9 * @date $Date: 2004-08-07 00:06:06 $ 9 10 * 10 11 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 static bool p_fftwWisdomImported = false; 28 29 29 psImage * psImageFFT( psImage* out, const psImage* in, psFftDirection direction)30 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction) 30 31 { 31 32 unsigned int numCols; … … 35 36 36 37 /* got good image data? */ 37 if ( in == NULL ) { 38 psFree( out ); 39 return NULL; 40 } 41 42 type = in->type.type; 43 44 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 45 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 46 type ); 47 psFree( out ); 48 return NULL; 49 } 50 51 if ( type != PS_TYPE_C32 && direction == PS_FFT_REVERSE ) { 52 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 53 type ); 54 psFree( out ); 55 return NULL; 56 57 } 58 59 if ( type != PS_TYPE_F32 && direction == PS_FFT_FORWARD ) { 60 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 61 type ); 62 psFree( out ); 38 if (in == NULL) { 39 psFree(out); 40 return NULL; 41 } 42 43 type = in->type.type; 44 45 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 46 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 47 psFree(out); 48 return NULL; 49 } 50 51 if (type != PS_TYPE_C32 && direction == PS_FFT_REVERSE) { 52 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 53 psFree(out); 54 return NULL; 55 56 } 57 58 if (type != PS_TYPE_F32 && direction == PS_FFT_FORWARD) { 59 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 60 psFree(out); 63 61 return NULL; 64 62 } 65 63 66 64 /* make sure the system-level wisdom information is imported. */ 67 if ( ! p_fftwWisdomImported) {65 if (!p_fftwWisdomImported) { 68 66 fftwf_import_system_wisdom(); 69 67 p_fftwWisdomImported = true; … … 73 71 numCols = in->numCols; 74 72 75 out = psImageCopy( out, in, PS_TYPE_C32 ); 76 77 plan = fftwf_plan_dft_2d( numCols, numRows, 78 ( fftwf_complex* ) out->data.C32[ 0 ], 79 ( fftwf_complex* ) out->data.C32[ 0 ], 80 direction, 81 P_FFTW_PLAN_RIGOR ); 82 83 /* check if a plan exists now*/ 84 if ( plan == NULL ) { 85 psError( __func__, "Failed to create FFTW plan." ); 86 psFree( out ); 73 out = psImageCopy(out, in, PS_TYPE_C32); 74 75 plan = fftwf_plan_dft_2d(numCols, numRows, 76 (fftwf_complex *) out->data.C32[0], 77 (fftwf_complex *) out->data.C32[0], direction, P_FFTW_PLAN_RIGOR); 78 79 /* check if a plan exists now */ 80 if (plan == NULL) { 81 psError(__func__, "Failed to create FFTW plan."); 82 psFree(out); 87 83 return NULL; 88 84 } 89 85 90 86 /* finally, call FFTW with the plan made above */ 91 fftwf_execute( plan ); 92 93 fftwf_destroy_plan( plan ); 94 95 return out; 96 97 } 98 99 100 psImage *psImageReal( psImage *out, const psImage* in ) 87 fftwf_execute(plan); 88 89 fftwf_destroy_plan(plan); 90 91 return out; 92 93 } 94 95 psImage *psImageReal(psImage * out, const psImage * in) 101 96 { 102 97 psElemType type; … … 104 99 unsigned int numRows; 105 100 106 107 if ( in == NULL ) { 108 psFree( out ); 101 if (in == NULL) { 102 psFree(out); 109 103 return NULL; 110 104 } … … 115 109 116 110 /* if not a complex number, this is logically just a copy */ 117 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {111 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 118 112 // Warn user, as this is probably not expected 119 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 120 "Just an image copy was performed." ); 121 return psImageCopy( out, in, type ); 122 } 123 124 if ( type == PS_TYPE_C32 ) { 125 psF32 * outRow; 126 psC32* inRow; 127 128 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 129 for ( unsigned int row = 0;row < numRows;row++ ) { 130 outRow = out->data.F32[ row ]; 131 inRow = in->data.C32[ row ]; 132 133 for ( unsigned int col = 0;col < numCols;col++ ) { 134 outRow[ col ] = crealf( inRow[ col ] ); 135 } 136 } 137 } else 138 if ( type == PS_TYPE_C64 ) { 139 psF64 * outRow; 140 psC64* inRow; 141 142 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 143 for ( unsigned int row = 0;row < numRows;row++ ) { 144 outRow = out->data.F64[ row ]; 145 inRow = in->data.C64[ row ]; 146 147 for ( unsigned int col = 0;col < numCols;col++ ) { 148 outRow[ col ] = creal( inRow[ col ] ); 149 } 150 } 151 } else { 152 psError( __func__, "Can not extract real component from given image type (%d).", 153 type ); 154 psFree( out ); 155 return NULL; 156 } 157 158 return out; 159 } 160 161 psImage *psImageImaginary( psImage *out, const psImage* in ) 113 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 114 "Just an image copy was performed."); 115 return psImageCopy(out, in, type); 116 } 117 118 if (type == PS_TYPE_C32) { 119 psF32 *outRow; 120 psC32 *inRow; 121 122 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 123 for (unsigned int row = 0; row < numRows; row++) { 124 outRow = out->data.F32[row]; 125 inRow = in->data.C32[row]; 126 127 for (unsigned int col = 0; col < numCols; col++) { 128 outRow[col] = crealf(inRow[col]); 129 } 130 } 131 } else if (type == PS_TYPE_C64) { 132 psF64 *outRow; 133 psC64 *inRow; 134 135 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 136 for (unsigned int row = 0; row < numRows; row++) { 137 outRow = out->data.F64[row]; 138 inRow = in->data.C64[row]; 139 140 for (unsigned int col = 0; col < numCols; col++) { 141 outRow[col] = creal(inRow[col]); 142 } 143 } 144 } else { 145 psError(__func__, "Can not extract real component from given image type (%d).", type); 146 psFree(out); 147 return NULL; 148 } 149 150 return out; 151 } 152 153 psImage *psImageImaginary(psImage * out, const psImage * in) 162 154 { 163 155 psElemType type; … … 165 157 unsigned int numRows; 166 158 167 168 if ( in == NULL ) { 169 psFree( out ); 159 if (in == NULL) { 160 psFree(out); 170 161 return NULL; 171 162 } … … 176 167 177 168 /* if not a complex number, this is logically just zeroed image of same size */ 178 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {169 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 179 170 // Warn user, as this is probably not expected 180 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "181 "A zero image was returned.");182 out = psImageRecycle( out, numCols, numRows, type);183 memset( out->data.V[ 0 ], 0, PSELEMTYPE_SIZEOF( type ) * numCols * numRows);171 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 172 "A zero image was returned."); 173 out = psImageRecycle(out, numCols, numRows, type); 174 memset(out->data.V[0], 0, PSELEMTYPE_SIZEOF(type) * numCols * numRows); 184 175 return out; 185 176 } 186 177 187 if ( type == PS_TYPE_C32 ) { 188 psF32 * outRow; 189 psC32* inRow; 190 191 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 192 for ( unsigned int row = 0;row < numRows;row++ ) { 193 outRow = out->data.F32[ row ]; 194 inRow = in->data.C32[ row ]; 195 196 for ( unsigned int col = 0;col < numCols;col++ ) { 197 outRow[ col ] = cimagf( inRow[ col ] ); 198 } 199 } 200 } else 201 if ( type == PS_TYPE_C64 ) { 202 psF64 * outRow; 203 psC64* inRow; 204 205 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 206 for ( unsigned int row = 0;row < numRows;row++ ) { 207 outRow = out->data.F64[ row ]; 208 inRow = in->data.C64[ row ]; 209 210 for ( unsigned int col = 0;col < numCols;col++ ) { 211 outRow[ col ] = cimag( inRow[ col ] ); 212 } 213 } 214 } else { 215 psError( __func__, "Can not extract imaginary component from given image type (%d).", 216 type ); 217 psFree( out ); 218 return NULL; 219 } 220 221 return out; 222 } 223 224 psImage *psImageComplex( psImage* out, psImage *real, const psImage *imag ) 178 if (type == PS_TYPE_C32) { 179 psF32 *outRow; 180 psC32 *inRow; 181 182 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 183 for (unsigned int row = 0; row < numRows; row++) { 184 outRow = out->data.F32[row]; 185 inRow = in->data.C32[row]; 186 187 for (unsigned int col = 0; col < numCols; col++) { 188 outRow[col] = cimagf(inRow[col]); 189 } 190 } 191 } else if (type == PS_TYPE_C64) { 192 psF64 *outRow; 193 psC64 *inRow; 194 195 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 196 for (unsigned int row = 0; row < numRows; row++) { 197 outRow = out->data.F64[row]; 198 inRow = in->data.C64[row]; 199 200 for (unsigned int col = 0; col < numCols; col++) { 201 outRow[col] = cimag(inRow[col]); 202 } 203 } 204 } else { 205 psError(__func__, "Can not extract imaginary component from given image type (%d).", type); 206 psFree(out); 207 return NULL; 208 } 209 210 return out; 211 } 212 213 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag) 225 214 { 226 215 psElemType type; … … 228 217 unsigned int numRows; 229 218 230 231 if ( real == NULL || imag == NULL ) { 232 psFree( out ); 219 if (real == NULL || imag == NULL) { 220 psFree(out); 233 221 return NULL; 234 222 } … … 238 226 numRows = real->numRows; 239 227 240 if ( imag->type.type != type ) { 241 psError( __func__, "The inputs to psImageComplex must be the same type." ); 242 psFree( out ); 243 return NULL; 244 } 245 246 if ( imag->numCols != numCols || 247 imag->numRows != numRows ) { 248 psError( __func__, "The inputs to psImageComplex must be the same dimensions." ); 249 psFree( out ); 250 return NULL; 251 } 252 253 if ( PS_IS_PSELEMTYPE_COMPLEX( type ) ) { 254 psError( __func__, "The inputs to psImageComplex can not be complex." ); 255 psFree( out ); 256 return NULL; 257 } 258 259 if ( type != PS_TYPE_F32 && type != PS_TYPE_F64 ) { 260 psError( __func__, "The input type to psImageComplex must be a floating point." ); 261 psFree( out ); 262 return NULL; 263 } 264 265 if ( type == PS_TYPE_F32 ) { 266 psC32 * outRow; 267 psF32* realRow; 268 psF32* imagRow; 269 270 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 271 272 for ( unsigned int row = 0;row < numRows;row++ ) { 273 outRow = out->data.C32[ row ]; 274 realRow = real->data.F32[ row ]; 275 imagRow = imag->data.F32[ row ]; 276 277 for ( unsigned int col = 0;col < numCols;col++ ) { 278 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 279 } 280 } 281 } else 282 if ( type == PS_TYPE_F64 ) { 283 psC64 * outRow; 284 psF64* realRow; 285 psF64* imagRow; 286 287 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 288 for ( unsigned int row = 0;row < numRows;row++ ) { 289 outRow = out->data.C64[ row ]; 290 realRow = real->data.F64[ row ]; 291 imagRow = imag->data.F64[ row ]; 292 293 for ( unsigned int col = 0;col < numCols;col++ ) { 294 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 295 } 296 } 297 } else { 298 psError( __func__, "Can not merge real and imaginary portions for given image type (%d).", 299 type ); 300 psFree( out ); 301 return NULL; 302 } 303 304 return out; 305 } 306 307 psImage *psImageConjugate( psImage *out, const psImage *in ) 228 if (imag->type.type != type) { 229 psError(__func__, "The inputs to psImageComplex must be the same type."); 230 psFree(out); 231 return NULL; 232 } 233 234 if (imag->numCols != numCols || imag->numRows != numRows) { 235 psError(__func__, "The inputs to psImageComplex must be the same dimensions."); 236 psFree(out); 237 return NULL; 238 } 239 240 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 241 psError(__func__, "The inputs to psImageComplex can not be complex."); 242 psFree(out); 243 return NULL; 244 } 245 246 if (type != PS_TYPE_F32 && type != PS_TYPE_F64) { 247 psError(__func__, "The input type to psImageComplex must be a floating point."); 248 psFree(out); 249 return NULL; 250 } 251 252 if (type == PS_TYPE_F32) { 253 psC32 *outRow; 254 psF32 *realRow; 255 psF32 *imagRow; 256 257 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 258 259 for (unsigned int row = 0; row < numRows; row++) { 260 outRow = out->data.C32[row]; 261 realRow = real->data.F32[row]; 262 imagRow = imag->data.F32[row]; 263 264 for (unsigned int col = 0; col < numCols; col++) { 265 outRow[col] = realRow[col] + I * imagRow[col]; 266 } 267 } 268 } else if (type == PS_TYPE_F64) { 269 psC64 *outRow; 270 psF64 *realRow; 271 psF64 *imagRow; 272 273 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 274 for (unsigned int row = 0; row < numRows; row++) { 275 outRow = out->data.C64[row]; 276 realRow = real->data.F64[row]; 277 imagRow = imag->data.F64[row]; 278 279 for (unsigned int col = 0; col < numCols; col++) { 280 outRow[col] = realRow[col] + I * imagRow[col]; 281 } 282 } 283 } else { 284 psError(__func__, "Can not merge real and imaginary portions for given image type (%d).", type); 285 psFree(out); 286 return NULL; 287 } 288 289 return out; 290 } 291 292 psImage *psImageConjugate(psImage * out, const psImage * in) 308 293 { 309 294 psElemType type; … … 311 296 unsigned int numRows; 312 297 313 314 if ( in == NULL ) { 315 psFree( out ); 298 if (in == NULL) { 299 psFree(out); 316 300 return NULL; 317 301 } … … 322 306 323 307 /* if not a complex number, this is logically just a image copy */ 324 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {308 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 325 309 // Warn user, as this is probably not expected 326 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 327 "Image copy was performed instead." ); 328 return psImageCopy( out, in, type ); 329 } 330 331 if ( type == PS_TYPE_C32 ) { 332 psC32 * outRow; 333 psC32* inRow; 334 335 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 336 for ( unsigned int row = 0;row < numRows;row++ ) { 337 outRow = out->data.C32[ row ]; 338 inRow = in->data.C32[ row ]; 339 340 for ( unsigned int col = 0;col < numCols;col++ ) { 341 outRow[ col ] = crealf( inRow[ col ] ) - I * cimagf( inRow[ col ] ); 342 } 343 } 344 } else 345 if ( type == PS_TYPE_C64 ) { 346 psC64 * outRow; 347 psC64* inRow; 348 349 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 350 for ( unsigned int row = 0;row < numRows;row++ ) { 351 outRow = out->data.C64[ row ]; 352 inRow = in->data.C64[ row ]; 353 354 for ( unsigned int col = 0;col < numCols;col++ ) { 355 outRow[ col ] = creal( inRow[ col ] ) - I * cimag( inRow[ col ] ); 356 } 357 } 358 } else { 359 psError( __func__, "Can not compute complex conjugate for given image type (%d).", 360 type ); 361 psFree( out ); 362 return NULL; 363 } 364 365 return out; 366 } 367 368 psImage *psImagePowerSpectrum( psImage* out, const psImage* in ) 310 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 311 "Image copy was performed instead."); 312 return psImageCopy(out, in, type); 313 } 314 315 if (type == PS_TYPE_C32) { 316 psC32 *outRow; 317 psC32 *inRow; 318 319 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 320 for (unsigned int row = 0; row < numRows; row++) { 321 outRow = out->data.C32[row]; 322 inRow = in->data.C32[row]; 323 324 for (unsigned int col = 0; col < numCols; col++) { 325 outRow[col] = crealf(inRow[col]) - I * cimagf(inRow[col]); 326 } 327 } 328 } else if (type == PS_TYPE_C64) { 329 psC64 *outRow; 330 psC64 *inRow; 331 332 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 333 for (unsigned int row = 0; row < numRows; row++) { 334 outRow = out->data.C64[row]; 335 inRow = in->data.C64[row]; 336 337 for (unsigned int col = 0; col < numCols; col++) { 338 outRow[col] = creal(inRow[col]) - I * cimag(inRow[col]); 339 } 340 } 341 } else { 342 psError(__func__, "Can not compute complex conjugate for given image type (%d).", type); 343 psFree(out); 344 return NULL; 345 } 346 347 return out; 348 } 349 350 psImage *psImagePowerSpectrum(psImage * out, const psImage * in) 369 351 { 370 352 psElemType type; … … 373 355 int numElementsSquared; 374 356 375 if ( in == NULL) {376 psFree( out);357 if (in == NULL) { 358 psFree(out); 377 359 return NULL; 378 360 } … … 384 366 385 367 /* if not a complex number, this is not implemented */ 386 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {387 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");388 psFree( out);389 return NULL; 390 } 391 392 if ( type == PS_TYPE_C32) {393 psF32 * outRow;394 psC32 *inRow;368 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 369 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 370 psFree(out); 371 return NULL; 372 } 373 374 if (type == PS_TYPE_C32) { 375 psF32 *outRow; 376 psC32 *inRow; 395 377 psF32 real; 396 378 psF32 imag; 397 379 398 399 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 400 for ( unsigned int row = 0;row < numRows;row++ ) { 401 outRow = out->data.F32[ row ]; 402 inRow = in->data.C32[ row ]; 403 404 for ( unsigned int col = 0;col < numCols;col++ ) { 405 real = crealf( inRow[ col ] ); 406 imag = cimagf( inRow[ col ] ); 407 outRow[ col ] = ( real * real + imag * imag ) / numElementsSquared; 408 } 409 } 410 } else 411 if ( type == PS_TYPE_C64 ) { 412 psF64 * outRow; 413 psC64* inRow; 414 psF64 real; 415 psF64 imag; 416 417 418 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 419 for ( unsigned int row = 0;row < numRows;row++ ) { 420 outRow = out->data.F64[ row ]; 421 inRow = in->data.C64[ row ]; 422 423 for ( unsigned int col = 0;col < numCols;col++ ) { 424 real = crealf( inRow[ col ] ); 425 imag = cimagf( inRow[ col ] ); 426 outRow[ col ] = real * real + imag * imag / numElementsSquared; 427 } 428 } 429 } else { 430 psError( __func__, "Can not power spectrum for given image type (%d).", 431 type ); 432 psFree( out ); 433 return NULL; 434 } 380 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 381 for (unsigned int row = 0; row < numRows; row++) { 382 outRow = out->data.F32[row]; 383 inRow = in->data.C32[row]; 384 385 for (unsigned int col = 0; col < numCols; col++) { 386 real = crealf(inRow[col]); 387 imag = cimagf(inRow[col]); 388 outRow[col] = (real * real + imag * imag) / numElementsSquared; 389 } 390 } 391 } else if (type == PS_TYPE_C64) { 392 psF64 *outRow; 393 psC64 *inRow; 394 psF64 real; 395 psF64 imag; 396 397 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 398 for (unsigned int row = 0; row < numRows; row++) { 399 outRow = out->data.F64[row]; 400 inRow = in->data.C64[row]; 401 402 for (unsigned int col = 0; col < numCols; col++) { 403 real = crealf(inRow[col]); 404 imag = cimagf(inRow[col]); 405 outRow[col] = real * real + imag * imag / numElementsSquared; 406 } 407 } 408 } else { 409 psError(__func__, "Can not power spectrum for given image type (%d).", type); 410 psFree(out); 411 return NULL; 412 } 435 413 436 414 return out; … … 440 418 /************************************** Vector Functions ***************************************/ 441 419 442 psVector * psVectorFFT( psVector* out, const psVector* in, psFftDirection direction)420 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction) 443 421 { 444 422 unsigned int numElements; … … 447 425 448 426 /* got good image data? */ 449 if ( in == NULL ) { 450 psFree( out ); 451 return NULL; 452 } 453 454 type = in->type.type; 455 456 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 457 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 458 type ); 459 psFree( out ); 460 return NULL; 461 } 462 463 if ( ( type != PS_TYPE_C32 ) && ( direction == PS_FFT_REVERSE ) ) { 464 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 465 type ); 466 psFree( out ); 467 return NULL; 468 469 } 470 471 if ( ( type != PS_TYPE_F32 ) && ( direction == PS_FFT_FORWARD ) ) { 472 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 473 type ); 474 psFree( out ); 427 if (in == NULL) { 428 psFree(out); 429 return NULL; 430 } 431 432 type = in->type.type; 433 434 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 435 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 436 psFree(out); 437 return NULL; 438 } 439 440 if ((type != PS_TYPE_C32) && (direction == PS_FFT_REVERSE)) { 441 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 442 psFree(out); 443 return NULL; 444 445 } 446 447 if ((type != PS_TYPE_F32) && (direction == PS_FFT_FORWARD)) { 448 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 449 psFree(out); 475 450 return NULL; 476 451 } 477 452 478 453 /* make sure the system-level wisdom information is imported. */ 479 if ( ! p_fftwWisdomImported) {454 if (!p_fftwWisdomImported) { 480 455 fftwf_import_system_wisdom(); 481 456 p_fftwWisdomImported = true; … … 484 459 numElements = in->n; 485 460 486 out = psVectorRecycle( out, numElements, PS_TYPE_C32);461 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 487 462 out->n = numElements; 488 463 489 if ( type == PS_TYPE_F32) {464 if (type == PS_TYPE_F32) { 490 465 // need to convert to complex 491 psC32 * outVec = out->data.C32;492 psF32 *inVec = in->data.F32;493 for ( unsigned int i = 0;i < numElements;i++ ) { 494 outVec[ i ] = inVec[ i ];495 }496 } else {497 psC32* outVec = out->data.C32;498 psC32 * inVec = in->data.C32;499 for ( unsigned int i = 0;i < numElements;i++ ) {500 outVec[ i ] = inVec[ i ]; 501 }502 }503 504 plan = fftwf_plan_dft_1d( numElements,505 ( fftwf_complex* ) out->data.C32, 506 ( fftwf_complex* ) out->data.C32,507 direction,508 P_FFTW_PLAN_RIGOR);509 510 /* check if a plan exists now */511 if ( plan == NULL) {512 psError( __func__, "Failed to create FFTW plan.");513 psFree( out);466 psC32 *outVec = out->data.C32; 467 psF32 *inVec = in->data.F32; 468 469 for (unsigned int i = 0; i < numElements; i++) { 470 outVec[i] = inVec[i]; 471 } 472 } else { 473 psC32 *outVec = out->data.C32; 474 psC32 *inVec = in->data.C32; 475 476 for (unsigned int i = 0; i < numElements; i++) { 477 outVec[i] = inVec[i]; 478 } 479 } 480 481 plan = fftwf_plan_dft_1d(numElements, 482 (fftwf_complex *) out->data.C32, 483 (fftwf_complex *) out->data.C32, direction, P_FFTW_PLAN_RIGOR); 484 485 /* check if a plan exists now */ 486 if (plan == NULL) { 487 psError(__func__, "Failed to create FFTW plan."); 488 psFree(out); 514 489 return NULL; 515 490 } 516 491 517 492 /* finally, call FFTW with the plan made above */ 518 fftwf_execute( plan ); 519 520 fftwf_destroy_plan( plan ); 521 522 return out; 523 } 524 525 526 psVector *psVectorReal( psVector *out, const psVector* in ) 493 fftwf_execute(plan); 494 495 fftwf_destroy_plan(plan); 496 497 return out; 498 } 499 500 psVector *psVectorReal(psVector * out, const psVector * in) 527 501 { 528 502 psElemType type; 529 503 unsigned int numElements; 530 504 531 if ( in == NULL) {532 psFree( out);505 if (in == NULL) { 506 psFree(out); 533 507 return NULL; 534 508 } … … 538 512 539 513 /* if not a complex number, this is logically just a copy */ 540 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {514 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 541 515 // Warn user, as this is probably not expected 542 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. "543 "Just a vector copy was performed.");544 out = psVectorRecycle( out, numElements, type);516 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 517 "Just a vector copy was performed."); 518 out = psVectorRecycle(out, numElements, type); 545 519 out->n = numElements; 546 memcpy( out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF( type ));520 memcpy(out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF(type)); 547 521 return out; 548 522 } 549 523 550 if ( type == PS_TYPE_C32) {551 psF32 * outVec;552 psC32 *inVec = in->data.C32;553 554 out = psVectorRecycle( out, numElements, PS_TYPE_F32);524 if (type == PS_TYPE_C32) { 525 psF32 *outVec; 526 psC32 *inVec = in->data.C32; 527 528 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 555 529 out->n = numElements; 556 530 outVec = out->data.F32; 557 531 558 for ( unsigned int i = 0;i < numElements;i++ ) { 559 outVec[ i ] = crealf( inVec[ i ] ); 560 } 561 } else { 562 psError( __func__, "Can not extract real component from given vector type (%d).", 563 type ); 564 psFree( out ); 565 return NULL; 566 } 567 568 return out; 569 } 570 571 psVector *psVectorImaginary( psVector *out, const psVector* in ) 532 for (unsigned int i = 0; i < numElements; i++) { 533 outVec[i] = crealf(inVec[i]); 534 } 535 } else { 536 psError(__func__, "Can not extract real component from given vector type (%d).", type); 537 psFree(out); 538 return NULL; 539 } 540 541 return out; 542 } 543 544 psVector *psVectorImaginary(psVector * out, const psVector * in) 572 545 { 573 546 psElemType type; 574 547 unsigned int numElements; 575 548 576 577 if ( in == NULL ) { 578 psFree( out ); 549 if (in == NULL) { 550 psFree(out); 579 551 return NULL; 580 552 } … … 584 556 585 557 /* if not a complex number, this is logically just zeroed image of same size */ 586 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {558 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 587 559 // Warn user, as this is probably not expected 588 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "589 "A zeroed vector was returned.");590 out = psVectorRecycle( out, numElements, type);560 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 561 "A zeroed vector was returned."); 562 out = psVectorRecycle(out, numElements, type); 591 563 out->n = numElements; 592 memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements);564 memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements); 593 565 return out; 594 566 } 595 567 596 if ( type == PS_TYPE_C32) {597 psF32 * outVec;598 psC32 *inVec = in->data.C32;599 600 out = psVectorRecycle( out, numElements, PS_TYPE_F32);568 if (type == PS_TYPE_C32) { 569 psF32 *outVec; 570 psC32 *inVec = in->data.C32; 571 572 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 601 573 out->n = numElements; 602 574 outVec = out->data.F32; 603 575 604 for ( unsigned int i = 0;i < numElements;i++ ) { 605 outVec[ i ] = cimagf( inVec[ i ] ); 606 } 607 } else { 608 psError( __func__, "Can not extract imaginary component from given vector type (%d).", 609 type ); 610 psFree( out ); 611 return NULL; 612 } 613 614 return out; 615 } 616 617 psVector *psVectorComplex( psVector* out, psVector *real, const psVector *imag ) 576 for (unsigned int i = 0; i < numElements; i++) { 577 outVec[i] = cimagf(inVec[i]); 578 } 579 } else { 580 psError(__func__, "Can not extract imaginary component from given vector type (%d).", type); 581 psFree(out); 582 return NULL; 583 } 584 585 return out; 586 } 587 588 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag) 618 589 { 619 590 psElemType type; 620 591 unsigned int numElements; 621 592 622 623 if ( real == NULL || imag == NULL ) { 624 psFree( out ); 593 if (real == NULL || imag == NULL) { 594 psFree(out); 625 595 return NULL; 626 596 } 627 597 628 598 type = real->type.type; 629 if ( real->n < imag->n) {599 if (real->n < imag->n) { 630 600 numElements = real->n; 631 601 } else { … … 633 603 } 634 604 635 if ( imag->type.type != type) {636 psError( __func__, "The inputs to psVectorComplex must be the same type.");637 psFree( out);638 return NULL; 639 } 640 641 if ( PS_IS_PSELEMTYPE_COMPLEX( type )) {642 psError( __func__, "The inputs to psVectorComplex can not be complex.");643 psFree( out);644 return NULL; 645 } 646 647 if ( type == PS_TYPE_F32) {648 psC32 * outVec;649 psF32 *realVec = real->data.F32;650 psF32 *imagVec = imag->data.F32;651 652 out = psVectorRecycle( out, numElements, PS_TYPE_C32);605 if (imag->type.type != type) { 606 psError(__func__, "The inputs to psVectorComplex must be the same type."); 607 psFree(out); 608 return NULL; 609 } 610 611 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 612 psError(__func__, "The inputs to psVectorComplex can not be complex."); 613 psFree(out); 614 return NULL; 615 } 616 617 if (type == PS_TYPE_F32) { 618 psC32 *outVec; 619 psF32 *realVec = real->data.F32; 620 psF32 *imagVec = imag->data.F32; 621 622 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 653 623 out->n = numElements; 654 624 outVec = out->data.C32; 655 625 656 for ( unsigned int i = 0;i < numElements;i++ ) { 657 outVec[ i ] = realVec[ i ] + I * imagVec[ i ]; 658 } 659 } else { 660 psError( __func__, "Can not merge real and imaginary portions for given vector type (%d).", 661 type ); 662 psFree( out ); 663 return NULL; 664 } 665 666 return out; 667 } 668 669 psVector *psVectorConjugate( psVector *out, const psVector *in ) 626 for (unsigned int i = 0; i < numElements; i++) { 627 outVec[i] = realVec[i] + I * imagVec[i]; 628 } 629 } else { 630 psError(__func__, "Can not merge real and imaginary portions for given vector type (%d).", type); 631 psFree(out); 632 return NULL; 633 } 634 635 return out; 636 } 637 638 psVector *psVectorConjugate(psVector * out, const psVector * in) 670 639 { 671 640 psElemType type; 672 641 unsigned int numElements; 673 642 674 675 if ( in == NULL ) { 676 psFree( out ); 643 if (in == NULL) { 644 psFree(out); 677 645 return NULL; 678 646 } … … 682 650 683 651 /* if not a complex number, this is logically just a image copy */ 684 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {652 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 685 653 // Warn user, as this is probably not expected 686 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. "687 "Vector copy was performed instead.");688 689 out = psVectorRecycle( out, numElements, type);654 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 655 "Vector copy was performed instead."); 656 657 out = psVectorRecycle(out, numElements, type); 690 658 out->n = numElements; 691 memcpy( out->data.V, in->data.V, PSELEMTYPE_SIZEOF( type ) * numElements);659 memcpy(out->data.V, in->data.V, PSELEMTYPE_SIZEOF(type) * numElements); 692 660 return out; 693 661 } 694 662 695 if ( type == PS_TYPE_C32) {696 psC32 * outVec;697 psC32 *inVec = in->data.C32;698 699 out = psVectorRecycle( out, numElements, PS_TYPE_C32);663 if (type == PS_TYPE_C32) { 664 psC32 *outVec; 665 psC32 *inVec = in->data.C32; 666 667 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 700 668 out->n = numElements; 701 669 outVec = out->data.C32; 702 670 703 for ( unsigned int i = 0;i < numElements;i++ ) { 704 outVec[ i ] = crealf( inVec[ i ] ) - I * cimagf( inVec[ i ] ); 705 } 706 } else { 707 psError( __func__, "Can not compute complex conjugate for given vector type (%d).", 708 type ); 709 psFree( out ); 710 return NULL; 711 } 712 713 return out; 714 } 715 716 psVector *psVectorPowerSpectrum( psVector* out, const psVector* in ) 671 for (unsigned int i = 0; i < numElements; i++) { 672 outVec[i] = crealf(inVec[i]) - I * cimagf(inVec[i]); 673 } 674 } else { 675 psError(__func__, "Can not compute complex conjugate for given vector type (%d).", type); 676 psFree(out); 677 return NULL; 678 } 679 680 return out; 681 } 682 683 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in) 717 684 { 718 685 psElemType type; … … 722 689 unsigned int inNumElementsSquared; 723 690 724 if ( in == NULL) {725 psFree( out);691 if (in == NULL) { 692 psFree(out); 726 693 return NULL; 727 694 } … … 734 701 735 702 /* if not a complex number, this is not implemented */ 736 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {737 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");738 psFree( out);739 return NULL; 740 } 741 742 if ( type == PS_TYPE_C32) {743 psF32 * outVec;744 psC32 *inVec = in->data.C32;703 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 704 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 705 psFree(out); 706 return NULL; 707 } 708 709 if (type == PS_TYPE_C32) { 710 psF32 *outVec; 711 psC32 *inVec = in->data.C32; 745 712 psF32 inAbs1; 746 713 psF32 inAbs2; 747 714 748 out = psVectorRecycle( out, outNumElements, PS_TYPE_F32);715 out = psVectorRecycle(out, outNumElements, PS_TYPE_F32); 749 716 out->n = outNumElements; 750 717 outVec = out->data.F32; 751 718 752 719 // from ADD: P_0 = |C_0|^2/N^2 753 inAbs1 = cabsf( inVec[ 0 ]);754 outVec[ 0] = inAbs1 * inAbs1 / inNumElementsSquared;720 inAbs1 = cabsf(inVec[0]); 721 outVec[0] = inAbs1 * inAbs1 / inNumElementsSquared; 755 722 756 723 // from ADD: P_j = (|C_j|^2+|C_N-j|^2)/N^2, where j = 1,2,...,(N/2-1) 757 for ( unsigned int i = 1;i < inHalfNumElements;i++) {758 inAbs1 = cabsf( inVec[ i ]);759 inAbs2 = cabsf( inVec[ inNumElements - i ]);760 outVec[ i ] = ( inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared;724 for (unsigned int i = 1; i < inHalfNumElements; i++) { 725 inAbs1 = cabsf(inVec[i]); 726 inAbs2 = cabsf(inVec[inNumElements - i]); 727 outVec[i] = (inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared; 761 728 } 762 729 763 730 // from ADD: P_N/2 = |C_N/2|^2/N^2 764 inAbs1 = cabsf( inVec[ inHalfNumElements ] ); 765 outVec[ inHalfNumElements ] = inAbs1 * inAbs1 / inNumElementsSquared; 766 } else { 767 psError( __func__, "Can not power spectrum for given vector type (%d).", 768 type ); 769 psFree( out ); 770 return NULL; 771 } 772 773 return out; 774 775 } 731 inAbs1 = cabsf(inVec[inHalfNumElements]); 732 outVec[inHalfNumElements] = inAbs1 * inAbs1 / inNumElementsSquared; 733 } else { 734 psError(__func__, "Can not power spectrum for given vector type (%d).", type); 735 psFree(out); 736 return NULL; 737 } 738 739 return out; 740 741 } -
trunk/psLib/src/dataManip/psVectorFFT.h
r1406 r1407 1 1 2 /** @file psFFT.h 2 3 * … … 7 8 * @author Robert DeSonia, MHPCC 8 9 * 9 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 14 15 15 16 #ifndef PS_FFT_H 16 # define PS_FFT_H17 # define PS_FFT_H 17 18 18 # include "psImage.h"19 # include "psVector.h"19 # include "psImage.h" 20 # include "psVector.h" 20 21 21 22 /// @addtogroup Transform … … 24 25 /** Details on FFT implementation (private). */ 25 26 26 27 27 typedef enum { 28 // / psImageFFT/psVectorFFT should perform a forward FFT.28 // / psImageFFT/psVectorFFT should perform a forward FFT. 29 29 PS_FFT_FORWARD = (-1), 30 30 31 // /< psImageFFT/psVectorFFT should perform a reverse FFT.31 // /< psImageFFT/psVectorFFT should perform a reverse FFT. 32 32 PS_FFT_REVERSE = (+1) 33 33 } psFftDirection; 34 34 35 psImage * psImageFFT(psImage* out, const psImage* in, psFftDirection direction);36 psImage * psImageReal(psImage *out, const psImage* in);37 psImage * psImageImaginary(psImage *out, const psImage* in);38 psImage * psImageComplex(psImage* out, psImage *real, const psImage *imag);39 psImage * psImageConjugate(psImage *out, const psImage *in);40 psImage * psImagePowerSpectrum(psImage* out, const psImage* in);35 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction); 36 psImage *psImageReal(psImage * out, const psImage * in); 37 psImage *psImageImaginary(psImage * out, const psImage * in); 38 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag); 39 psImage *psImageConjugate(psImage * out, const psImage * in); 40 psImage *psImagePowerSpectrum(psImage * out, const psImage * in); 41 41 42 psVector * psVectorFFT(psVector* out, const psVector* in, psFftDirection direction);43 psVector * psVectorReal(psVector* out, const psVector* in);44 psVector * psVectorImaginary(psVector* out, const psVector* in);45 psVector * psVectorComplex(psVector* out, psVector* real, const psVector* imag);46 psVector * psVectorConjugate(psVector* out, const psVector* in);47 psVector * psVectorPowerSpectrum(psVector* out, const psVector* in);42 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction); 43 psVector *psVectorReal(psVector * out, const psVector * in); 44 psVector *psVectorImaginary(psVector * out, const psVector * in); 45 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag); 46 psVector *psVectorConjugate(psVector * out, const psVector * in); 47 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in); 48 48 49 49 /// @} 50 50 51 51 #endif 52 -
trunk/psLib/src/fft/psVectorFFT.c
r1406 r1407 1 1 2 /** @file psFFT.c 2 3 * … … 5 6 * @author Robert DeSonia, MHPCC 6 7 * 7 * @version $Revision: 1.1 8$ $Name: not supported by cvs2svn $8 * @date $Date: 2004-08-0 6 22:34:05$8 * @version $Revision: 1.19 $ $Name: not supported by cvs2svn $ 9 * @date $Date: 2004-08-07 00:06:06 $ 9 10 * 10 11 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 static bool p_fftwWisdomImported = false; 28 29 29 psImage * psImageFFT( psImage* out, const psImage* in, psFftDirection direction)30 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction) 30 31 { 31 32 unsigned int numCols; … … 35 36 36 37 /* got good image data? */ 37 if ( in == NULL ) { 38 psFree( out ); 39 return NULL; 40 } 41 42 type = in->type.type; 43 44 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 45 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 46 type ); 47 psFree( out ); 48 return NULL; 49 } 50 51 if ( type != PS_TYPE_C32 && direction == PS_FFT_REVERSE ) { 52 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 53 type ); 54 psFree( out ); 55 return NULL; 56 57 } 58 59 if ( type != PS_TYPE_F32 && direction == PS_FFT_FORWARD ) { 60 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 61 type ); 62 psFree( out ); 38 if (in == NULL) { 39 psFree(out); 40 return NULL; 41 } 42 43 type = in->type.type; 44 45 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 46 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 47 psFree(out); 48 return NULL; 49 } 50 51 if (type != PS_TYPE_C32 && direction == PS_FFT_REVERSE) { 52 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 53 psFree(out); 54 return NULL; 55 56 } 57 58 if (type != PS_TYPE_F32 && direction == PS_FFT_FORWARD) { 59 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 60 psFree(out); 63 61 return NULL; 64 62 } 65 63 66 64 /* make sure the system-level wisdom information is imported. */ 67 if ( ! p_fftwWisdomImported) {65 if (!p_fftwWisdomImported) { 68 66 fftwf_import_system_wisdom(); 69 67 p_fftwWisdomImported = true; … … 73 71 numCols = in->numCols; 74 72 75 out = psImageCopy( out, in, PS_TYPE_C32 ); 76 77 plan = fftwf_plan_dft_2d( numCols, numRows, 78 ( fftwf_complex* ) out->data.C32[ 0 ], 79 ( fftwf_complex* ) out->data.C32[ 0 ], 80 direction, 81 P_FFTW_PLAN_RIGOR ); 82 83 /* check if a plan exists now*/ 84 if ( plan == NULL ) { 85 psError( __func__, "Failed to create FFTW plan." ); 86 psFree( out ); 73 out = psImageCopy(out, in, PS_TYPE_C32); 74 75 plan = fftwf_plan_dft_2d(numCols, numRows, 76 (fftwf_complex *) out->data.C32[0], 77 (fftwf_complex *) out->data.C32[0], direction, P_FFTW_PLAN_RIGOR); 78 79 /* check if a plan exists now */ 80 if (plan == NULL) { 81 psError(__func__, "Failed to create FFTW plan."); 82 psFree(out); 87 83 return NULL; 88 84 } 89 85 90 86 /* finally, call FFTW with the plan made above */ 91 fftwf_execute( plan ); 92 93 fftwf_destroy_plan( plan ); 94 95 return out; 96 97 } 98 99 100 psImage *psImageReal( psImage *out, const psImage* in ) 87 fftwf_execute(plan); 88 89 fftwf_destroy_plan(plan); 90 91 return out; 92 93 } 94 95 psImage *psImageReal(psImage * out, const psImage * in) 101 96 { 102 97 psElemType type; … … 104 99 unsigned int numRows; 105 100 106 107 if ( in == NULL ) { 108 psFree( out ); 101 if (in == NULL) { 102 psFree(out); 109 103 return NULL; 110 104 } … … 115 109 116 110 /* if not a complex number, this is logically just a copy */ 117 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {111 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 118 112 // Warn user, as this is probably not expected 119 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 120 "Just an image copy was performed." ); 121 return psImageCopy( out, in, type ); 122 } 123 124 if ( type == PS_TYPE_C32 ) { 125 psF32 * outRow; 126 psC32* inRow; 127 128 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 129 for ( unsigned int row = 0;row < numRows;row++ ) { 130 outRow = out->data.F32[ row ]; 131 inRow = in->data.C32[ row ]; 132 133 for ( unsigned int col = 0;col < numCols;col++ ) { 134 outRow[ col ] = crealf( inRow[ col ] ); 135 } 136 } 137 } else 138 if ( type == PS_TYPE_C64 ) { 139 psF64 * outRow; 140 psC64* inRow; 141 142 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 143 for ( unsigned int row = 0;row < numRows;row++ ) { 144 outRow = out->data.F64[ row ]; 145 inRow = in->data.C64[ row ]; 146 147 for ( unsigned int col = 0;col < numCols;col++ ) { 148 outRow[ col ] = creal( inRow[ col ] ); 149 } 150 } 151 } else { 152 psError( __func__, "Can not extract real component from given image type (%d).", 153 type ); 154 psFree( out ); 155 return NULL; 156 } 157 158 return out; 159 } 160 161 psImage *psImageImaginary( psImage *out, const psImage* in ) 113 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 114 "Just an image copy was performed."); 115 return psImageCopy(out, in, type); 116 } 117 118 if (type == PS_TYPE_C32) { 119 psF32 *outRow; 120 psC32 *inRow; 121 122 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 123 for (unsigned int row = 0; row < numRows; row++) { 124 outRow = out->data.F32[row]; 125 inRow = in->data.C32[row]; 126 127 for (unsigned int col = 0; col < numCols; col++) { 128 outRow[col] = crealf(inRow[col]); 129 } 130 } 131 } else if (type == PS_TYPE_C64) { 132 psF64 *outRow; 133 psC64 *inRow; 134 135 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 136 for (unsigned int row = 0; row < numRows; row++) { 137 outRow = out->data.F64[row]; 138 inRow = in->data.C64[row]; 139 140 for (unsigned int col = 0; col < numCols; col++) { 141 outRow[col] = creal(inRow[col]); 142 } 143 } 144 } else { 145 psError(__func__, "Can not extract real component from given image type (%d).", type); 146 psFree(out); 147 return NULL; 148 } 149 150 return out; 151 } 152 153 psImage *psImageImaginary(psImage * out, const psImage * in) 162 154 { 163 155 psElemType type; … … 165 157 unsigned int numRows; 166 158 167 168 if ( in == NULL ) { 169 psFree( out ); 159 if (in == NULL) { 160 psFree(out); 170 161 return NULL; 171 162 } … … 176 167 177 168 /* if not a complex number, this is logically just zeroed image of same size */ 178 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {169 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 179 170 // Warn user, as this is probably not expected 180 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "181 "A zero image was returned.");182 out = psImageRecycle( out, numCols, numRows, type);183 memset( out->data.V[ 0 ], 0, PSELEMTYPE_SIZEOF( type ) * numCols * numRows);171 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 172 "A zero image was returned."); 173 out = psImageRecycle(out, numCols, numRows, type); 174 memset(out->data.V[0], 0, PSELEMTYPE_SIZEOF(type) * numCols * numRows); 184 175 return out; 185 176 } 186 177 187 if ( type == PS_TYPE_C32 ) { 188 psF32 * outRow; 189 psC32* inRow; 190 191 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 192 for ( unsigned int row = 0;row < numRows;row++ ) { 193 outRow = out->data.F32[ row ]; 194 inRow = in->data.C32[ row ]; 195 196 for ( unsigned int col = 0;col < numCols;col++ ) { 197 outRow[ col ] = cimagf( inRow[ col ] ); 198 } 199 } 200 } else 201 if ( type == PS_TYPE_C64 ) { 202 psF64 * outRow; 203 psC64* inRow; 204 205 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 206 for ( unsigned int row = 0;row < numRows;row++ ) { 207 outRow = out->data.F64[ row ]; 208 inRow = in->data.C64[ row ]; 209 210 for ( unsigned int col = 0;col < numCols;col++ ) { 211 outRow[ col ] = cimag( inRow[ col ] ); 212 } 213 } 214 } else { 215 psError( __func__, "Can not extract imaginary component from given image type (%d).", 216 type ); 217 psFree( out ); 218 return NULL; 219 } 220 221 return out; 222 } 223 224 psImage *psImageComplex( psImage* out, psImage *real, const psImage *imag ) 178 if (type == PS_TYPE_C32) { 179 psF32 *outRow; 180 psC32 *inRow; 181 182 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 183 for (unsigned int row = 0; row < numRows; row++) { 184 outRow = out->data.F32[row]; 185 inRow = in->data.C32[row]; 186 187 for (unsigned int col = 0; col < numCols; col++) { 188 outRow[col] = cimagf(inRow[col]); 189 } 190 } 191 } else if (type == PS_TYPE_C64) { 192 psF64 *outRow; 193 psC64 *inRow; 194 195 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 196 for (unsigned int row = 0; row < numRows; row++) { 197 outRow = out->data.F64[row]; 198 inRow = in->data.C64[row]; 199 200 for (unsigned int col = 0; col < numCols; col++) { 201 outRow[col] = cimag(inRow[col]); 202 } 203 } 204 } else { 205 psError(__func__, "Can not extract imaginary component from given image type (%d).", type); 206 psFree(out); 207 return NULL; 208 } 209 210 return out; 211 } 212 213 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag) 225 214 { 226 215 psElemType type; … … 228 217 unsigned int numRows; 229 218 230 231 if ( real == NULL || imag == NULL ) { 232 psFree( out ); 219 if (real == NULL || imag == NULL) { 220 psFree(out); 233 221 return NULL; 234 222 } … … 238 226 numRows = real->numRows; 239 227 240 if ( imag->type.type != type ) { 241 psError( __func__, "The inputs to psImageComplex must be the same type." ); 242 psFree( out ); 243 return NULL; 244 } 245 246 if ( imag->numCols != numCols || 247 imag->numRows != numRows ) { 248 psError( __func__, "The inputs to psImageComplex must be the same dimensions." ); 249 psFree( out ); 250 return NULL; 251 } 252 253 if ( PS_IS_PSELEMTYPE_COMPLEX( type ) ) { 254 psError( __func__, "The inputs to psImageComplex can not be complex." ); 255 psFree( out ); 256 return NULL; 257 } 258 259 if ( type != PS_TYPE_F32 && type != PS_TYPE_F64 ) { 260 psError( __func__, "The input type to psImageComplex must be a floating point." ); 261 psFree( out ); 262 return NULL; 263 } 264 265 if ( type == PS_TYPE_F32 ) { 266 psC32 * outRow; 267 psF32* realRow; 268 psF32* imagRow; 269 270 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 271 272 for ( unsigned int row = 0;row < numRows;row++ ) { 273 outRow = out->data.C32[ row ]; 274 realRow = real->data.F32[ row ]; 275 imagRow = imag->data.F32[ row ]; 276 277 for ( unsigned int col = 0;col < numCols;col++ ) { 278 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 279 } 280 } 281 } else 282 if ( type == PS_TYPE_F64 ) { 283 psC64 * outRow; 284 psF64* realRow; 285 psF64* imagRow; 286 287 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 288 for ( unsigned int row = 0;row < numRows;row++ ) { 289 outRow = out->data.C64[ row ]; 290 realRow = real->data.F64[ row ]; 291 imagRow = imag->data.F64[ row ]; 292 293 for ( unsigned int col = 0;col < numCols;col++ ) { 294 outRow[ col ] = realRow[ col ] + I * imagRow[ col ]; 295 } 296 } 297 } else { 298 psError( __func__, "Can not merge real and imaginary portions for given image type (%d).", 299 type ); 300 psFree( out ); 301 return NULL; 302 } 303 304 return out; 305 } 306 307 psImage *psImageConjugate( psImage *out, const psImage *in ) 228 if (imag->type.type != type) { 229 psError(__func__, "The inputs to psImageComplex must be the same type."); 230 psFree(out); 231 return NULL; 232 } 233 234 if (imag->numCols != numCols || imag->numRows != numRows) { 235 psError(__func__, "The inputs to psImageComplex must be the same dimensions."); 236 psFree(out); 237 return NULL; 238 } 239 240 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 241 psError(__func__, "The inputs to psImageComplex can not be complex."); 242 psFree(out); 243 return NULL; 244 } 245 246 if (type != PS_TYPE_F32 && type != PS_TYPE_F64) { 247 psError(__func__, "The input type to psImageComplex must be a floating point."); 248 psFree(out); 249 return NULL; 250 } 251 252 if (type == PS_TYPE_F32) { 253 psC32 *outRow; 254 psF32 *realRow; 255 psF32 *imagRow; 256 257 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 258 259 for (unsigned int row = 0; row < numRows; row++) { 260 outRow = out->data.C32[row]; 261 realRow = real->data.F32[row]; 262 imagRow = imag->data.F32[row]; 263 264 for (unsigned int col = 0; col < numCols; col++) { 265 outRow[col] = realRow[col] + I * imagRow[col]; 266 } 267 } 268 } else if (type == PS_TYPE_F64) { 269 psC64 *outRow; 270 psF64 *realRow; 271 psF64 *imagRow; 272 273 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 274 for (unsigned int row = 0; row < numRows; row++) { 275 outRow = out->data.C64[row]; 276 realRow = real->data.F64[row]; 277 imagRow = imag->data.F64[row]; 278 279 for (unsigned int col = 0; col < numCols; col++) { 280 outRow[col] = realRow[col] + I * imagRow[col]; 281 } 282 } 283 } else { 284 psError(__func__, "Can not merge real and imaginary portions for given image type (%d).", type); 285 psFree(out); 286 return NULL; 287 } 288 289 return out; 290 } 291 292 psImage *psImageConjugate(psImage * out, const psImage * in) 308 293 { 309 294 psElemType type; … … 311 296 unsigned int numRows; 312 297 313 314 if ( in == NULL ) { 315 psFree( out ); 298 if (in == NULL) { 299 psFree(out); 316 300 return NULL; 317 301 } … … 322 306 323 307 /* if not a complex number, this is logically just a image copy */ 324 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {308 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 325 309 // Warn user, as this is probably not expected 326 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 327 "Image copy was performed instead." ); 328 return psImageCopy( out, in, type ); 329 } 330 331 if ( type == PS_TYPE_C32 ) { 332 psC32 * outRow; 333 psC32* inRow; 334 335 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C32 ); 336 for ( unsigned int row = 0;row < numRows;row++ ) { 337 outRow = out->data.C32[ row ]; 338 inRow = in->data.C32[ row ]; 339 340 for ( unsigned int col = 0;col < numCols;col++ ) { 341 outRow[ col ] = crealf( inRow[ col ] ) - I * cimagf( inRow[ col ] ); 342 } 343 } 344 } else 345 if ( type == PS_TYPE_C64 ) { 346 psC64 * outRow; 347 psC64* inRow; 348 349 out = psImageRecycle( out, numCols, numRows, PS_TYPE_C64 ); 350 for ( unsigned int row = 0;row < numRows;row++ ) { 351 outRow = out->data.C64[ row ]; 352 inRow = in->data.C64[ row ]; 353 354 for ( unsigned int col = 0;col < numCols;col++ ) { 355 outRow[ col ] = creal( inRow[ col ] ) - I * cimag( inRow[ col ] ); 356 } 357 } 358 } else { 359 psError( __func__, "Can not compute complex conjugate for given image type (%d).", 360 type ); 361 psFree( out ); 362 return NULL; 363 } 364 365 return out; 366 } 367 368 psImage *psImagePowerSpectrum( psImage* out, const psImage* in ) 310 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 311 "Image copy was performed instead."); 312 return psImageCopy(out, in, type); 313 } 314 315 if (type == PS_TYPE_C32) { 316 psC32 *outRow; 317 psC32 *inRow; 318 319 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C32); 320 for (unsigned int row = 0; row < numRows; row++) { 321 outRow = out->data.C32[row]; 322 inRow = in->data.C32[row]; 323 324 for (unsigned int col = 0; col < numCols; col++) { 325 outRow[col] = crealf(inRow[col]) - I * cimagf(inRow[col]); 326 } 327 } 328 } else if (type == PS_TYPE_C64) { 329 psC64 *outRow; 330 psC64 *inRow; 331 332 out = psImageRecycle(out, numCols, numRows, PS_TYPE_C64); 333 for (unsigned int row = 0; row < numRows; row++) { 334 outRow = out->data.C64[row]; 335 inRow = in->data.C64[row]; 336 337 for (unsigned int col = 0; col < numCols; col++) { 338 outRow[col] = creal(inRow[col]) - I * cimag(inRow[col]); 339 } 340 } 341 } else { 342 psError(__func__, "Can not compute complex conjugate for given image type (%d).", type); 343 psFree(out); 344 return NULL; 345 } 346 347 return out; 348 } 349 350 psImage *psImagePowerSpectrum(psImage * out, const psImage * in) 369 351 { 370 352 psElemType type; … … 373 355 int numElementsSquared; 374 356 375 if ( in == NULL) {376 psFree( out);357 if (in == NULL) { 358 psFree(out); 377 359 return NULL; 378 360 } … … 384 366 385 367 /* if not a complex number, this is not implemented */ 386 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {387 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");388 psFree( out);389 return NULL; 390 } 391 392 if ( type == PS_TYPE_C32) {393 psF32 * outRow;394 psC32 *inRow;368 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 369 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 370 psFree(out); 371 return NULL; 372 } 373 374 if (type == PS_TYPE_C32) { 375 psF32 *outRow; 376 psC32 *inRow; 395 377 psF32 real; 396 378 psF32 imag; 397 379 398 399 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F32 ); 400 for ( unsigned int row = 0;row < numRows;row++ ) { 401 outRow = out->data.F32[ row ]; 402 inRow = in->data.C32[ row ]; 403 404 for ( unsigned int col = 0;col < numCols;col++ ) { 405 real = crealf( inRow[ col ] ); 406 imag = cimagf( inRow[ col ] ); 407 outRow[ col ] = ( real * real + imag * imag ) / numElementsSquared; 408 } 409 } 410 } else 411 if ( type == PS_TYPE_C64 ) { 412 psF64 * outRow; 413 psC64* inRow; 414 psF64 real; 415 psF64 imag; 416 417 418 out = psImageRecycle( out, numCols, numRows, PS_TYPE_F64 ); 419 for ( unsigned int row = 0;row < numRows;row++ ) { 420 outRow = out->data.F64[ row ]; 421 inRow = in->data.C64[ row ]; 422 423 for ( unsigned int col = 0;col < numCols;col++ ) { 424 real = crealf( inRow[ col ] ); 425 imag = cimagf( inRow[ col ] ); 426 outRow[ col ] = real * real + imag * imag / numElementsSquared; 427 } 428 } 429 } else { 430 psError( __func__, "Can not power spectrum for given image type (%d).", 431 type ); 432 psFree( out ); 433 return NULL; 434 } 380 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F32); 381 for (unsigned int row = 0; row < numRows; row++) { 382 outRow = out->data.F32[row]; 383 inRow = in->data.C32[row]; 384 385 for (unsigned int col = 0; col < numCols; col++) { 386 real = crealf(inRow[col]); 387 imag = cimagf(inRow[col]); 388 outRow[col] = (real * real + imag * imag) / numElementsSquared; 389 } 390 } 391 } else if (type == PS_TYPE_C64) { 392 psF64 *outRow; 393 psC64 *inRow; 394 psF64 real; 395 psF64 imag; 396 397 out = psImageRecycle(out, numCols, numRows, PS_TYPE_F64); 398 for (unsigned int row = 0; row < numRows; row++) { 399 outRow = out->data.F64[row]; 400 inRow = in->data.C64[row]; 401 402 for (unsigned int col = 0; col < numCols; col++) { 403 real = crealf(inRow[col]); 404 imag = cimagf(inRow[col]); 405 outRow[col] = real * real + imag * imag / numElementsSquared; 406 } 407 } 408 } else { 409 psError(__func__, "Can not power spectrum for given image type (%d).", type); 410 psFree(out); 411 return NULL; 412 } 435 413 436 414 return out; … … 440 418 /************************************** Vector Functions ***************************************/ 441 419 442 psVector * psVectorFFT( psVector* out, const psVector* in, psFftDirection direction)420 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction) 443 421 { 444 422 unsigned int numElements; … … 447 425 448 426 /* got good image data? */ 449 if ( in == NULL ) { 450 psFree( out ); 451 return NULL; 452 } 453 454 type = in->type.type; 455 456 if ( ( type != PS_TYPE_F32 ) && ( type != PS_TYPE_C32 ) ) { 457 psError( __func__, "Input image must be a 32-bit float or complex image (type=%d)", 458 type ); 459 psFree( out ); 460 return NULL; 461 } 462 463 if ( ( type != PS_TYPE_C32 ) && ( direction == PS_FFT_REVERSE ) ) { 464 psError( __func__, "Input image must be complex image for reverse FFT (type=%d).", 465 type ); 466 psFree( out ); 467 return NULL; 468 469 } 470 471 if ( ( type != PS_TYPE_F32 ) && ( direction == PS_FFT_FORWARD ) ) { 472 psError( __func__, "Input image must be real image for forward FFT (type=%d).", 473 type ); 474 psFree( out ); 427 if (in == NULL) { 428 psFree(out); 429 return NULL; 430 } 431 432 type = in->type.type; 433 434 if ((type != PS_TYPE_F32) && (type != PS_TYPE_C32)) { 435 psError(__func__, "Input image must be a 32-bit float or complex image (type=%d)", type); 436 psFree(out); 437 return NULL; 438 } 439 440 if ((type != PS_TYPE_C32) && (direction == PS_FFT_REVERSE)) { 441 psError(__func__, "Input image must be complex image for reverse FFT (type=%d).", type); 442 psFree(out); 443 return NULL; 444 445 } 446 447 if ((type != PS_TYPE_F32) && (direction == PS_FFT_FORWARD)) { 448 psError(__func__, "Input image must be real image for forward FFT (type=%d).", type); 449 psFree(out); 475 450 return NULL; 476 451 } 477 452 478 453 /* make sure the system-level wisdom information is imported. */ 479 if ( ! p_fftwWisdomImported) {454 if (!p_fftwWisdomImported) { 480 455 fftwf_import_system_wisdom(); 481 456 p_fftwWisdomImported = true; … … 484 459 numElements = in->n; 485 460 486 out = psVectorRecycle( out, numElements, PS_TYPE_C32);461 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 487 462 out->n = numElements; 488 463 489 if ( type == PS_TYPE_F32) {464 if (type == PS_TYPE_F32) { 490 465 // need to convert to complex 491 psC32 * outVec = out->data.C32;492 psF32 *inVec = in->data.F32;493 for ( unsigned int i = 0;i < numElements;i++ ) { 494 outVec[ i ] = inVec[ i ];495 }496 } else {497 psC32* outVec = out->data.C32;498 psC32 * inVec = in->data.C32;499 for ( unsigned int i = 0;i < numElements;i++ ) {500 outVec[ i ] = inVec[ i ]; 501 }502 }503 504 plan = fftwf_plan_dft_1d( numElements,505 ( fftwf_complex* ) out->data.C32, 506 ( fftwf_complex* ) out->data.C32,507 direction,508 P_FFTW_PLAN_RIGOR);509 510 /* check if a plan exists now */511 if ( plan == NULL) {512 psError( __func__, "Failed to create FFTW plan.");513 psFree( out);466 psC32 *outVec = out->data.C32; 467 psF32 *inVec = in->data.F32; 468 469 for (unsigned int i = 0; i < numElements; i++) { 470 outVec[i] = inVec[i]; 471 } 472 } else { 473 psC32 *outVec = out->data.C32; 474 psC32 *inVec = in->data.C32; 475 476 for (unsigned int i = 0; i < numElements; i++) { 477 outVec[i] = inVec[i]; 478 } 479 } 480 481 plan = fftwf_plan_dft_1d(numElements, 482 (fftwf_complex *) out->data.C32, 483 (fftwf_complex *) out->data.C32, direction, P_FFTW_PLAN_RIGOR); 484 485 /* check if a plan exists now */ 486 if (plan == NULL) { 487 psError(__func__, "Failed to create FFTW plan."); 488 psFree(out); 514 489 return NULL; 515 490 } 516 491 517 492 /* finally, call FFTW with the plan made above */ 518 fftwf_execute( plan ); 519 520 fftwf_destroy_plan( plan ); 521 522 return out; 523 } 524 525 526 psVector *psVectorReal( psVector *out, const psVector* in ) 493 fftwf_execute(plan); 494 495 fftwf_destroy_plan(plan); 496 497 return out; 498 } 499 500 psVector *psVectorReal(psVector * out, const psVector * in) 527 501 { 528 502 psElemType type; 529 503 unsigned int numElements; 530 504 531 if ( in == NULL) {532 psFree( out);505 if (in == NULL) { 506 psFree(out); 533 507 return NULL; 534 508 } … … 538 512 539 513 /* if not a complex number, this is logically just a copy */ 540 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {514 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 541 515 // Warn user, as this is probably not expected 542 psLogMsg( __func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. "543 "Just a vector copy was performed.");544 out = psVectorRecycle( out, numElements, type);516 psLogMsg(__func__, PS_LOG_WARN, "Real portion of a non-Complex type called called for. " 517 "Just a vector copy was performed."); 518 out = psVectorRecycle(out, numElements, type); 545 519 out->n = numElements; 546 memcpy( out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF( type ));520 memcpy(out->data.V, in->data.V, numElements * PSELEMTYPE_SIZEOF(type)); 547 521 return out; 548 522 } 549 523 550 if ( type == PS_TYPE_C32) {551 psF32 * outVec;552 psC32 *inVec = in->data.C32;553 554 out = psVectorRecycle( out, numElements, PS_TYPE_F32);524 if (type == PS_TYPE_C32) { 525 psF32 *outVec; 526 psC32 *inVec = in->data.C32; 527 528 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 555 529 out->n = numElements; 556 530 outVec = out->data.F32; 557 531 558 for ( unsigned int i = 0;i < numElements;i++ ) { 559 outVec[ i ] = crealf( inVec[ i ] ); 560 } 561 } else { 562 psError( __func__, "Can not extract real component from given vector type (%d).", 563 type ); 564 psFree( out ); 565 return NULL; 566 } 567 568 return out; 569 } 570 571 psVector *psVectorImaginary( psVector *out, const psVector* in ) 532 for (unsigned int i = 0; i < numElements; i++) { 533 outVec[i] = crealf(inVec[i]); 534 } 535 } else { 536 psError(__func__, "Can not extract real component from given vector type (%d).", type); 537 psFree(out); 538 return NULL; 539 } 540 541 return out; 542 } 543 544 psVector *psVectorImaginary(psVector * out, const psVector * in) 572 545 { 573 546 psElemType type; 574 547 unsigned int numElements; 575 548 576 577 if ( in == NULL ) { 578 psFree( out ); 549 if (in == NULL) { 550 psFree(out); 579 551 return NULL; 580 552 } … … 584 556 585 557 /* if not a complex number, this is logically just zeroed image of same size */ 586 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {558 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 587 559 // Warn user, as this is probably not expected 588 psLogMsg( __func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. "589 "A zeroed vector was returned.");590 out = psVectorRecycle( out, numElements, type);560 psLogMsg(__func__, PS_LOG_WARN, "Imaginary portion of a non-Complex type called for. " 561 "A zeroed vector was returned."); 562 out = psVectorRecycle(out, numElements, type); 591 563 out->n = numElements; 592 memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements);564 memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements); 593 565 return out; 594 566 } 595 567 596 if ( type == PS_TYPE_C32) {597 psF32 * outVec;598 psC32 *inVec = in->data.C32;599 600 out = psVectorRecycle( out, numElements, PS_TYPE_F32);568 if (type == PS_TYPE_C32) { 569 psF32 *outVec; 570 psC32 *inVec = in->data.C32; 571 572 out = psVectorRecycle(out, numElements, PS_TYPE_F32); 601 573 out->n = numElements; 602 574 outVec = out->data.F32; 603 575 604 for ( unsigned int i = 0;i < numElements;i++ ) { 605 outVec[ i ] = cimagf( inVec[ i ] ); 606 } 607 } else { 608 psError( __func__, "Can not extract imaginary component from given vector type (%d).", 609 type ); 610 psFree( out ); 611 return NULL; 612 } 613 614 return out; 615 } 616 617 psVector *psVectorComplex( psVector* out, psVector *real, const psVector *imag ) 576 for (unsigned int i = 0; i < numElements; i++) { 577 outVec[i] = cimagf(inVec[i]); 578 } 579 } else { 580 psError(__func__, "Can not extract imaginary component from given vector type (%d).", type); 581 psFree(out); 582 return NULL; 583 } 584 585 return out; 586 } 587 588 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag) 618 589 { 619 590 psElemType type; 620 591 unsigned int numElements; 621 592 622 623 if ( real == NULL || imag == NULL ) { 624 psFree( out ); 593 if (real == NULL || imag == NULL) { 594 psFree(out); 625 595 return NULL; 626 596 } 627 597 628 598 type = real->type.type; 629 if ( real->n < imag->n) {599 if (real->n < imag->n) { 630 600 numElements = real->n; 631 601 } else { … … 633 603 } 634 604 635 if ( imag->type.type != type) {636 psError( __func__, "The inputs to psVectorComplex must be the same type.");637 psFree( out);638 return NULL; 639 } 640 641 if ( PS_IS_PSELEMTYPE_COMPLEX( type )) {642 psError( __func__, "The inputs to psVectorComplex can not be complex.");643 psFree( out);644 return NULL; 645 } 646 647 if ( type == PS_TYPE_F32) {648 psC32 * outVec;649 psF32 *realVec = real->data.F32;650 psF32 *imagVec = imag->data.F32;651 652 out = psVectorRecycle( out, numElements, PS_TYPE_C32);605 if (imag->type.type != type) { 606 psError(__func__, "The inputs to psVectorComplex must be the same type."); 607 psFree(out); 608 return NULL; 609 } 610 611 if (PS_IS_PSELEMTYPE_COMPLEX(type)) { 612 psError(__func__, "The inputs to psVectorComplex can not be complex."); 613 psFree(out); 614 return NULL; 615 } 616 617 if (type == PS_TYPE_F32) { 618 psC32 *outVec; 619 psF32 *realVec = real->data.F32; 620 psF32 *imagVec = imag->data.F32; 621 622 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 653 623 out->n = numElements; 654 624 outVec = out->data.C32; 655 625 656 for ( unsigned int i = 0;i < numElements;i++ ) { 657 outVec[ i ] = realVec[ i ] + I * imagVec[ i ]; 658 } 659 } else { 660 psError( __func__, "Can not merge real and imaginary portions for given vector type (%d).", 661 type ); 662 psFree( out ); 663 return NULL; 664 } 665 666 return out; 667 } 668 669 psVector *psVectorConjugate( psVector *out, const psVector *in ) 626 for (unsigned int i = 0; i < numElements; i++) { 627 outVec[i] = realVec[i] + I * imagVec[i]; 628 } 629 } else { 630 psError(__func__, "Can not merge real and imaginary portions for given vector type (%d).", type); 631 psFree(out); 632 return NULL; 633 } 634 635 return out; 636 } 637 638 psVector *psVectorConjugate(psVector * out, const psVector * in) 670 639 { 671 640 psElemType type; 672 641 unsigned int numElements; 673 642 674 675 if ( in == NULL ) { 676 psFree( out ); 643 if (in == NULL) { 644 psFree(out); 677 645 return NULL; 678 646 } … … 682 650 683 651 /* if not a complex number, this is logically just a image copy */ 684 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {652 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 685 653 // Warn user, as this is probably not expected 686 psLogMsg( __func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. "687 "Vector copy was performed instead.");688 689 out = psVectorRecycle( out, numElements, type);654 psLogMsg(__func__, PS_LOG_WARN, "Complex Conjugate of a non-Complex type called for. " 655 "Vector copy was performed instead."); 656 657 out = psVectorRecycle(out, numElements, type); 690 658 out->n = numElements; 691 memcpy( out->data.V, in->data.V, PSELEMTYPE_SIZEOF( type ) * numElements);659 memcpy(out->data.V, in->data.V, PSELEMTYPE_SIZEOF(type) * numElements); 692 660 return out; 693 661 } 694 662 695 if ( type == PS_TYPE_C32) {696 psC32 * outVec;697 psC32 *inVec = in->data.C32;698 699 out = psVectorRecycle( out, numElements, PS_TYPE_C32);663 if (type == PS_TYPE_C32) { 664 psC32 *outVec; 665 psC32 *inVec = in->data.C32; 666 667 out = psVectorRecycle(out, numElements, PS_TYPE_C32); 700 668 out->n = numElements; 701 669 outVec = out->data.C32; 702 670 703 for ( unsigned int i = 0;i < numElements;i++ ) { 704 outVec[ i ] = crealf( inVec[ i ] ) - I * cimagf( inVec[ i ] ); 705 } 706 } else { 707 psError( __func__, "Can not compute complex conjugate for given vector type (%d).", 708 type ); 709 psFree( out ); 710 return NULL; 711 } 712 713 return out; 714 } 715 716 psVector *psVectorPowerSpectrum( psVector* out, const psVector* in ) 671 for (unsigned int i = 0; i < numElements; i++) { 672 outVec[i] = crealf(inVec[i]) - I * cimagf(inVec[i]); 673 } 674 } else { 675 psError(__func__, "Can not compute complex conjugate for given vector type (%d).", type); 676 psFree(out); 677 return NULL; 678 } 679 680 return out; 681 } 682 683 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in) 717 684 { 718 685 psElemType type; … … 722 689 unsigned int inNumElementsSquared; 723 690 724 if ( in == NULL) {725 psFree( out);691 if (in == NULL) { 692 psFree(out); 726 693 return NULL; 727 694 } … … 734 701 735 702 /* if not a complex number, this is not implemented */ 736 if ( ! PS_IS_PSELEMTYPE_COMPLEX( type )) {737 psError( __func__, "Power Spectrum for non-complex inputs is not implemented.");738 psFree( out);739 return NULL; 740 } 741 742 if ( type == PS_TYPE_C32) {743 psF32 * outVec;744 psC32 *inVec = in->data.C32;703 if (!PS_IS_PSELEMTYPE_COMPLEX(type)) { 704 psError(__func__, "Power Spectrum for non-complex inputs is not implemented."); 705 psFree(out); 706 return NULL; 707 } 708 709 if (type == PS_TYPE_C32) { 710 psF32 *outVec; 711 psC32 *inVec = in->data.C32; 745 712 psF32 inAbs1; 746 713 psF32 inAbs2; 747 714 748 out = psVectorRecycle( out, outNumElements, PS_TYPE_F32);715 out = psVectorRecycle(out, outNumElements, PS_TYPE_F32); 749 716 out->n = outNumElements; 750 717 outVec = out->data.F32; 751 718 752 719 // from ADD: P_0 = |C_0|^2/N^2 753 inAbs1 = cabsf( inVec[ 0 ]);754 outVec[ 0] = inAbs1 * inAbs1 / inNumElementsSquared;720 inAbs1 = cabsf(inVec[0]); 721 outVec[0] = inAbs1 * inAbs1 / inNumElementsSquared; 755 722 756 723 // from ADD: P_j = (|C_j|^2+|C_N-j|^2)/N^2, where j = 1,2,...,(N/2-1) 757 for ( unsigned int i = 1;i < inHalfNumElements;i++) {758 inAbs1 = cabsf( inVec[ i ]);759 inAbs2 = cabsf( inVec[ inNumElements - i ]);760 outVec[ i ] = ( inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared;724 for (unsigned int i = 1; i < inHalfNumElements; i++) { 725 inAbs1 = cabsf(inVec[i]); 726 inAbs2 = cabsf(inVec[inNumElements - i]); 727 outVec[i] = (inAbs1 * inAbs1 + inAbs2 * inAbs2) / inNumElementsSquared; 761 728 } 762 729 763 730 // from ADD: P_N/2 = |C_N/2|^2/N^2 764 inAbs1 = cabsf( inVec[ inHalfNumElements ] ); 765 outVec[ inHalfNumElements ] = inAbs1 * inAbs1 / inNumElementsSquared; 766 } else { 767 psError( __func__, "Can not power spectrum for given vector type (%d).", 768 type ); 769 psFree( out ); 770 return NULL; 771 } 772 773 return out; 774 775 } 731 inAbs1 = cabsf(inVec[inHalfNumElements]); 732 outVec[inHalfNumElements] = inAbs1 * inAbs1 / inNumElementsSquared; 733 } else { 734 psError(__func__, "Can not power spectrum for given vector type (%d).", type); 735 psFree(out); 736 return NULL; 737 } 738 739 return out; 740 741 } -
trunk/psLib/src/fft/psVectorFFT.h
r1406 r1407 1 1 2 /** @file psFFT.h 2 3 * … … 7 8 * @author Robert DeSonia, MHPCC 8 9 * 9 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 14 15 15 16 #ifndef PS_FFT_H 16 # define PS_FFT_H17 # define PS_FFT_H 17 18 18 # include "psImage.h"19 # include "psVector.h"19 # include "psImage.h" 20 # include "psVector.h" 20 21 21 22 /// @addtogroup Transform … … 24 25 /** Details on FFT implementation (private). */ 25 26 26 27 27 typedef enum { 28 // / psImageFFT/psVectorFFT should perform a forward FFT.28 // / psImageFFT/psVectorFFT should perform a forward FFT. 29 29 PS_FFT_FORWARD = (-1), 30 30 31 // /< psImageFFT/psVectorFFT should perform a reverse FFT.31 // /< psImageFFT/psVectorFFT should perform a reverse FFT. 32 32 PS_FFT_REVERSE = (+1) 33 33 } psFftDirection; 34 34 35 psImage * psImageFFT(psImage* out, const psImage* in, psFftDirection direction);36 psImage * psImageReal(psImage *out, const psImage* in);37 psImage * psImageImaginary(psImage *out, const psImage* in);38 psImage * psImageComplex(psImage* out, psImage *real, const psImage *imag);39 psImage * psImageConjugate(psImage *out, const psImage *in);40 psImage * psImagePowerSpectrum(psImage* out, const psImage* in);35 psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction); 36 psImage *psImageReal(psImage * out, const psImage * in); 37 psImage *psImageImaginary(psImage * out, const psImage * in); 38 psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag); 39 psImage *psImageConjugate(psImage * out, const psImage * in); 40 psImage *psImagePowerSpectrum(psImage * out, const psImage * in); 41 41 42 psVector * psVectorFFT(psVector* out, const psVector* in, psFftDirection direction);43 psVector * psVectorReal(psVector* out, const psVector* in);44 psVector * psVectorImaginary(psVector* out, const psVector* in);45 psVector * psVectorComplex(psVector* out, psVector* real, const psVector* imag);46 psVector * psVectorConjugate(psVector* out, const psVector* in);47 psVector * psVectorPowerSpectrum(psVector* out, const psVector* in);42 psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction); 43 psVector *psVectorReal(psVector * out, const psVector * in); 44 psVector *psVectorImaginary(psVector * out, const psVector * in); 45 psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag); 46 psVector *psVectorConjugate(psVector * out, const psVector * in); 47 psVector *psVectorPowerSpectrum(psVector * out, const psVector * in); 48 48 49 49 /// @} 50 50 51 51 #endif 52 -
trunk/psLib/src/image/psImage.c
r1406 r1407 1 1 2 /** @file psImage.c 2 3 * … … 9 10 * @author Ross Harman, MHPCC 10 11 * 11 * @version $Revision: 1.3 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.38 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 … … 29 32 #include "psImage.h" 30 33 31 static void imageFree(psImage * image);34 static void imageFree(psImage * image); 32 35 33 36 /*****************************************************************************/ 37 34 38 /* FUNCTION IMPLEMENTATION - PUBLIC */ 39 35 40 /*****************************************************************************/ 36 41 37 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, 38 const psElemType type) 42 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, const psElemType type) 39 43 { 40 44 int area = 0; 41 int elementSize = PSELEMTYPE_SIZEOF(type); // element size in bytes 42 int rowSize = numCols*elementSize; // row size in bytes. 43 44 area = numCols*numRows; 45 int elementSize = PSELEMTYPE_SIZEOF(type); // element 46 47 // size in 48 // bytes 49 int rowSize = numCols * elementSize; // row 50 51 // size 52 53 // in bytes. 54 55 area = numCols * numRows; 45 56 46 57 if (area < 1) { 47 psError(__func__, "Invalid value for number of rows or columns "48 " (numRows=%d, numCols=%d).", numRows, numCols);58 psError(__func__, 59 "Invalid value for number of rows or columns " "(numRows=%d, numCols=%d).", numRows, numCols); 49 60 return NULL; 50 61 } 51 62 52 psImage *image = (psImage *) psAlloc(sizeof(psImage));53 if(image == NULL) { 54 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__);55 }56 57 p_psMemSetDeallocator(image,(psFreeFcn)imageFree); 58 59 image->data.V = psAlloc(sizeof(void*)*numRows); 60 i f(image->data.V == NULL) {61 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__);62 }63 64 65 image->data.V[0] = psAlloc(area *elementSize);66 if (image->data.V[0] == NULL) {67 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);68 } 69 70 for (int i = 1; i < numRows; i++) {71 image->data.V[i] = (void *)((int8_t*)image->data.V[i-1]+rowSize);72 } 73 74 *(int *)&image->col0 = 0;75 *(int *)&image->row0 = 0;76 *(unsigned int *)&image->numCols = numCols;77 *(unsigned int *)&image->numRows = numRows;78 *(psDimen *)&image->type.dimen = PS_DIMEN_IMAGE;79 *(psElemType *)&image->type.type = type;63 psImage *image = (psImage *) psAlloc(sizeof(psImage)); 64 65 if (image == NULL) { 66 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 67 } 68 69 p_psMemSetDeallocator(image, (psFreeFcn) imageFree); 70 71 image->data.V = psAlloc(sizeof(void *) * numRows); 72 if (image->data.V == NULL) { 73 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 74 } 75 76 image->data.V[0] = psAlloc(area * elementSize); 77 if (image->data.V[0] == NULL) { 78 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 79 } 80 81 for (int i = 1; i < numRows; i++) { 82 image->data.V[i] = (void *)((int8_t *) image->data.V[i - 1] + rowSize); 83 } 84 85 *(int *)&image->col0 = 0; 86 *(int *)&image->row0 = 0; 87 *(unsigned int *)&image->numCols = numCols; 88 *(unsigned int *)&image->numRows = numRows; 89 *(psDimen *) & image->type.dimen = PS_DIMEN_IMAGE; 90 *(psElemType *) & image->type.type = type; 80 91 image->parent = NULL; 81 92 image->nChildren = 0; … … 85 96 } 86 97 87 static void imageFree(psImage * image)98 static void imageFree(psImage * image) 88 99 { 89 100 if (image == NULL) { … … 92 103 93 104 if (image->type.type == PS_TYPE_PTR) { 94 // 2-D array of pointers -- must dereference 105 // 2-D array of pointers -- must 106 // dereference 95 107 unsigned int oldNumRows = image->numRows; 96 108 unsigned int oldNumCols = image->numCols; 97 psPTR *rowPtr;98 99 for (unsigned int row=0;row<oldNumRows;row++) {109 psPTR *rowPtr; 110 111 for (unsigned int row = 0; row < oldNumRows; row++) { 100 112 rowPtr = image->data.PTR[row]; 101 for (unsigned int col =0;col<oldNumCols;col++) {113 for (unsigned int col = 0; col < oldNumCols; col++) { 102 114 psMemDecrRefCounter(rowPtr[col]); 103 115 } … … 112 124 } 113 125 114 psImage* psImageRecycle(psImage* old, 115 unsigned int numCols, 116 unsigned int numRows, 117 const psElemType type) 126 psImage *psImageRecycle(psImage * old, unsigned int numCols, unsigned int numRows, const psElemType type) 118 127 { 119 int elementSize = PSELEMTYPE_SIZEOF(type); // element size in bytes 120 int rowSize = numCols*elementSize; // row size in bytes. 128 int elementSize = PSELEMTYPE_SIZEOF(type); // element 129 130 // size in 131 // bytes 132 int rowSize = numCols * elementSize; // row 133 134 // size 135 136 // in bytes. 121 137 122 138 if (old == NULL) { 123 old = psImageAlloc(numCols, numRows,type);139 old = psImageAlloc(numCols, numRows, type); 124 140 return old; 125 141 } 126 142 127 143 if (old->type.dimen != PS_DIMEN_IMAGE) { 128 psError(__func__, "Can not realloc image because input is not an image.");144 psError(__func__, "Can not realloc image because input is not an image."); 129 145 return NULL; 130 146 } 131 147 132 148 if (old->type.type == PS_TYPE_PTR) { 133 // 2-D array of pointers -- must dereference 149 // 2-D array of pointers -- must 150 // dereference 134 151 unsigned int oldNumRows = old->numRows; 135 152 unsigned int oldNumCols = old->numCols; 136 psPTR *rowPtr;137 138 for (unsigned int row=0;row<oldNumRows;row++) {153 psPTR *rowPtr; 154 155 for (unsigned int row = 0; row < oldNumRows; row++) { 139 156 rowPtr = old->data.PTR[row]; 140 for (unsigned int col =0;col<oldNumCols;col++) {157 for (unsigned int col = 0; col < oldNumCols; col++) { 141 158 psMemDecrRefCounter(rowPtr[col]); 142 159 rowPtr[col] = NULL; … … 146 163 147 164 /* image already the right size/type? */ 148 if (numCols == old->numCols && numRows == old->numRows && 149 type == old->type.type) { 165 if (numCols == old->numCols && numRows == old->numRows && type == old->type.type) { 150 166 return old; 151 167 } 152 153 168 // Resize the image buffer 154 old->data.V[0] = psRealloc(old->data.V[0], numCols * numRows * elementSize);155 old->data.V = (void **) psRealloc(old->data.V,numRows * sizeof(void*));169 old->data.V[0] = psRealloc(old->data.V[0], numCols * numRows * elementSize); 170 old->data.V = (void **)psRealloc(old->data.V, numRows * sizeof(void *)); 156 171 157 172 // recreate the row pointers 158 for (int i = 1; i < numRows; i++) {159 old->data.V[i] = (void *)((int8_t*)old->data.V[i-1]+rowSize);160 } 161 162 *(unsigned int *)&old->numCols = numCols;163 *(unsigned int *)&old->numRows = numRows;164 *(psElemType *)&old->type.type = type;173 for (int i = 1; i < numRows; i++) { 174 old->data.V[i] = (void *)((int8_t *) old->data.V[i - 1] + rowSize); 175 } 176 177 *(unsigned int *)&old->numCols = numCols; 178 *(unsigned int *)&old->numRows = numRows; 179 *(psElemType *) & old->type.type = type; 165 180 166 181 return old; 167 182 } 168 183 169 int psImageFreeChildren(psImage * image)184 int psImageFreeChildren(psImage * image) 170 185 { 171 186 int i = 0; … … 181 196 children = image->children; 182 197 183 for (i=0; i<nChildren; i++) {198 for (i = 0; i < nChildren; i++) { 184 199 if (children[i] != NULL) { 185 200 numFreed++; … … 191 206 image->nChildren = 0; 192 207 image->children = NULL; 193 194 208 195 209 return numFreed; … … 202 216 linear interpolation is performed on the image. 203 217 *****************************************************************************/ 204 psF32 psImagePixelInterpolate( 205 const psImage *input, 206 float x, 207 float y, 208 psF32 unexposedValue, 209 psImageInterpolateMode mode) 218 psF32 psImagePixelInterpolate(const psImage * input, 219 float x, float y, psF32 unexposedValue, psImageInterpolateMode mode) 210 220 { 211 221 212 222 if (input == NULL) { 213 psError(__func__, "Image can not be NULL.");223 psError(__func__, "Image can not be NULL."); 214 224 return unexposedValue; 215 225 } 216 217 226 #define PSIMAGE_PIXEL_INTERPOLATE_CASE(TYPE) \ 218 227 case PS_TYPE_##TYPE: \ … … 243 252 PSIMAGE_PIXEL_INTERPOLATE_CASE(C64); 244 253 default: 245 psError(__func__, "Unsupported image datatype (%d)",input->type.type);254 psError(__func__, "Unsupported image datatype (%d)", input->type.type); 246 255 } 247 256 … … 303 312 PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C32) 304 313 PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C64) 305 306 314 #define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR(TYPE) \ 307 315 inline psF64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \ … … 359 367 return(pixel); \ 360 368 } 361 362 369 #define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(TYPE) \ 363 370 inline psC64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \ … … 428 435 PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C32) 429 436 PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C64) 430 431 -
trunk/psLib/src/image/psImage.h
r1406 r1407 1 1 2 /** @file psImage.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.2 7$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.28 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 17 18 */ 18 # ifndef PS_IMAGE_H19 # define PS_IMAGE_H19 #ifndef PS_IMAGE_H 20 # define PS_IMAGE_H 20 21 21 # include <complex.h>22 # include <complex.h> 22 23 23 # include "psType.h"24 # include "psType.h" 24 25 25 26 /// @addtogroup Image … … 39 40 typedef struct psImage 40 41 { 41 const psType type; ///< Image data type and dimension.42 const unsigned int numCols; ///< Number of columns in image43 const unsigned int numRows; ///< Number of rows in image.44 const int col0; ///< Column position relative to parent.45 const int row0; ///< Row position relative to parent.42 const psType type; // /< Image data type and dimension. 43 const unsigned int numCols; // /< Number of columns in image 44 const unsigned int numRows; // /< Number of rows in image. 45 const int col0; // /< Column position relative to parent. 46 const int row0; // /< Row position relative to parent. 46 47 47 48 union { 48 psU8 **U8; ///< Unsigned 8-bit integer data.49 psU16 **U16; ///< Unsigned 16-bit integer data.50 psU32 **U32; ///< Unsigned 32-bit integer data.51 psU64 **U64; ///< Unsigned 64-bit integer data.52 psS8 **S8; ///< Signed 8-bit integer data.53 psS16 **S16; ///< Signed 16-bit integer data.54 psS32 **S32; ///< Signed 32-bit integer data.55 psS64 **S64; ///< Signed 64-bit integer data.56 psF32 **F32; ///< Single-precision float data.57 psF64 **F64; ///< Double-precision float data.58 psC32 **C32; ///< Single-precision complex data.59 psC64 **C64; ///< Double-precision complex data.60 psPTR **PTR; ///< Void pointers.61 psPTR *V; ///< Pointer to data.62 } data; ///< Union for data types.63 const struct psImage *parent; // /< Parent, if a subimage.64 int nChildren; ///< Number of subimages.65 struct psImage ** children; ///< Children of this region.49 psU8 **U8; // /< Unsigned 8-bit integer data. 50 psU16 **U16; // /< Unsigned 16-bit integer data. 51 psU32 **U32; // /< Unsigned 32-bit integer data. 52 psU64 **U64; // /< Unsigned 64-bit integer data. 53 psS8 **S8; // /< Signed 8-bit integer data. 54 psS16 **S16; // /< Signed 16-bit integer data. 55 psS32 **S32; // /< Signed 32-bit integer data. 56 psS64 **S64; // /< Signed 64-bit integer data. 57 psF32 **F32; // /< Single-precision float data. 58 psF64 **F64; // /< Double-precision float data. 59 psC32 **C32; // /< Single-precision complex data. 60 psC64 **C64; // /< Double-precision complex data. 61 psPTR **PTR; // /< Void pointers. 62 psPTR *V; // /< Pointer to data. 63 } data; // /< Union for data types. 64 const struct psImage *parent; // /< Parent, if a subimage. 65 int nChildren; // /< Number of subimages. 66 struct psImage **children; // /< Children of this region. 66 67 } 67 68 psImage; 68 69 69 70 /*****************************************************************************/ 71 70 72 /* FUNCTION PROTOTYPES */ 73 71 74 /*****************************************************************************/ 72 73 75 74 76 /** Create an image of the specified size and type. … … 80 82 * 81 83 */ 82 psImage *psImageAlloc( 83 unsigned int numCols, ///< Number of rows in image. 84 unsigned int numRows, ///< Number of columns in image. 85 const psElemType type ///< Type of data for image. 86 ); 84 psImage *psImageAlloc(unsigned int numCols, // /< Number of rows in image. 85 unsigned int numRows, // /< Number of columns in image. 86 const psElemType type // /< Type of data for image. 87 ); 87 88 88 89 /** Resize a given image to the given size/type. … … 91 92 * 92 93 */ 93 psImage* psImageRecycle( 94 psImage* old, ///< the psImage to recycle by resizing image buffer 95 unsigned int numCols, ///< the desired number of columns in image 96 unsigned int numRows, ///< the desired number of rows in image 97 const psElemType type ///< the desired datatype of the image 98 ); 99 94 psImage *psImageRecycle(psImage * old, // /< the psImage to recycle by resizing image buffer 95 unsigned int numCols, // /< the desired number of columns in image 96 unsigned int numRows, // /< the desired number of rows in image 97 const psElemType type // /< the desired datatype of the image 98 ); 100 99 101 100 /** Frees all children of a psImage. … … 104 103 * 105 104 */ 106 int psImageFreeChildren( 107 psImage* image 108 /**< psImage in which all children shall be deallocated */ 109 ); 105 int psImageFreeChildren(psImage * image 110 106 111 psF32 psImagePixelInterpolate( 112 const psImage *input, 113 float x, 114 float y, 115 psF32 unexposedValue, 116 psImageInterpolateMode mode 117 ); 107 /**< psImage in which all children shall be deallocated */ 108 ); 118 109 119 #define p_psImagePixelInterpolateFcns(TYPE) \ 110 psF32 psImagePixelInterpolate(const psImage * input, 111 float x, float y, psF32 unexposedValue, psImageInterpolateMode mode); 112 113 # define p_psImagePixelInterpolateFcns(TYPE) \ 120 114 inline psF64 p_psImagePixelInterpolateFLAT_##TYPE( \ 121 115 const psImage *input, \ … … 131 125 ); 132 126 133 # define p_psImagePixelInterpolateComplexFcns(TYPE) \127 # define p_psImagePixelInterpolateComplexFcns(TYPE) \ 134 128 inline psC64 p_psImagePixelInterpolateFLAT_##TYPE( \ 135 129 const psImage *input, \ … … 157 151 p_psImagePixelInterpolateComplexFcns(C32) 158 152 p_psImagePixelInterpolateComplexFcns(C64) 159 160 153 /// @} 161 162 154 #endif -
trunk/psLib/src/image/psImageExtraction.c
r1406 r1407 1 1 2 /** @file psImageExtraction.c 2 3 * … … 9 10 * @author Robert DeSonia, MHPCC 10 11 * 11 * @version $Revision: 1. 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.8 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 22 23 #include "psError.h" 23 24 24 psImage *psImageSubset( psImage *out, psImage *image, unsigned int numCols,25 unsigned int numRows, unsigned int col0,26 unsigned int row0)25 psImage *psImageSubset(psImage * out, 26 psImage * image, 27 unsigned int numCols, unsigned int numRows, unsigned int col0, unsigned int row0) 27 28 { 28 unsigned int elementSize; // size of image element in bytes 29 unsigned int outputRowSize; // output row size in bytes 30 unsigned int inputColOffset; // offset in bytes to first subset pixel in input row 31 32 if ( image == NULL || image->data.V == NULL ) { 33 psError( __func__, "Can not subset image because input image or its pixel buffer is NULL." ); 34 return NULL; 35 } 36 37 if ( image->type.dimen != PS_DIMEN_IMAGE ) { 38 psError( __func__, "Can not subset image because input image is not an image." ); 39 return NULL; 40 } 41 42 if ( numCols < 1 || numRows < 1 ) { 43 psError( __func__, "Can not subset image because number of rows or columns are zero (%dx%d).", 44 numCols, numRows ); 45 return NULL; 46 } 47 48 if ( col0 >= image->numCols || row0 >= image->numRows ) { 49 psError( __func__, "Can not subset image because col0,row0 (%d,%d) is not a valid pixel location.", 50 col0, row0 ); 29 unsigned int elementSize; // size of image 30 31 // element in 32 // bytes 33 unsigned int outputRowSize; // output row 34 35 // size in bytes 36 unsigned int inputColOffset; // offset 37 38 // in 39 // bytes 40 // to 41 // first 42 // subset 43 44 // pixel in input row 45 46 if (image == NULL || image->data.V == NULL) { 47 psError(__func__, "Can not subset image because input image or its pixel buffer is NULL."); 48 return NULL; 49 } 50 51 if (image->type.dimen != PS_DIMEN_IMAGE) { 52 psError(__func__, "Can not subset image because input image is not an image."); 53 return NULL; 54 } 55 56 if (numCols < 1 || numRows < 1) { 57 psError(__func__, 58 "Can not subset image because number of rows or columns are zero (%dx%d).", numCols, numRows); 59 return NULL; 60 } 61 62 if (col0 >= image->numCols || row0 >= image->numRows) { 63 psError(__func__, 64 "Can not subset image because col0,row0 (%d,%d) is not a valid pixel location.", col0, row0); 51 65 return NULL; 52 66 } 53 67 54 68 /* validate subimage size */ 55 if ( col0 + numCols >= image->numCols || row0 + numRows >= image->numRows ) { 56 psError( __func__, "Can not subset image outside of image boundaries (size=%dx%d, " 57 "subset=[%d:%d,%d:%d]).", image->numCols, image->numRows, col0, 58 col0 + numCols, row0, row0 + numRows ); 59 return NULL; 60 } 61 62 63 elementSize = PSELEMTYPE_SIZEOF( image->type.type ); 64 65 out = psImageRecycle( out, numCols, numRows, image->type.type ); 66 67 // set the parent information into the child output image 68 *( int* ) & out->row0 = row0; 69 *( int* ) & out->col0 = col0; 70 *( psImage** ) & out->parent = ( psImage* ) image; 71 72 // add output image as a child of the input image. 69 if (col0 + numCols >= image->numCols || row0 + numRows >= image->numRows) { 70 psError(__func__, 71 "Can not subset image outside of image boundaries (size=%dx%d, " 72 "subset=[%d:%d,%d:%d]).", 73 image->numCols, image->numRows, col0, col0 + numCols, row0, row0 + numRows); 74 return NULL; 75 } 76 77 elementSize = PSELEMTYPE_SIZEOF(image->type.type); 78 79 out = psImageRecycle(out, numCols, numRows, image->type.type); 80 81 // set the parent information into the child 82 // output image 83 *(int *)&out->row0 = row0; 84 *(int *)&out->col0 = col0; 85 *(psImage **) & out->parent = (psImage *) image; 86 87 // add output image as a child of the input 88 // image. 73 89 image->nChildren++; 74 image->children = ( psImage ** ) psRealloc( image->children, 75 image->nChildren * sizeof( psImage* ) ); 76 image->children[ image->nChildren - 1 ] = out; 90 image->children = (psImage **) psRealloc(image->children, image->nChildren * sizeof(psImage *)); 91 image->children[image->nChildren - 1] = out; 77 92 78 93 inputColOffset = elementSize * col0; 79 94 outputRowSize = elementSize * numCols; 80 95 81 for ( int row = 0; row < numRows; row++ ) { 82 memcpy( out->data.V[ row ], image->data.U8[ row0 + row ] + inputColOffset, 83 outputRowSize ); 84 } 85 86 return ( out ); 96 for (int row = 0; row < numRows; row++) { 97 memcpy(out->data.V[row], image->data.U8[row0 + row] + inputColOffset, outputRowSize); 98 } 99 100 return (out); 87 101 } 88 102 89 90 psImage *psImageCopy( psImage* restrict output, const psImage *input, 91 psElemType type ) 103 psImage *psImageCopy(psImage * restrict output, const psImage * input, psElemType type) 92 104 { 93 105 psElemType inDatatype; … … 97 109 int numCols; 98 110 99 if ( input == NULL || input->data.V == NULL ) { 100 psError( __func__, "Can not copy image because input image or its pixel buffer is NULL." ); 101 psFree( output ); 102 return NULL; 103 } 104 105 if ( input == output ) { 106 psError( __func__, "Can not copy image because given input and output " 107 "parameter reference the same psImage struct." ); 108 psFree( output ); 109 return NULL; 110 } 111 112 if ( input->type.dimen != PS_DIMEN_IMAGE ) { 113 psError( __func__, "Can not copy image because input image is not actually an image." ); 114 psFree( output ); 111 if (input == NULL || input->data.V == NULL) { 112 psError(__func__, "Can not copy image because input image or its pixel buffer is NULL."); 113 psFree(output); 114 return NULL; 115 } 116 117 if (input == output) { 118 psError(__func__, 119 "Can not copy image because given input and output " 120 "parameter reference the same psImage struct."); 121 psFree(output); 122 return NULL; 123 } 124 125 if (input->type.dimen != PS_DIMEN_IMAGE) { 126 psError(__func__, "Can not copy image because input image is not actually an image."); 127 psFree(output); 115 128 return NULL; 116 129 } … … 120 133 numCols = input->numCols; 121 134 elements = numRows * numCols; 122 elementSize = PSELEMTYPE_SIZEOF( inDatatype ); 123 124 if ( inDatatype == PS_TYPE_PTR || type == PS_TYPE_PTR ) { 125 psError( __func__, "Can not copy image to/from a void* matrix" ); 126 psFree( output ); 127 return NULL; 128 } 129 130 output = psImageRecycle( output, numCols, numRows, type ); 131 132 // cover the trival case of copy of the same datatype. 133 if ( type == inDatatype ) { 134 memcpy( output->data.V[ 0 ], input->data.V[ 0 ], elementSize * elements ); 135 elementSize = PSELEMTYPE_SIZEOF(inDatatype); 136 137 if (inDatatype == PS_TYPE_PTR || type == PS_TYPE_PTR) { 138 psError(__func__, "Can not copy image to/from a void* matrix"); 139 psFree(output); 140 return NULL; 141 } 142 143 output = psImageRecycle(output, numCols, numRows, type); 144 145 // cover the trival case of copy of the same 146 // datatype. 147 if (type == inDatatype) { 148 memcpy(output->data.V[0], input->data.V[0], elementSize * elements); 135 149 return output; 136 150 } 137 138 151 #define PSIMAGE_ELEMENT_COPY(IN,INTYPE,OUT,OUTTYPE,ELEMENTS) { \ 139 152 ps##INTYPE *in = IN->data.INTYPE[0]; \ … … 186 199 } 187 200 188 switch ( type) {201 switch (type) { 189 202 case PS_TYPE_S8: 190 PSIMAGE_COPY_CASE( output, S8);203 PSIMAGE_COPY_CASE(output, S8); 191 204 break; 192 205 case PS_TYPE_S16: 193 PSIMAGE_COPY_CASE( output, S16);206 PSIMAGE_COPY_CASE(output, S16); 194 207 break; 195 208 case PS_TYPE_S32: 196 PSIMAGE_COPY_CASE( output, S32);209 PSIMAGE_COPY_CASE(output, S32); 197 210 break; 198 211 case PS_TYPE_S64: 199 PSIMAGE_COPY_CASE( output, S64);212 PSIMAGE_COPY_CASE(output, S64); 200 213 break; 201 214 case PS_TYPE_U8: 202 PSIMAGE_COPY_CASE( output, U8);215 PSIMAGE_COPY_CASE(output, U8); 203 216 break; 204 217 case PS_TYPE_U16: 205 PSIMAGE_COPY_CASE( output, U16);218 PSIMAGE_COPY_CASE(output, U16); 206 219 break; 207 220 case PS_TYPE_U32: 208 PSIMAGE_COPY_CASE( output, U32);221 PSIMAGE_COPY_CASE(output, U32); 209 222 break; 210 223 case PS_TYPE_U64: 211 PSIMAGE_COPY_CASE( output, U64);224 PSIMAGE_COPY_CASE(output, U64); 212 225 break; 213 226 case PS_TYPE_F32: 214 PSIMAGE_COPY_CASE( output, F32);227 PSIMAGE_COPY_CASE(output, F32); 215 228 break; 216 229 case PS_TYPE_F64: 217 PSIMAGE_COPY_CASE( output, F64);230 PSIMAGE_COPY_CASE(output, F64); 218 231 break; 219 232 case PS_TYPE_C32: 220 PSIMAGE_COPY_CASE( output, C32);233 PSIMAGE_COPY_CASE(output, C32); 221 234 break; 222 235 case PS_TYPE_C64: 223 PSIMAGE_COPY_CASE( output, C64);236 PSIMAGE_COPY_CASE(output, C64); 224 237 break; 225 238 default: … … 229 242 } 230 243 231 psVector* psImageSlice( psVector* out, 232 psVector* slicePositions, 233 const psImage* restrict in, 234 const psImage* restrict mask, 235 unsigned int maskVal, 236 unsigned int col, 237 unsigned int row, 238 unsigned int numCols, 239 unsigned int numRows, 240 psImageCutDirection direction, 241 const psStats* stats ) 244 psVector *psImageSlice(psVector * out, 245 psVector * slicePositions, 246 const psImage * restrict in, 247 const psImage * restrict mask, 248 unsigned int maskVal, 249 unsigned int col, 250 unsigned int row, 251 unsigned int numCols, 252 unsigned int numRows, psImageCutDirection direction, const psStats * stats) 242 253 { 243 254 double statVal; 244 psStats *myStats;255 psStats *myStats; 245 256 psElemType type; 246 257 int inRows; 247 258 int inCols; 248 259 int delta = 1; 249 psF64* outData; 250 251 if ( in == NULL || in->data.V == NULL ) { 252 psError( __func__, "Input image can not be NULL." ); 253 psFree( out ); 254 return NULL; 255 } 256 257 if ( numRows == 0 || numCols == 0 ) { 258 psError( __func__, "The specified region contains no data (%dx%d)", 259 numCols, numRows ); 260 psFree( out ); 260 psF64 *outData; 261 262 if (in == NULL || in->data.V == NULL) { 263 psError(__func__, "Input image can not be NULL."); 264 psFree(out); 265 return NULL; 266 } 267 268 if (numRows == 0 || numCols == 0) { 269 psError(__func__, "The specified region contains no data (%dx%d)", numCols, numRows); 270 psFree(out); 261 271 return NULL; 262 272 } … … 266 276 inCols = in->numCols; 267 277 268 if ( direction == PS_CUT_X_NEG || direction == PS_CUT_Y_NEG) {278 if (direction == PS_CUT_X_NEG || direction == PS_CUT_Y_NEG) { 269 279 delta = -1; 270 280 } 271 272 // if numRows/numCols is negative, invert the problem to give positive 273 // numRows/numCols (and cut in opposite direction). 274 if ( numRows < 0 ) { 281 // if numRows/numCols is negative, invert the 282 // problem to give positive 283 // numRows/numCols (and cut in opposite 284 // direction). 285 if (numRows < 0) { 275 286 numRows = -numRows; 276 row -= ( numRows - 1);287 row -= (numRows - 1); 277 288 delta = -delta; 278 289 } 279 290 280 if ( numCols < 0) {291 if (numCols < 0) { 281 292 numCols = -numCols; 282 col -= ( numCols - 1);293 col -= (numCols - 1); 283 294 delta = -delta; 284 295 } 285 296 286 if ( mask != NULL) {287 if ( inRows != mask->numRows || inCols != mask->numCols) {288 psError( __func__, "The mask and image dimensions did not match (%dx%d vs %dx%d)",289 mask->numCols, mask->numRows, in->numCols, in->numRows );290 psFree( out);291 }292 if ( mask->type.type != PS_TYPE_MASK ) {293 psError( __func__, "The mask datatype (%d) must be %s.",294 mask->type.type, PS_TYPE_MASK_NAME);295 psFree( out);296 } 297 } 298 299 if ( row >= inRows || col >= inCols ||300 col + numCols > in->numCols || row + numRows > in->numRows ) {301 psError( __func__,"The specified image region (%d,%d to %d,%d) is outside of image area (0,0 to %d,%d).",302 col, row, col + numCols - 1, row + numRows - 1, in->numCols - 1, in->numRows - 1);303 psFree( out);304 return NULL; 305 } 306 307 // verify that the stats struct specifies asingle stats operation308 if ( stats == NULL || p_psGetStatValue( stats, &statVal ) == false) {309 psError( __func__, "The stat options didn't specify a single supported statistic type.");310 psFree( out);311 return NULL; 312 } 313 314 // since stats input is const, I need tocreate a 'scratch' stats struct315 myStats = psAlloc( sizeof( psStats ));297 if (mask != NULL) { 298 if (inRows != mask->numRows || inCols != mask->numCols) { 299 psError(__func__, 300 "The mask and image dimensions did not match (%dx%d vs %dx%d)", 301 mask->numCols, mask->numRows, in->numCols, in->numRows); 302 psFree(out); 303 } 304 if (mask->type.type != PS_TYPE_MASK) { 305 psError(__func__, "The mask datatype (%d) must be %s.", mask->type.type, PS_TYPE_MASK_NAME); 306 psFree(out); 307 } 308 } 309 310 if (row >= inRows || col >= inCols || col + numCols > in->numCols || row + numRows > in->numRows) { 311 psError(__func__, 312 "The specified image region (%d,%d to %d,%d) is outside of image area (0,0 to %d,%d).", 313 col, row, col + numCols - 1, row + numRows - 1, in->numCols - 1, in->numRows - 1); 314 psFree(out); 315 return NULL; 316 } 317 // verify that the stats struct specifies a 318 // single stats operation 319 if (stats == NULL || p_psGetStatValue(stats, &statVal) == false) { 320 psError(__func__, "The stat options didn't specify a single supported statistic type."); 321 psFree(out); 322 return NULL; 323 } 324 // since stats input is const, I need to 325 // create a 'scratch' stats struct 326 myStats = psAlloc(sizeof(psStats)); 316 327 *myStats = *stats; 317 328 318 319 320 if ( direction == PS_CUT_X_POS || direction == PS_CUT_X_NEG ) { 321 psVector * imgVec = psVectorAlloc( numRows, type ); 322 psVector* maskVec = NULL; 323 psMaskType* maskData = NULL; 324 psU32* outPosition = NULL; 325 326 // recycle output to make a proper sized/type output structure 327 // n.b. type is double as that is the type given for all stats in psStats. 328 out = psVectorRecycle( out, numCols, PS_TYPE_F64); 329 if (direction == PS_CUT_X_POS || direction == PS_CUT_X_NEG) { 330 psVector *imgVec = psVectorAlloc(numRows, type); 331 psVector *maskVec = NULL; 332 psMaskType *maskData = NULL; 333 psU32 *outPosition = NULL; 334 335 // recycle output to make a proper 336 // sized/type output structure 337 // n.b. type is double as that is the 338 // type given for all stats in 339 // psStats. 340 out = psVectorRecycle(out, numCols, PS_TYPE_F64); 329 341 if (slicePositions != NULL) { 330 slicePositions = psVectorRecycle(slicePositions, numCols,PS_TYPE_U32);342 slicePositions = psVectorRecycle(slicePositions, numCols, PS_TYPE_U32); 331 343 outPosition = slicePositions->data.U32; 332 344 } 333 345 outData = out->data.F64; 334 if ( delta < 0) {346 if (delta < 0) { 335 347 outData += numCols - 1; 336 348 if (outPosition != NULL) { … … 339 351 } 340 352 341 if ( mask != NULL ) { 342 maskVec = psVectorAlloc( numRows, mask->type.type ); 343 } 344 353 if (mask != NULL) { 354 maskVec = psVectorAlloc(numRows, mask->type.type); 355 } 345 356 #define PSIMAGE_CUT_VERTICAL(TYPE) \ 346 357 case PS_TYPE_##TYPE: { \ … … 373 384 } 374 385 375 switch ( type) {376 PSIMAGE_CUT_VERTICAL( U8);377 PSIMAGE_CUT_VERTICAL( U16);378 PSIMAGE_CUT_VERTICAL( U32);379 PSIMAGE_CUT_VERTICAL( U64);380 PSIMAGE_CUT_VERTICAL( S8);381 PSIMAGE_CUT_VERTICAL( S16);382 PSIMAGE_CUT_VERTICAL( S32);383 PSIMAGE_CUT_VERTICAL( S64);384 PSIMAGE_CUT_VERTICAL( F32);385 PSIMAGE_CUT_VERTICAL( F64);386 PSIMAGE_CUT_VERTICAL( C32);387 PSIMAGE_CUT_VERTICAL( C64);386 switch (type) { 387 PSIMAGE_CUT_VERTICAL(U8); 388 PSIMAGE_CUT_VERTICAL(U16); 389 PSIMAGE_CUT_VERTICAL(U32); 390 PSIMAGE_CUT_VERTICAL(U64); 391 PSIMAGE_CUT_VERTICAL(S8); 392 PSIMAGE_CUT_VERTICAL(S16); 393 PSIMAGE_CUT_VERTICAL(S32); 394 PSIMAGE_CUT_VERTICAL(S64); 395 PSIMAGE_CUT_VERTICAL(F32); 396 PSIMAGE_CUT_VERTICAL(F64); 397 PSIMAGE_CUT_VERTICAL(C32); 398 PSIMAGE_CUT_VERTICAL(C64); 388 399 default: 389 psError( __func__, "Unsupported datatype (%d)", type);390 psFree( out);400 psError(__func__, "Unsupported datatype (%d)", type); 401 psFree(out); 391 402 out = NULL; 392 403 } 393 psFree( imgVec ); 394 psFree( maskVec ); 395 } else 396 if ( direction == PS_CUT_Y_POS || direction == PS_CUT_Y_NEG ) { // Cut in Y direction 397 psVector * imgVec = NULL; 398 psVector* maskVec = NULL; 399 int elementSize = PSELEMTYPE_SIZEOF( type ); 400 psU32* outPosition = NULL; 401 402 // fill in psVectors to fake out the statistics functions. 403 imgVec = psAlloc( sizeof( psVector ) ); 404 imgVec->type = in->type; 405 imgVec->n = imgVec->nalloc = numCols; 406 if ( mask != NULL ) { 407 maskVec = psAlloc( sizeof( psVector ) ); 408 maskVec->type = mask->type; 409 maskVec->n = maskVec->nalloc = numCols; 404 psFree(imgVec); 405 psFree(maskVec); 406 } else if (direction == PS_CUT_Y_POS || direction == PS_CUT_Y_NEG) { // Cut 407 // 408 // 409 // 410 // 411 // 412 // 413 // 414 // 415 // 416 // in 417 // Y 418 // direction 419 psVector *imgVec = NULL; 420 psVector *maskVec = NULL; 421 int elementSize = PSELEMTYPE_SIZEOF(type); 422 psU32 *outPosition = NULL; 423 424 // fill in psVectors to fake out the 425 // statistics functions. 426 imgVec = psAlloc(sizeof(psVector)); 427 imgVec->type = in->type; 428 imgVec->n = imgVec->nalloc = numCols; 429 if (mask != NULL) { 430 maskVec = psAlloc(sizeof(psVector)); 431 maskVec->type = mask->type; 432 maskVec->n = maskVec->nalloc = numCols; 433 } 434 // recycle output to make a proper 435 // sized/type output structure 436 // n.b. type is double as that is the 437 // type given for all stats in 438 // psStats. 439 out = psVectorRecycle(out, numRows, PS_TYPE_F64); 440 if (slicePositions != NULL) { 441 slicePositions = psVectorRecycle(slicePositions, numRows, PS_TYPE_U32); 442 outPosition = slicePositions->data.U32; 443 } 444 outData = out->data.F64; 445 if (delta < 0) { 446 outData += numRows - 1; 447 if (outPosition != NULL) { 448 outPosition += numRows - 1; 410 449 } 411 412 // recycle output to make a proper sized/type output structure 413 // n.b. type is double as that is the type given for all stats in psStats. 414 out = psVectorRecycle( out, numRows, PS_TYPE_F64 ); 415 if (slicePositions != NULL) { 416 slicePositions = psVectorRecycle(slicePositions,numRows,PS_TYPE_U32); 417 outPosition = slicePositions->data.U32; 450 } 451 452 for (int r = 0; r < numRows; r++) { 453 // point the vector struct to the 454 // data to calculate the stats 455 imgVec->data.V = (void *)(in->data.U8[row + r] + col * elementSize); 456 if (maskVec != NULL) { 457 maskVec->data.V = (void *)(mask->data.U8[row + r] + col * sizeof(psMaskType)); 418 458 } 419 outData = out->data.F64; 420 if ( delta < 0 ) { 421 outData += numRows - 1; 422 if (outPosition != NULL) { 423 outPosition += numRows - 1; 424 } 459 myStats = psVectorStats(myStats, imgVec, maskVec, maskVal); 460 (void)p_psGetStatValue(myStats, &statVal); // we 461 // know 462 // it 463 // works 464 // cause we tested it 465 // above 466 *outData = statVal; 467 if (outPosition != NULL) { 468 *outPosition = row + r; 469 outPosition += delta; 470 425 471 } 426 427 for ( int r = 0;r < numRows;r++ ) { 428 // point the vector struct to the data to calculate the stats 429 imgVec->data.V = ( void* ) ( in->data.U8[ row + r ] + col * elementSize ); 430 if ( maskVec != NULL ) { 431 maskVec->data.V = ( void* ) ( mask->data.U8[ row + r ] + col * sizeof( psMaskType ) ); 432 } 433 myStats = psVectorStats( myStats, imgVec, maskVec, maskVal ); 434 ( void ) p_psGetStatValue( myStats, &statVal ); // we know it works cause we tested it above 435 *outData = statVal; 436 if (outPosition != NULL) { 437 *outPosition = row+r; 438 outPosition += delta; 439 \ 440 } 441 outData += delta; 442 } 443 psFree( imgVec ); 444 psFree( maskVec ); 445 } else { // don't know what the direction flag is 446 psError( __func__, "Invalid direction flag (%d)", direction ); 447 psFree( out ); 448 out = NULL; 449 } 450 451 psFree( myStats ); 472 outData += delta; 473 } 474 psFree(imgVec); 475 psFree(maskVec); 476 } else { // don't 477 // know 478 // what 479 // the 480 // direction 481 // flag 482 // is 483 psError(__func__, "Invalid direction flag (%d)", direction); 484 psFree(out); 485 out = NULL; 486 } 487 488 psFree(myStats); 452 489 453 490 return out; 454 491 } 455 -
trunk/psLib/src/image/psImageExtraction.h
r1404 r1407 1 1 2 /** @file psImageExtraction.h 2 3 * … … 9 10 * @author Robert DeSonia, MHPCC 10 11 * 11 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 21:50:13$12 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 16 17 17 18 #ifndef PSIMAGEEXTRACTION_H 18 # define PSIMAGEEXTRACTION_H19 # define PSIMAGEEXTRACTION_H 19 20 20 # include "psImage.h"21 # include "psVector.h"22 # include "psStats.h"21 # include "psImage.h" 22 # include "psVector.h" 23 # include "psStats.h" 23 24 24 25 /// @addtogroup Image … … 40 41 * 41 42 */ 42 psImage *psImageSubset( 43 psImage *out, ///< Subimage to return, or NULL. 44 psImage *image, ///< Parent image. 45 unsigned int numCols, ///< Subimage width (<= image.nCols - col0). 46 unsigned int numRows, ///< Subimage height (<= image.nRows - row0). 47 unsigned int col0, ///< Subimage col-offset (0 <= col0 < nCol). 48 unsigned int row0 ///< Subimage row-offset (0 <= row0 < nCol). 49 ); 43 psImage *psImageSubset(psImage * out, // /< Subimage to return, or NULL. 44 psImage * image, // /< Parent image. 45 unsigned int numCols, // /< Subimage width (<= image.nCols - col0). 46 unsigned int numRows, // /< Subimage height (<= image.nRows - row0). 47 unsigned int col0, // /< Subimage col-offset (0 <= col0 < nCol). 48 unsigned int row0 // /< Subimage row-offset (0 <= row0 < nCol). 49 ); 50 50 51 51 /** Makes a copy of a psImage … … 55 55 * 56 56 */ 57 psImage *psImageCopy( 58 psImage* restrict output, 59 /**< if not NULL, a psImage that could be recycled. If it can not be used, 60 * it will be freed via psImageFree 61 */ 62 const psImage *input, 63 /**< the psImage to copy */ 64 psElemType type 65 /**< the desired datatype of the returned copy */ 66 ); 57 psImage *psImageCopy(psImage * restrict output, 67 58 68 psVector* psImageSlice( 69 psVector* out, 70 psVector* slicePositions, 71 const psImage* restrict input, 72 const psImage* restrict mask, 73 unsigned int maskVal, 74 unsigned int col, 75 unsigned int row, 76 unsigned int numCols, 77 unsigned int numRows, 78 psImageCutDirection direction, 79 const psStats* stats 80 ); 59 /**< if not NULL, a psImage that could be recycled. If it can not be used, 60 * it will be freed via psImageFree 61 */ 62 const psImage * input, 81 63 82 psVector* psImageCut( 83 psVector* out, 84 const psImage* input, 85 const psImage* restrict mask, 86 unsigned int maskVal, 87 float startCol, 88 float startRow, 89 float endCol, 90 float endRow, 91 float width, 92 const psStats* stats 93 ); 64 /**< the psImage to copy */ 65 psElemType type 94 66 95 psVector* psImageRadialCut( 96 psVector* out, 97 const psImage* input, 98 const psImage* restrict mask, 99 unsigned int maskVal, 100 float centerCol, 101 float centerRow, 102 const psVector* radii, 103 const psStats* stats 104 ); 67 /**< the desired datatype of the returned copy */ 68 ); 69 70 psVector *psImageSlice(psVector * out, 71 psVector * slicePositions, 72 const psImage * restrict input, 73 const psImage * restrict mask, 74 unsigned int maskVal, 75 unsigned int col, 76 unsigned int row, 77 unsigned int numCols, 78 unsigned int numRows, psImageCutDirection direction, const psStats * stats); 79 80 psVector *psImageCut(psVector * out, 81 const psImage * input, 82 const psImage * restrict mask, 83 unsigned int maskVal, 84 float startCol, 85 float startRow, float endCol, float endRow, float width, const psStats * stats); 86 87 psVector *psImageRadialCut(psVector * out, 88 const psImage * input, 89 const psImage * restrict mask, 90 unsigned int maskVal, 91 float centerCol, float centerRow, const psVector * radii, const psStats * stats); 105 92 106 93 /// @} -
trunk/psLib/src/image/psImageIO.c
r1406 r1407 1 1 2 /** @file psImageIO.c 2 3 * … … 7 8 * @author Robert DeSonia, MHPCC 8 9 * 9 * @version $Revision: 1. 8$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.9 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 21 22 #include "psMemory.h" 22 23 23 psImage* psImageReadSection(psImage* output, int col, int row, int numCols, 24 int numRows, int z, char* extname, int extnum, char* filename) 24 psImage *psImageReadSection(psImage * output, 25 int col, 26 int row, 27 int numCols, int numRows, int z, char *extname, int extnum, char *filename) 25 28 { 26 fitsfile *fptr=NULL; /*Pointer to the FITS file*/27 int status=0; /*CFITSIO file vars*/28 int nAxis=0;29 int anynull=0;30 int bitPix=0; /*Pixel type*/31 long nAxes[3];32 long firstPixel[3];/* lower-left corner of image subset */33 long lastPixel[3];/* upper-right corner of image subset */34 long increment[3];/* increment for image subset */35 char fitsErr[80] = ""; /*CFITSIO error message string */36 int hduType = IMAGE_HDU;37 int fitsDatatype = 0;38 int datatype = 0;29 fitsfile *fptr = NULL; /* Pointer to the FITS file */ 30 int status = 0; /* CFITSIO file vars */ 31 int nAxis = 0; 32 int anynull = 0; 33 int bitPix = 0; /* Pixel type */ 34 long nAxes[3]; 35 long firstPixel[3]; /* lower-left corner of image subset */ 36 long lastPixel[3]; /* upper-right corner of image subset */ 37 long increment[3]; /* increment for image subset */ 38 char fitsErr[80] = ""; /* CFITSIO error message string */ 39 int hduType = IMAGE_HDU; 40 int fitsDatatype = 0; 41 int datatype = 0; 39 42 40 43 if (filename == NULL) { 41 psError(__func__, "Must specify filename; it can not be NULL.");44 psError(__func__, "Must specify filename; it can not be NULL."); 42 45 psFree(output); 43 46 return NULL; … … 47 50 (void)fits_open_file(&fptr, filename, READONLY, &status); 48 51 if (fptr == NULL || status != 0) { 49 fits_get_errstatus(status,fitsErr); 50 psError(__func__,"Could not open file '%s'. (%s)", 51 filename, fitsErr); 52 fits_get_errstatus(status, fitsErr); 53 psError(__func__, "Could not open file '%s'. (%s)", filename, fitsErr); 52 54 psFree(output); 53 55 return NULL; … … 56 58 /* find the specified extension */ 57 59 if (extname != NULL) { 58 if (fits_movnam_hdu(fptr, hduType, extname, 0, &status) != 0) {60 if (fits_movnam_hdu(fptr, hduType, extname, 0, &status) != 0) { 59 61 fits_get_errstatus(status, fitsErr); 60 62 status = 0; 61 63 (void)fits_close_file(fptr, &status); 62 psError(__func__,"Could not index to '%s' HDU for file %s. (%s)", 63 extname, filename, fitsErr); 64 psError(__func__, "Could not index to '%s' HDU for file %s. (%s)", extname, filename, fitsErr); 64 65 psFree(output); 65 66 return NULL; 66 67 } 67 68 } else { 68 if (fits_movabs_hdu(fptr, extnum +1, &hduType, &status) != 0) {69 if (fits_movabs_hdu(fptr, extnum + 1, &hduType, &status) != 0) { 69 70 fits_get_errstatus(status, fitsErr); 70 71 status = 0; 71 72 (void)fits_close_file(fptr, &status); 72 psError(__func__,"Could not index to HDU #%d for file %s. (%s)", 73 extnum, filename, fitsErr); 73 psError(__func__, "Could not index to HDU #%d for file %s. (%s)", extnum, filename, fitsErr); 74 74 psFree(output); 75 75 return NULL; … … 82 82 status = 0; 83 83 (void)fits_close_file(fptr, &status); 84 psError("Could not determine image data type of '%s'. (%s)", 85 filename, fitsErr); 84 psError("Could not determine image data type of '%s'. (%s)", filename, fitsErr); 86 85 psFree(output); 87 86 return NULL; … … 93 92 status = 0; 94 93 (void)fits_close_file(fptr, &status); 95 psError("Could not determine dimensions of '%s'. (%s)", 96 filename,fitsErr); 94 psError("Could not determine dimensions of '%s'. (%s)", filename, fitsErr); 97 95 psFree(output); 98 96 return NULL; … … 100 98 101 99 /* Validate the number of axis */ 102 if ( (nAxis < 2) || (nAxis > 3) ) { 103 status=0; 104 (void)fits_close_file(fptr, &status); 105 psError("Dimensions of '%s' are not supported (NAXIS=%i).", 106 filename, nAxis); 107 psFree(output); 108 return NULL; 109 } 110 111 /* Get the Image size from the FITS file */ 112 if ( fits_get_img_size(fptr, nAxis, nAxes, &status) != 0) { 100 if ((nAxis < 2) || (nAxis > 3)) { 101 status = 0; 102 (void)fits_close_file(fptr, &status); 103 psError("Dimensions of '%s' are not supported (NAXIS=%i).", filename, nAxis); 104 psFree(output); 105 return NULL; 106 } 107 108 /* Get the Image size from the FITS file */ 109 if (fits_get_img_size(fptr, nAxis, nAxes, &status) != 0) { 113 110 (void)fits_get_errstatus(status, fitsErr); 114 111 status = 0; 115 112 (void)fits_close_file(fptr, &status); 116 psError("Could not determine image size of '%s'. (%s)", 117 filename,fitsErr); 113 psError("Could not determine image size of '%s'. (%s)", filename, fitsErr); 118 114 psFree(output); 119 115 return NULL; … … 127 123 } 128 124 129 firstPixel[0] = col +1;130 firstPixel[1] = row +1;131 firstPixel[2] = z +1;125 firstPixel[0] = col + 1; 126 firstPixel[1] = row + 1; 127 firstPixel[2] = z + 1; 132 128 133 129 lastPixel[0] = firstPixel[0] + numCols - 1; 134 130 lastPixel[1] = firstPixel[1] + numRows - 1; 135 lastPixel[2] = z +1;131 lastPixel[2] = z + 1; 136 132 137 133 increment[0] = 1; … … 139 135 increment[2] = 1; 140 136 141 // turn off the BSCALE/BZERO processing in CFITSIO 142 // (void)fits_set_bscale(fptr, 1.0,0.0,&status); 137 // turn off the BSCALE/BZERO processing in 138 // CFITSIO 139 // (void)fits_set_bscale(fptr, 140 // 1.0,0.0,&status); 143 141 144 142 switch (bitPix) { … … 180 178 break; 181 179 default: 182 psError(__func__, "Unsupported bitpix value (%d) in FITS file %s.",183 bitPix,filename);184 psFree(output);185 return NULL;186 }187 output = psImageRecycle(output,numCols,numRows,datatype);188 if (fits_read_subset(fptr, fitsDatatype, firstPixel, lastPixel, increment,189 NULL, output->data.V[0], &anynull, &status) != 0) {180 psError(__func__, "Unsupported bitpix value (%d) in FITS file %s.", bitPix, filename); 181 psFree(output); 182 return NULL; 183 } 184 output = psImageRecycle(output, numCols, numRows, datatype); 185 if (fits_read_subset 186 (fptr, fitsDatatype, firstPixel, 187 lastPixel, increment, NULL, output->data.V[0], &anynull, &status) != 0) { 190 188 psFree(output); 191 189 (void)fits_get_errstatus(status, fitsErr); 192 190 status = 0; 193 191 (void)fits_close_file(fptr, &status); 194 psError(__func__,"Failed to read image [%s]", 195 filename, fitsErr); 192 psError(__func__, "Failed to read image [%s]", filename, fitsErr); 196 193 return NULL; 197 194 } … … 202 199 } 203 200 204 205 bool psImageWriteSection(psImage* input, int col0,int row0,int z, 206 char* extname, int extnum, char* filename) 201 bool psImageWriteSection(psImage * input, int col0, int row0, int z, char *extname, int extnum, 202 char *filename) 207 203 { 208 int numCols = 0;209 int numRows = 0;210 211 int status=0; /* CFITSIOstatus */212 fitsfile *fptr=NULL;/* pointer to the FITS file */213 long nAxes[3];/* Image axis vars */214 long firstPixel[3];/* First Pixel to read */215 long lastPixel[3];/* Last Pixel to read */216 char fitsErr[80];/* FITSIO message string */217 int datatype = 0; /* the datatype of the image */218 int bitPix = 0; /* FITS bitPix value */219 int hduType = IMAGE_HDU; /* the HDU type (image,table, etc.) */220 double bscale = 1.0;221 double bzero = 0.0;222 bool createNewHDU = false;204 int numCols = 0; 205 int numRows = 0; 206 207 int status = 0; /* CFITSIO status */ 208 fitsfile *fptr = NULL; /* pointer to the FITS file */ 209 long nAxes[3]; /* Image axis vars */ 210 long firstPixel[3]; /* First Pixel to read */ 211 long lastPixel[3]; /* Last Pixel to read */ 212 char fitsErr[80]; /* FITSIO message string */ 213 int datatype = 0; /* the datatype of the image */ 214 int bitPix = 0; /* FITS bitPix value */ 215 int hduType = IMAGE_HDU; /* the HDU type (image,table, etc.) */ 216 double bscale = 1.0; 217 double bzero = 0.0; 218 bool createNewHDU = false; 223 219 224 220 /* need a valid image to write */ 225 if(input==NULL) { 226 psError(__func__, "Can not write %s. Input psImage is NULL.", 227 filename); 221 if (input == NULL) { 222 psError(__func__, "Can not write %s. Input psImage is NULL.", filename); 228 223 return false; 229 224 } … … 244 239 case PS_TYPE_U16: 245 240 bitPix = SHORT_IMG; 246 bzero = -1.0f *INT16_MIN;241 bzero = -1.0f * INT16_MIN; 247 242 datatype = TUSHORT; 248 243 break; … … 253 248 case PS_TYPE_U32: 254 249 bitPix = LONG_IMG; 255 bzero = -1.0f *INT32_MIN;250 bzero = -1.0f * INT32_MIN; 256 251 datatype = TUINT; 257 252 break; … … 269 264 break; 270 265 default: 271 psError(__func__, "psImage datatype (%d) not supported. File %s not written.",272 input->type.type,filename);266 psError(__func__, 267 "psImage datatype (%d) not supported. File %s not written.", input->type.type, filename); 273 268 return false; 274 269 } 275 270 276 271 /* Open the FITS file */ 277 if (access(filename, F_OK) == 0) { // file exists 272 if (access(filename, F_OK) == 0) { // file 273 // exists 278 274 (void)fits_open_file(&fptr, filename, READWRITE, &status); 279 275 if (fptr == NULL || status != 0) { 280 fits_get_errstatus(status,fitsErr); 281 psError(__func__,"Could not open file '%s'. FITS error:%s", 282 filename, fitsErr); 276 fits_get_errstatus(status, fitsErr); 277 psError(__func__, "Could not open file '%s'. FITS error:%s", filename, fitsErr); 283 278 return false; 284 279 } … … 286 281 /* find the specified extension */ 287 282 if (extname != NULL) { 288 if (fits_movnam_hdu(fptr, hduType, extname, 0, &status) != 0) {283 if (fits_movnam_hdu(fptr, hduType, extname, 0, &status) != 0) { 289 284 fits_get_errstatus(status, fitsErr); 290 285 status = 0; 291 286 (void)fits_close_file(fptr, &status); 292 psError(__func__, "Could not index to '%s' HDU for file %s. (%s)",293 extname, filename, fitsErr);287 psError(__func__, 288 "Could not index to '%s' HDU for file %s. (%s)", extname, filename, fitsErr); 294 289 return false; 295 290 } 296 291 } else { 297 292 int numHDUs = 0; 298 fits_get_num_hdus(fptr,&numHDUs,&status); 293 294 fits_get_num_hdus(fptr, &numHDUs, &status); 299 295 if (numHDUs < extnum) { 300 296 status = 0; 301 297 (void)fits_close_file(fptr, &status); 302 psError(__func__, "extnum (%d) must not exceed number of HDUs (%d) by more than one.",303 extnum, numHDUs);298 psError(__func__, 299 "extnum (%d) must not exceed number of HDUs (%d) by more than one.", extnum, numHDUs); 304 300 return false; 305 } else 306 if (numHDUs == extnum) {307 createNewHDU = true;308 } else309 if (fits_movabs_hdu(fptr, extnum+1, &hduType, &status) != 0) {310 fits_get_errstatus(status, fitsErr);311 status = 0;312 (void)fits_close_file(fptr, &status);313 psError(__func__,"Could not index to HDU #%d for file %s. (%s)",314 extnum, filename, fitsErr);315 return false; 316 }317 }318 319 } else { // file does notexist320 321 (void)fits_create_file(&fptr, filename,&status);301 } else if (numHDUs == extnum) { 302 createNewHDU = true; 303 } else if (fits_movabs_hdu(fptr, extnum + 1, &hduType, &status) != 0) { 304 fits_get_errstatus(status, fitsErr); 305 status = 0; 306 (void)fits_close_file(fptr, &status); 307 psError(__func__, "Could not index to HDU #%d for file %s. (%s)", extnum, filename, fitsErr); 308 return false; 309 } 310 } 311 312 } else { // file 313 // does 314 // not 315 // exist 316 317 (void)fits_create_file(&fptr, filename, &status); 322 318 if (fptr == NULL || status != 0) { 323 fits_get_errstatus(status,fitsErr); 324 psError(__func__,"Could not create file '%s'. (%s)", 325 filename, fitsErr); 319 fits_get_errstatus(status, fitsErr); 320 psError(__func__, "Could not create file '%s'. (%s)", filename, fitsErr); 326 321 return false; 327 322 } … … 330 325 331 326 if (createNewHDU) { 332 /* create the mandatory image keywords */333 nAxes[0] = col0 +numCols;334 nAxes[1] = row0 +numRows;335 nAxes[2] = z +1;327 /* create the mandatory image keywords */ 328 nAxes[0] = col0 + numCols; 329 nAxes[1] = row0 + numRows; 330 nAxes[2] = z + 1; 336 331 if (fits_create_img(fptr, bitPix, 3, nAxes, &status) != 0) { 337 332 (void)fits_get_errstatus(status, fitsErr); 338 333 status = 0; 339 334 (void)fits_close_file(fptr, &status); 340 psError(__func__,"Could not create image HDU in FITS file '%s'. %s", 341 filename, fitsErr); 335 psError(__func__, "Could not create image HDU in FITS file '%s'. %s", filename, fitsErr); 342 336 return false; 343 337 } 344 345 338 // set the bscale/bzero 346 fits_write_key_dbl(fptr, "BZERO", bzero,12,"Pixel Value Offset",&status);347 fits_write_key_dbl(fptr, "BSCALE", bscale,12,"Pixel Value Scale",&status);348 fits_set_bscale(fptr, bscale,bzero,&status);339 fits_write_key_dbl(fptr, "BZERO", bzero, 12, "Pixel Value Offset", &status); 340 fits_write_key_dbl(fptr, "BSCALE", bscale, 12, "Pixel Value Scale", &status); 341 fits_set_bscale(fptr, bscale, bzero, &status); 349 342 350 343 if (extname != NULL) { … … 354 347 status = 0; 355 348 (void)fits_close_file(fptr, &status); 356 psError(__func__, "Could not create EXTNAME keyword in FITS file '%s'. (%s)",357 filename, fitsErr);349 psError(__func__, 350 "Could not create EXTNAME keyword in FITS file '%s'. (%s)", filename, fitsErr); 358 351 return false; 359 352 } … … 361 354 } 362 355 363 firstPixel[0] = col0 +1;364 firstPixel[1] = row0 +1;365 firstPixel[2] = z +1;356 firstPixel[0] = col0 + 1; 357 firstPixel[1] = row0 + 1; 358 firstPixel[2] = z + 1; 366 359 367 360 lastPixel[0] = firstPixel[0] + numCols - 1; 368 361 lastPixel[1] = firstPixel[1] + numRows - 1; 369 lastPixel[2] = z +1;370 371 if ( fits_write_subset(fptr, datatype, firstPixel, lastPixel, input->data.V[0], &status) != 0) {362 lastPixel[2] = z + 1; 363 364 if (fits_write_subset(fptr, datatype, firstPixel, lastPixel, input->data.V[0], &status) != 0) { 372 365 (void)fits_get_errstatus(status, fitsErr); 373 366 status = 0; 374 367 (void)fits_close_file(fptr, &status); 375 psError(__func__, "Could not write image data to '%s'. (%s)", 376 filename, fitsErr); 368 psError(__func__, "Could not write image data to '%s'. (%s)", filename, fitsErr); 377 369 return false; 378 370 } -
trunk/psLib/src/image/psImageIO.h
r1241 r1407 1 1 2 /** @file psImageIO.h 2 3 * … … 9 10 * @author Robert DeSonia, MHPCC 10 11 * 11 * @version $Revision: 1. 3$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-0 7-19 22:01:19$12 * @version $Revision: 1.4 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 # ifndef PS_IMAGEIO_H17 # define PS_IMAGEIO_H17 #ifndef PS_IMAGEIO_H 18 # define PS_IMAGEIO_H 18 19 19 # include <stdbool.h>20 # include <stdbool.h> 20 21 21 # include "psImage.h"22 # include "psImage.h" 22 23 23 24 /// @addtogroup ImageIO … … 29 30 * signifies that a problem had occured. 30 31 */ 31 psImage* psImageReadSection( 32 psImage* output, 33 /**< the output psImage to recycle, or NULL if new psImage desired */ 34 int col0, 35 /**< the column index of the origin to start reading */ 36 int row0, 37 /**< the row index of the origin to start reading */ 38 int numCols, 39 /**< the number of desired columns to read */ 40 int numRows, 41 /**< the number of desired rows to read */ 42 int z, 43 /**< the z index to read if file is organized as a 3D image cube. */ 44 char* extname, 45 /**< the image extension to read (this should match the EXTNAME keyword in 46 * the extension If NULL, the extnum parameter is to be used instead 47 */ 48 int extnum, 49 /**< the image extension to read (0=PHU, 1=first extension, etc.) This is 50 * only used if extname is NULL 51 */ 52 char* filename 53 /**< the filename of the FITS image file to read */ 54 ); 32 psImage *psImageReadSection(psImage * output, 33 34 /**< the output psImage to recycle, or NULL if new psImage desired */ 35 int col0, 36 37 /**< the column index of the origin to start reading */ 38 int row0, 39 40 /**< the row index of the origin to start reading */ 41 int numCols, 42 43 /**< the number of desired columns to read */ 44 int numRows, 45 46 /**< the number of desired rows to read */ 47 int z, 48 49 /**< the z index to read if file is organized as a 3D image cube. */ 50 char *extname, 51 52 /**< the image extension to read (this should match the EXTNAME keyword in 53 * the extension If NULL, the extnum parameter is to be used instead 54 */ 55 int extnum, 56 57 /**< the image extension to read (0=PHU, 1=first extension, etc.) This is 58 * only used if extname is NULL 59 */ 60 char *filename 61 62 /**< the filename of the FITS image file to read */ 63 ); 55 64 56 65 /** Read an image or subimage from a FITS file specified by a filename. … … 58 67 * return bool TRUE is successful, otherwise FALSE. 59 68 */ 60 bool psImageWriteSection( 61 psImage* input, 62 /**< the psImage to write */ 63 int col0, 64 /**< the column index of the origin to start writing */ 65 int row0, 66 /**< the row index of the origin to start writing */ 67 int z, 68 /**< the z index to start writing */ 69 char* extname, 70 /**< the image extension to write (this should match the EXTNAME keyword in 71 * the extension If NULL, the extnum parameter is to be used instead 72 */ 73 int extnum, 74 /**< the image extension to write (0=PHU, 1=first extension, etc.) This is 75 * only used if extname is NULL. 76 */ 77 char* filename 78 /**< the filename of the FITS image file to write */ 79 ); 69 bool psImageWriteSection(psImage * input, 70 71 /**< the psImage to write */ 72 int col0, 73 74 /**< the column index of the origin to start writing */ 75 int row0, 76 77 /**< the row index of the origin to start writing */ 78 int z, 79 80 /**< the z index to start writing */ 81 char *extname, 82 83 /**< the image extension to write (this should match the EXTNAME keyword in 84 * the extension If NULL, the extnum parameter is to be used instead 85 */ 86 int extnum, 87 88 /**< the image extension to write (0=PHU, 1=first extension, etc.) This is 89 * only used if extname is NULL. 90 */ 91 char *filename 92 93 /**< the filename of the FITS image file to write */ 94 ); 80 95 81 96 /// @} -
trunk/psLib/src/image/psImageManip.c
r1406 r1407 1 1 2 /** @file psImageManip.c 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 0$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.11 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 #include <math.h> // for isfinite(), etc. 18 #include <math.h> // for 19 // isfinite(), 20 // etc. 18 21 #include <stdlib.h> 19 22 #include <stdbool.h> 20 #include <string.h> // for memcpy, etc. 23 #include <string.h> // for 24 // memcpy, 25 // etc. 21 26 22 27 #include "psError.h" … … 26 31 #include "psImageExtraction.h" 27 32 28 int psImageClip(psImage * input, psF64 min, psF64 vmin, psF64 max, psF64 vmax)33 int psImageClip(psImage * input, psF64 min, psF64 vmin, psF64 max, psF64 vmax) 29 34 { 30 35 int numClipped = 0; … … 37 42 38 43 if (max < min) { 39 psError(__func__, "psImageClip can not be invoked with max < min.");44 psError(__func__, "psImageClip can not be invoked with max < min."); 40 45 return 0; 41 46 } … … 100 105 break; 101 106 102 psImageClipCase(S8, "psS8")103 psImageClipCase(S16, "psS16")104 psImageClipCase(S32, "psS32")105 psImageClipCase(S64, "psS64")106 psImageClipCase(U8, "psU8")107 psImageClipCase(U16, "psU16")108 psImageClipCase(U32, "psU32")109 psImageClipCase(U64, "psU64")110 psImageClipCase(F32, "psF32")111 psImageClipCase(F64, "psF64")112 psImageClipCaseComplex(C32, "psC32",cabsf)113 psImageClipCaseComplex(C64, "psC64",cabs)107 psImageClipCase(S8, "psS8") 108 psImageClipCase(S16, "psS16") 109 psImageClipCase(S32, "psS32") 110 psImageClipCase(S64, "psS64") 111 psImageClipCase(U8, "psU8") 112 psImageClipCase(U16, "psU16") 113 psImageClipCase(U32, "psU32") 114 psImageClipCase(U64, "psU64") 115 psImageClipCase(F32, "psF32") 116 psImageClipCase(F64, "psF64") 117 psImageClipCaseComplex(C32, "psC32", cabsf) 118 psImageClipCaseComplex(C64, "psC64", cabs) 114 119 115 120 default: 116 psError(__func__,"psImageClip does not support the given datatype (%d)", 117 input->type.type); 121 psError(__func__, "psImageClip does not support the given datatype (%d)", input->type.type); 118 122 } 119 123 … … 121 125 } 122 126 123 int psImageClipNaN(psImage * input,psF64 value)127 int psImageClipNaN(psImage * input, psF64 value) 124 128 { 125 129 int numClipped = 0; … … 154 158 155 159 default: 156 psError(__func__,"psImageClip does not support the given datatype (%d)", 157 input->type.type); 160 psError(__func__, "psImageClip does not support the given datatype (%d)", input->type.type); 158 161 } 159 162 … … 161 164 } 162 165 163 int psImageOverlaySection(psImage* image, const psImage* overlay, int col0, 164 int row0, const char* op) 166 int psImageOverlaySection(psImage * image, const psImage * overlay, int col0, int row0, const char *op) 165 167 { 166 168 unsigned int imageNumRows; … … 170 172 unsigned int imageRowLimit; 171 173 unsigned int imageColLimit; 172 psElemType type;174 psElemType type; 173 175 174 176 if (image == NULL || overlay == NULL) { 175 psError(__func__, "one of the input images was NULL.");177 psError(__func__, "one of the input images was NULL."); 176 178 return 1; 177 179 } 178 180 179 181 if (op == NULL) { 180 psError(__func__, "Operation can not be NULL.");182 psError(__func__, "Operation can not be NULL."); 181 183 return 1; 182 184 } … … 185 187 186 188 if (type != overlay->type.type) { 187 psError(__func__,"Image and overlay datatypes must match. (%d vs %d)", 188 type,overlay->type.type); 189 psError(__func__, "Image and overlay datatypes must match. (%d vs %d)", type, overlay->type.type); 189 190 return 2; 190 191 } … … 197 198 /* check row0/col0 to see if it is within the image size */ 198 199 if (row0 < 0 || col0 < 0 || row0 >= imageNumRows || col0 >= imageNumCols) { 199 psError(__func__, "Overlay origin of (%d,%d) is outside of the image dimensions (%d x %d).", 200 psError(__func__, 201 "Overlay origin of (%d,%d) is outside of the image dimensions (%d x %d).", 200 202 col0, row0, imageNumCols, imageNumRows); 201 203 return 3; … … 203 205 204 206 /* check if overlay is totally withing input image */ 205 imageRowLimit = row0 +overlayNumRows;206 imageColLimit = col0 +overlayNumCols;207 imageRowLimit = row0 + overlayNumRows; 208 imageColLimit = col0 + overlayNumCols; 207 209 if (imageRowLimit > imageNumRows || imageColLimit > imageNumCols) { 208 psError(__func__, "Overlay image (%d,%d -> %d,%d) is partially outside" 210 psError(__func__, 211 "Overlay image (%d,%d -> %d,%d) is partially outside" 209 212 " of the input image (%d x %d).", 210 col0, row0, col0+overlayNumCols-1, row0+overlayNumRows-1, 211 imageNumCols,imageNumRows); 213 col0, row0, col0 + overlayNumCols - 1, row0 + overlayNumRows - 1, imageNumCols, imageNumRows); 212 214 return 4; 213 215 } … … 259 261 260 262 default: 261 psError(__func__, "Can not operate on type %d.",type);263 psError(__func__, "Can not operate on type %d.", type); 262 264 } 263 265 … … 265 267 } 266 268 267 int psImageClipComplexRegion(psImage * input, psC64 min, psC64 vmin, psC64 max, psC64 vmax)269 int psImageClipComplexRegion(psImage * input, psC64 min, psC64 vmin, psC64 max, psC64 vmax) 268 270 { 269 271 int numClipped = 0; … … 276 278 277 279 if (input == NULL) { 278 psError(__func__, "Can not perform clip on NULL image");280 psError(__func__, "Can not perform clip on NULL image"); 279 281 return 0; 280 282 } 281 283 282 if ( realMax < realMin) {283 psError(__func__, "psImageClipComplexRegion can not be invoked with "284 " max < min in the real image space.");284 if (realMax < realMin) { 285 psError(__func__, 286 "psImageClipComplexRegion can not be invoked with " "max < min in the real image space."); 285 287 return 0; 286 288 } 287 if ( imagMax < imagMin ) { 288 psError(__func__,"psImageClipComplexRegion can not be invoked with " 289 if (imagMax < imagMin) { 290 psError(__func__, 291 "psImageClipComplexRegion can not be invoked with " 289 292 "max < min in the imaginary image space."); 290 293 return 0; … … 294 297 numCols = input->numCols; 295 298 299 #define psImageClipComplexRegionCase(type,typename,realfcn,imagfcn) \ 300 case PS_TYPE_##type: { \ 301 if (realfcn(vmin) < PS_MIN_##type || imagfcn(vmin) < PS_MIN_##type || \ 302 realfcn(vmin) > PS_MAX_##type || imagfcn(vmin) > PS_MAX_##type ) { \ 303 psError(__func__, "Specified vmin (%g%+gi) is outside of image's " \ 304 typename " pixel range", \ 305 creal(vmin),cimag(vmin)); \ 306 break; \ 307 } \ 308 if (realfcn(vmax) > PS_MAX_##type || imagfcn(vmax) > PS_MAX_##type || \ 309 realfcn(vmax) < PS_MIN_##type || imagfcn(vmax) < PS_MIN_##type ) { \ 310 psError(__func__, "Specified vmax (%g%+gi) is outside of image's " \ 311 typename " pixel range", \ 312 creal(vmax),cimag(vmax)); \ 313 break; \ 314 } \ 315 for (unsigned int row = 0;row<numRows;row++) { \ 316 ps##type* inputRow = input->data.type[row]; \ 317 for (unsigned int col = 0; col < numCols; col++) { \ 318 if ( (realfcn(inputRow[col]) > realMax) || (imagfcn(inputRow[col]) > imagMax) ) { \ 319 inputRow[col] = (ps##type)vmax; \ 320 numClipped++; \ 321 } else if ( (realfcn(inputRow[col]) < realMin) || (imagfcn(inputRow[col]) < imagMin) ){ \ 322 inputRow[col] = (ps##type)vmin; \ 323 numClipped++; \ 324 } \ 325 } \ 326 } \ 327 } \ 328 break; 329 296 330 switch (input->type.type) { 297 331 298 #define psImageClipComplexRegionCase(type,typename,realfcn,imagfcn) \ 299 case PS_TYPE_##type: { \ 300 if (realfcn(vmin) < PS_MIN_##type || imagfcn(vmin) < PS_MIN_##type || \ 301 realfcn(vmin) > PS_MAX_##type || imagfcn(vmin) > PS_MAX_##type ) { \ 302 psError(__func__, "Specified vmin (%g%+gi) is outside of image's " \ 303 typename " pixel range", \ 304 creal(vmin),cimag(vmin)); \ 305 break; \ 306 } \ 307 if (realfcn(vmax) > PS_MAX_##type || imagfcn(vmax) > PS_MAX_##type || \ 308 realfcn(vmax) < PS_MIN_##type || imagfcn(vmax) < PS_MIN_##type ) { \ 309 psError(__func__, "Specified vmax (%g%+gi) is outside of image's " \ 310 typename " pixel range", \ 311 creal(vmax),cimag(vmax)); \ 312 break; \ 313 } \ 314 for (unsigned int row = 0;row<numRows;row++) { \ 315 ps##type* inputRow = input->data.type[row]; \ 316 for (unsigned int col = 0; col < numCols; col++) { \ 317 if ( (realfcn(inputRow[col]) > realMax) || (imagfcn(inputRow[col]) > imagMax) ) { \ 318 inputRow[col] = (ps##type)vmax; \ 319 numClipped++; \ 320 } else if ( (realfcn(inputRow[col]) < realMin) || (imagfcn(inputRow[col]) < imagMin) ){ \ 321 inputRow[col] = (ps##type)vmin; \ 322 numClipped++; \ 323 } \ 324 } \ 325 } \ 326 } \ 327 break; 328 329 psImageClipComplexRegionCase(C32,"psC32",crealf,cimagf) 330 psImageClipComplexRegionCase(C64,"psC64",creal,cimag) 332 psImageClipComplexRegionCase(C32, "psC32", crealf, cimagf) 333 psImageClipComplexRegionCase(C64, "psC64", creal, cimag) 331 334 332 335 default: 333 psError(__func__,"psImageClip does not support the given datatype (%d)", 334 input->type.type); 336 psError(__func__, "psImageClip does not support the given datatype (%d)", input->type.type); 335 337 } 336 338 … … 338 340 } 339 341 340 341 psImage* psImageRebin(psImage* out,const psImage* in,unsigned int scale,const psStats* stats) 342 psImage *psImageRebin(psImage * out, const psImage * in, unsigned int scale, const psStats * stats) 342 343 { 343 344 int inRows; … … 345 346 int outRows; 346 347 int outCols; 347 psVector* vec; // vector to hold the values of a single bin. 348 psStats* myStats; 348 psVector *vec; // vector to hold 349 350 // the values of 351 // a single bin. 352 psStats *myStats; 349 353 double statVal; 350 354 351 355 if (in == NULL) { 352 psError(__func__, "Input image is NULL.");356 psError(__func__, "Input image is NULL."); 353 357 psFree(out); 354 358 return NULL; … … 356 360 357 361 if (scale < 1) { 358 psError(__func__, "The scale must be positive.");362 psError(__func__, "The scale must be positive."); 359 363 psFree(out); 360 364 return NULL; … … 362 366 363 367 if (stats == NULL) { 364 psError(__func__, "The stats input can not be NULL.");368 psError(__func__, "The stats input can not be NULL."); 365 369 psFree(out); 366 370 return NULL; 367 371 } 368 372 369 if (p_psGetStatValue(stats, &statVal) == false) {370 psError(__func__, "The stat options didn't specify a single supported statistic type.");373 if (p_psGetStatValue(stats, &statVal) == false) { 374 psError(__func__, "The stat options didn't specify a single supported statistic type."); 371 375 psFree(out); 372 376 return NULL; … … 376 380 *myStats = *stats; 377 381 378 vec = psVectorAlloc(scale *scale,in->type.type);382 vec = psVectorAlloc(scale * scale, in->type.type); 379 383 380 384 // create output image. 381 385 inRows = in->numRows; 382 386 inCols = in->numCols; 383 outRows = (inRows+scale-1) / scale; // round-up for remainders 384 outCols = (inCols+scale-1) / scale; // round-up for remainders 385 out = psImageRecycle(out,outCols,outRows,in->type.type); 387 outRows = (inRows + scale - 1) / scale; // round-up 388 // for 389 // remainders 390 outCols = (inCols + scale - 1) / scale; // round-up 391 // for 392 // remainders 393 out = psImageRecycle(out, outCols, outRows, in->type.type); 386 394 387 395 #define PS_IMAGE_REBIN_CASE(type) \ … … 425 433 PS_IMAGE_REBIN_CASE(C64); 426 434 default: 427 psError(__func__, "Input image type not supported.");435 psError(__func__, "Input image type not supported."); 428 436 psFree(out); 429 437 out = NULL; … … 435 443 return out; 436 444 } 437 psImage* psImageResample(psImage* out, const psImage* in, int scale, psImageInterpolateMode mode) 445 446 psImage *psImageResample(psImage * out, const psImage * in, int scale, psImageInterpolateMode mode) 438 447 { 439 448 int outRows; … … 442 451 443 452 if (in == NULL) { 444 psError(__func__, "Input image can not be NULL.");453 psError(__func__, "Input image can not be NULL."); 445 454 psFree(out); 446 455 return NULL; 447 456 } 448 449 // create an output image of the same sizeand type450 outRows = in->numRows *scale;451 outCols = in->numCols *scale;457 // create an output image of the same size 458 // and type 459 outRows = in->numRows * scale; 460 outCols = in->numCols * scale; 452 461 invScale = 1.0f / (float)scale; 453 454 462 455 463 #define PSIMAGE_RESAMPLE_CASE(TYPE) \ … … 466 474 } 467 475 468 switch (in->type.type) {476 switch (in->type.type) { 469 477 PSIMAGE_RESAMPLE_CASE(U8) 470 478 PSIMAGE_RESAMPLE_CASE(U16) … … 480 488 PSIMAGE_RESAMPLE_CASE(C64) 481 489 default: 482 psError(__func__, "Unsupported type (%d)",in->type.type);490 psError(__func__, "Unsupported type (%d)", in->type.type); 483 491 psFree(out); 484 492 return NULL; … … 488 496 } 489 497 490 psImage * psImageRoll(psImage* out, const psImage* in, int dx, int dy)498 psImage *psImageRoll(psImage * out, const psImage * in, int dx, int dy) 491 499 { 492 500 int outRows; … … 495 503 496 504 if (in == NULL) { 497 psError(__func__, "Input image can not be NULL.");505 psError(__func__, "Input image can not be NULL."); 498 506 psFree(out); 499 507 return NULL; 500 508 } 501 502 // create an output image of the same sizeand type509 // create an output image of the same size 510 // and type 503 511 outRows = in->numRows; 504 512 outCols = in->numCols; 505 513 elementSize = PSELEMTYPE_SIZEOF(in->type.type); 506 out = psImageRecycle(out,outCols, outRows, in->type.type); 507 508 // make dx and dy between 0 and outCols or outRows, respectively 514 out = psImageRecycle(out, outCols, outRows, in->type.type); 515 516 // make dx and dy between 0 and outCols or 517 // outRows, respectively 509 518 dx = dx % outCols; 510 519 dy = dy % outRows; … … 516 525 } 517 526 518 int segment1Size = elementSize*(outCols-dx); 519 int segment2Size = elementSize*dx; 520 521 for (int row=0;row<outRows;row++) { 522 int inRowNumber = row+dy; 527 int segment1Size = elementSize * (outCols - dx); 528 int segment2Size = elementSize * dx; 529 530 for (int row = 0; row < outRows; row++) { 531 int inRowNumber = row + dy; 532 523 533 if (inRowNumber >= outRows) { 524 534 inRowNumber -= outRows; 525 535 } 526 psU8* inRow = in->data.U8[inRowNumber]; // to allow byte arithmetic, but for all types 527 psU8* outRow = out->data.U8[row]; 528 memcpy(outRow,inRow+segment2Size,segment1Size); 529 memcpy(outRow+segment1Size,inRow,segment2Size); 536 psU8 *inRow = in->data.U8[inRowNumber]; // to 537 538 // allow 539 540 // byte 541 // arithmetic, 542 543 // but for all types 544 psU8 *outRow = out->data.U8[row]; 545 546 memcpy(outRow, inRow + segment2Size, segment1Size); 547 memcpy(outRow + segment1Size, inRow, segment2Size); 530 548 } 531 549 … … 533 551 } 534 552 535 psImage* psImageRotate(psImage* out, const psImage* in, float angle, float unexposedValue, psImageInterpolateMode mode) 553 psImage *psImageRotate(psImage * out, 554 const psImage * in, float angle, float unexposedValue, psImageInterpolateMode mode) 536 555 { 537 556 if (in == NULL) { 538 psError(__func__, "The input image was NULL.");557 psError(__func__, "The input image was NULL."); 539 558 psFree(out); 540 559 return NULL; 541 560 } 542 543 561 // put the angle in the range of 0...360. 544 angle = angle - 360.0f *floor(angle/360.0f);545 546 if (fabsf(angle -90.0f) < FLT_EPSILON) {562 angle = angle - 360.0f * floor(angle / 360.0f); 563 564 if (fabsf(angle - 90.0f) < FLT_EPSILON) { 547 565 // perform 1/4 rotate counter-clockwise 548 566 int numRows = in->numCols; … … 550 568 int lastCol = numCols - 1; 551 569 psElemType type = in->type.type; 552 out = psImageRecycle(out,numCols,numRows,type); 570 571 out = psImageRecycle(out, numCols, numRows, type); 553 572 554 573 #define PSIMAGE_ROTATE_LEFT_90(TYPE) \ … … 578 597 PSIMAGE_ROTATE_LEFT_90(C64); 579 598 default: 580 psError(__func__, "Unsupported type (%d)",type);599 psError(__func__, "Unsupported type (%d)", type); 581 600 psFree(out); 582 601 return NULL; 583 602 } 584 } else 585 if (fabsf(angle-180.0f) < FLT_EPSILON) { 586 // perform 1/2 rotate 587 int numRows = in->numRows; 588 int lastRow = numRows - 1; 589 int numCols = in->numCols; 590 int lastCol = numCols - 1; 591 psElemType type = in->type.type; 592 out = psImageRecycle(out,numCols,numRows,type); 593 594 #define PSIMAGE_ROTATE_180_CASE(TYPE) \ 595 case PS_TYPE_##TYPE: { \ 596 for (int row=0;row<numRows;row++) { \ 597 ps##TYPE* outRow = out->data.TYPE[row]; \ 598 ps##TYPE* inRow = in->data.TYPE[lastRow-row]; \ 599 for (int col=0;col<numCols;col++) { \ 600 outRow[col] = inRow[lastCol - col]; \ 601 } \ 602 } \ 603 } \ 604 break; 605 606 switch (type) { 607 PSIMAGE_ROTATE_180_CASE(U8); 608 PSIMAGE_ROTATE_180_CASE(U16); 609 PSIMAGE_ROTATE_180_CASE(U32); 610 PSIMAGE_ROTATE_180_CASE(U64); 611 PSIMAGE_ROTATE_180_CASE(S8); 612 PSIMAGE_ROTATE_180_CASE(S16); 613 PSIMAGE_ROTATE_180_CASE(S32); 614 PSIMAGE_ROTATE_180_CASE(S64); 615 PSIMAGE_ROTATE_180_CASE(F32); 616 PSIMAGE_ROTATE_180_CASE(F64); 617 PSIMAGE_ROTATE_180_CASE(C32); 618 PSIMAGE_ROTATE_180_CASE(C64); 619 default: 620 psError(__func__,"Unsupported type (%d)",type); 621 psFree(out); 622 return NULL; 623 } 624 } else 625 if (fabsf(angle-270.0f) < FLT_EPSILON) { 626 // perform 1/4 rotate clockwise 627 int numRows = in->numCols; 628 int lastRow = numRows - 1; 629 int numCols = in->numRows; 630 psElemType type = in->type.type; 631 out = psImageRecycle(out,numCols,numRows,type); 632 633 #define PSIMAGE_ROTATE_RIGHT_90(TYPE) \ 634 case PS_TYPE_##TYPE: { \ 635 ps##TYPE** inData = in->data.TYPE; \ 636 for (int row=0;row<numRows;row++) { \ 637 ps##TYPE* outRow = out->data.TYPE[row]; \ 638 for (int col=0;col<numCols;col++) { \ 639 outRow[col] = inData[col][lastRow-row]; \ 640 } \ 641 } \ 642 } \ 643 break; 644 645 switch (type) { 646 PSIMAGE_ROTATE_RIGHT_90(U8); 647 PSIMAGE_ROTATE_RIGHT_90(U16); 648 PSIMAGE_ROTATE_RIGHT_90(U32); 649 PSIMAGE_ROTATE_RIGHT_90(U64); 650 PSIMAGE_ROTATE_RIGHT_90(S8); 651 PSIMAGE_ROTATE_RIGHT_90(S16); 652 PSIMAGE_ROTATE_RIGHT_90(S32); 653 PSIMAGE_ROTATE_RIGHT_90(S64); 654 PSIMAGE_ROTATE_RIGHT_90(F32); 655 PSIMAGE_ROTATE_RIGHT_90(F64); 656 PSIMAGE_ROTATE_RIGHT_90(C32); 657 PSIMAGE_ROTATE_RIGHT_90(C64); 658 default: 659 psError(__func__,"Unsupported type (%d)",type); 660 psFree(out); 661 return NULL; 662 } 663 } else 664 if (fabsf(angle) < FLT_EPSILON) { 665 out = psImageCopy(out,in,in->type.type); 666 } else { 667 psElemType type = in->type.type; 668 int numRows = in->numRows; 669 int numCols = in->numCols; 670 double centerX = (float)(numCols) / 2.0f; 671 float centerY = (float)(numRows) / 2.0f; 672 float t = angle*(3.14159265358f/180.0f); 673 float cosT = cosf(t); 674 float sinT = sinf(t); 675 676 // calculate the corners of the rotated image so we know the proper output image size. 677 // x' = x cos(t) + y sin(t); i.e, x' = (x-centerX)*cosT + (y-centerY)*sinT; 678 // y' = y cos(t) - x sin(t); i.e. y' = (y-centerY)*cosT - (x-centerX)*sinT; 679 680 681 int outCols = ceil(abs(numCols*cosT)+abs(numRows*sinT))+1; 682 int outRows = ceil(abs(numCols*sinT)+abs(numRows*cosT))+1; 683 float minX = (float)outCols/-2.0f; 684 int intMinY = outRows/-2; 685 686 out = psImageRecycle(out,outCols,outRows,type); 687 688 /* optimized public domain rotation routine by Karl Lager 689 float cosT,sinT; 690 cosT = cos(t); 691 sinT = sin(t); 692 for (y = min_y; y <= max_y; y++) 693 { x' = min_x * cosT + y * sinT + x1'; 694 y' = y * cosT - min_x * sinT + y1'; 695 for (x = min_x; x <= max_x; x++) 696 { if (x', y') is in the bounds of the bitmap, 697 get pixel(x', y') and plot the pixel to 698 (x, y) on screen. 699 x' += cosT; 700 y' -= sinT; 701 } 702 } 703 */ 704 705 // precalculate some figures that are used within loop 706 float minXTimesCosTPlusCenterX = minX*cosT+centerX; 707 float CenterYMinusminXTimesSinT = centerY-minX*sinT; 708 709 #define PSIMAGE_ROTATE_ARBITRARY_LOOP(TYPE,MODE) { \ 710 if (unexposedValue < PS_MIN_##TYPE || unexposedValue > PS_MAX_##TYPE) { \ 711 psError(__func__,"The given unexposedValue (%g) is outside of the " \ 712 "image type's range (%g->%g).", \ 713 unexposedValue, (double)PS_MIN_##TYPE,(double)PS_MAX_##TYPE); \ 714 psFree(out); \ 715 out = NULL; \ 716 break; \ 717 } \ 718 float inX; \ 719 float inY; \ 720 ps##TYPE* outRow; \ 721 for (int y = 0; y < outRows; y++) { \ 722 inX = minXTimesCosTPlusCenterX + (y+intMinY) * sinT; \ 723 inY = CenterYMinusminXTimesSinT + (y+intMinY) * cosT; \ 724 outRow = out->data.TYPE[y]; \ 725 for (int x = 0; x < outCols; x++) { \ 726 outRow[x] = p_psImagePixelInterpolate##MODE##_##TYPE(in,inX,inY,unexposedValue); \ 727 inX += cosT; \ 728 inY -= sinT; \ 729 } \ 730 } \ 731 } 732 733 #define PSIMAGE_ROTATE_ARBITRARY_CASE(MODE) \ 734 case PS_INTERPOLATE_##MODE: \ 735 switch (type) { \ 736 case PS_TYPE_U8: \ 737 PSIMAGE_ROTATE_ARBITRARY_LOOP(U8,MODE); \ 738 break; \ 739 case PS_TYPE_U16: \ 740 PSIMAGE_ROTATE_ARBITRARY_LOOP(U16,MODE); \ 741 break; \ 742 case PS_TYPE_U32: \ 743 PSIMAGE_ROTATE_ARBITRARY_LOOP(U32,MODE); \ 744 break; \ 745 case PS_TYPE_U64: \ 746 PSIMAGE_ROTATE_ARBITRARY_LOOP(U64,MODE); \ 747 break; \ 748 case PS_TYPE_S8: \ 749 PSIMAGE_ROTATE_ARBITRARY_LOOP(S8,MODE); \ 750 break; \ 751 case PS_TYPE_S16: \ 752 PSIMAGE_ROTATE_ARBITRARY_LOOP(S16,MODE); \ 753 break; \ 754 case PS_TYPE_S32: \ 755 PSIMAGE_ROTATE_ARBITRARY_LOOP(S32,MODE); \ 756 break; \ 757 case PS_TYPE_S64: \ 758 PSIMAGE_ROTATE_ARBITRARY_LOOP(S64,MODE); \ 759 break; \ 760 case PS_TYPE_F32: \ 761 PSIMAGE_ROTATE_ARBITRARY_LOOP(F32,MODE); \ 762 break; \ 763 case PS_TYPE_F64: \ 764 PSIMAGE_ROTATE_ARBITRARY_LOOP(F64,MODE); \ 765 break; \ 766 case PS_TYPE_C32: \ 767 PSIMAGE_ROTATE_ARBITRARY_LOOP(C32,MODE); \ 768 break; \ 769 case PS_TYPE_C64: \ 770 PSIMAGE_ROTATE_ARBITRARY_LOOP(C64,MODE); \ 771 break; \ 772 default: \ 773 psError(__func__,"Image type (%d) not supported",type); \ 774 psFree(out); \ 775 out = NULL; \ 776 } \ 777 break; 778 779 switch (mode) { 780 PSIMAGE_ROTATE_ARBITRARY_CASE(FLAT); 781 PSIMAGE_ROTATE_ARBITRARY_CASE(BILINEAR); 782 default: 783 psError(__func__,"Unsupported interpolation mode (%d)",mode); 784 psFree(out); 785 out = NULL; 786 } 787 } 603 } else if (fabsf(angle - 180.0f) < FLT_EPSILON) { 604 // perform 1/2 rotate 605 int numRows = in->numRows; 606 int lastRow = numRows - 1; 607 int numCols = in->numCols; 608 int lastCol = numCols - 1; 609 psElemType type = in->type.type; 610 611 out = psImageRecycle(out, numCols, numRows, type); 612 613 #define PSIMAGE_ROTATE_180_CASE(TYPE) \ 614 case PS_TYPE_##TYPE: { \ 615 for (int row=0;row<numRows;row++) { \ 616 ps##TYPE* outRow = out->data.TYPE[row]; \ 617 ps##TYPE* inRow = in->data.TYPE[lastRow-row]; \ 618 for (int col=0;col<numCols;col++) { \ 619 outRow[col] = inRow[lastCol - col]; \ 620 } \ 621 } \ 622 } \ 623 break; 624 625 switch (type) { 626 PSIMAGE_ROTATE_180_CASE(U8); 627 PSIMAGE_ROTATE_180_CASE(U16); 628 PSIMAGE_ROTATE_180_CASE(U32); 629 PSIMAGE_ROTATE_180_CASE(U64); 630 PSIMAGE_ROTATE_180_CASE(S8); 631 PSIMAGE_ROTATE_180_CASE(S16); 632 PSIMAGE_ROTATE_180_CASE(S32); 633 PSIMAGE_ROTATE_180_CASE(S64); 634 PSIMAGE_ROTATE_180_CASE(F32); 635 PSIMAGE_ROTATE_180_CASE(F64); 636 PSIMAGE_ROTATE_180_CASE(C32); 637 PSIMAGE_ROTATE_180_CASE(C64); 638 default: 639 psError(__func__, "Unsupported type (%d)", type); 640 psFree(out); 641 return NULL; 642 } 643 } else if (fabsf(angle - 270.0f) < FLT_EPSILON) { 644 // perform 1/4 rotate clockwise 645 int numRows = in->numCols; 646 int lastRow = numRows - 1; 647 int numCols = in->numRows; 648 psElemType type = in->type.type; 649 650 out = psImageRecycle(out, numCols, numRows, type); 651 652 #define PSIMAGE_ROTATE_RIGHT_90(TYPE) \ 653 case PS_TYPE_##TYPE: { \ 654 ps##TYPE** inData = in->data.TYPE; \ 655 for (int row=0;row<numRows;row++) { \ 656 ps##TYPE* outRow = out->data.TYPE[row]; \ 657 for (int col=0;col<numCols;col++) { \ 658 outRow[col] = inData[col][lastRow-row]; \ 659 } \ 660 } \ 661 } \ 662 break; 663 664 switch (type) { 665 PSIMAGE_ROTATE_RIGHT_90(U8); 666 PSIMAGE_ROTATE_RIGHT_90(U16); 667 PSIMAGE_ROTATE_RIGHT_90(U32); 668 PSIMAGE_ROTATE_RIGHT_90(U64); 669 PSIMAGE_ROTATE_RIGHT_90(S8); 670 PSIMAGE_ROTATE_RIGHT_90(S16); 671 PSIMAGE_ROTATE_RIGHT_90(S32); 672 PSIMAGE_ROTATE_RIGHT_90(S64); 673 PSIMAGE_ROTATE_RIGHT_90(F32); 674 PSIMAGE_ROTATE_RIGHT_90(F64); 675 PSIMAGE_ROTATE_RIGHT_90(C32); 676 PSIMAGE_ROTATE_RIGHT_90(C64); 677 default: 678 psError(__func__, "Unsupported type (%d)", type); 679 psFree(out); 680 return NULL; 681 } 682 } else if (fabsf(angle) < FLT_EPSILON) { 683 out = psImageCopy(out, in, in->type.type); 684 } else { 685 psElemType type = in->type.type; 686 int numRows = in->numRows; 687 int numCols = in->numCols; 688 double centerX = (float)(numCols) / 2.0f; 689 float centerY = (float)(numRows) / 2.0f; 690 float t = angle * (3.14159265358f / 180.0f); 691 float cosT = cosf(t); 692 float sinT = sinf(t); 693 694 // calculate the corners of the rotated 695 // image so we know the proper 696 // output image size. 697 // x' = x cos(t) + y sin(t); i.e, x' = 698 // (x-centerX)*cosT + 699 // (y-centerY)*sinT; 700 // y' = y cos(t) - x sin(t); i.e. y' = 701 // (y-centerY)*cosT - 702 // (x-centerX)*sinT; 703 704 int outCols = ceil(abs(numCols * cosT) + abs(numRows * sinT)) + 1; 705 int outRows = ceil(abs(numCols * sinT) + abs(numRows * cosT)) + 1; 706 float minX = (float)outCols / -2.0f; 707 int intMinY = outRows / -2; 708 709 out = psImageRecycle(out, outCols, outRows, type); 710 711 /* optimized public domain rotation routine by Karl Lager float cosT,sinT; cosT = cos(t); sinT = 712 * sin(t); for (y = min_y; y <= max_y; y++) { x' = min_x * cosT + y * sinT + x1'; y' = y * cosT - 713 * min_x * sinT + y1'; for (x = min_x; x <= max_x; x++) { if (x', y') * * * * * * * * is in the 714 * bounds of the bitmap, get pixel(x', y') and plot the pixel to (x, y) on screen. x' += cosT; y' -= 715 * sinT; } } */ 716 717 // precalculate some figures that are 718 // used within loop 719 float minXTimesCosTPlusCenterX = minX * cosT + centerX; 720 float CenterYMinusminXTimesSinT = centerY - minX * sinT; 721 722 #define PSIMAGE_ROTATE_ARBITRARY_LOOP(TYPE,MODE) { \ 723 if (unexposedValue < PS_MIN_##TYPE || unexposedValue > PS_MAX_##TYPE) { \ 724 psError(__func__,"The given unexposedValue (%g) is outside of the " \ 725 "image type's range (%g->%g).", \ 726 unexposedValue, (double)PS_MIN_##TYPE,(double)PS_MAX_##TYPE); \ 727 psFree(out); \ 728 out = NULL; \ 729 break; \ 730 } \ 731 float inX; \ 732 float inY; \ 733 ps##TYPE* outRow; \ 734 for (int y = 0; y < outRows; y++) { \ 735 inX = minXTimesCosTPlusCenterX + (y+intMinY) * sinT; \ 736 inY = CenterYMinusminXTimesSinT + (y+intMinY) * cosT; \ 737 outRow = out->data.TYPE[y]; \ 738 for (int x = 0; x < outCols; x++) { \ 739 outRow[x] = p_psImagePixelInterpolate##MODE##_##TYPE(in,inX,inY,unexposedValue); \ 740 inX += cosT; \ 741 inY -= sinT; \ 742 } \ 743 } \ 744 } 745 746 #define PSIMAGE_ROTATE_ARBITRARY_CASE(MODE) \ 747 case PS_INTERPOLATE_##MODE: \ 748 switch (type) { \ 749 case PS_TYPE_U8: \ 750 PSIMAGE_ROTATE_ARBITRARY_LOOP(U8,MODE); \ 751 break; \ 752 case PS_TYPE_U16: \ 753 PSIMAGE_ROTATE_ARBITRARY_LOOP(U16,MODE); \ 754 break; \ 755 case PS_TYPE_U32: \ 756 PSIMAGE_ROTATE_ARBITRARY_LOOP(U32,MODE); \ 757 break; \ 758 case PS_TYPE_U64: \ 759 PSIMAGE_ROTATE_ARBITRARY_LOOP(U64,MODE); \ 760 break; \ 761 case PS_TYPE_S8: \ 762 PSIMAGE_ROTATE_ARBITRARY_LOOP(S8,MODE); \ 763 break; \ 764 case PS_TYPE_S16: \ 765 PSIMAGE_ROTATE_ARBITRARY_LOOP(S16,MODE); \ 766 break; \ 767 case PS_TYPE_S32: \ 768 PSIMAGE_ROTATE_ARBITRARY_LOOP(S32,MODE); \ 769 break; \ 770 case PS_TYPE_S64: \ 771 PSIMAGE_ROTATE_ARBITRARY_LOOP(S64,MODE); \ 772 break; \ 773 case PS_TYPE_F32: \ 774 PSIMAGE_ROTATE_ARBITRARY_LOOP(F32,MODE); \ 775 break; \ 776 case PS_TYPE_F64: \ 777 PSIMAGE_ROTATE_ARBITRARY_LOOP(F64,MODE); \ 778 break; \ 779 case PS_TYPE_C32: \ 780 PSIMAGE_ROTATE_ARBITRARY_LOOP(C32,MODE); \ 781 break; \ 782 case PS_TYPE_C64: \ 783 PSIMAGE_ROTATE_ARBITRARY_LOOP(C64,MODE); \ 784 break; \ 785 default: \ 786 psError(__func__,"Image type (%d) not supported",type); \ 787 psFree(out); \ 788 out = NULL; \ 789 } \ 790 break; 791 792 switch (mode) { 793 PSIMAGE_ROTATE_ARBITRARY_CASE(FLAT); 794 PSIMAGE_ROTATE_ARBITRARY_CASE(BILINEAR); 795 default: 796 psError(__func__, "Unsupported interpolation mode (%d)", mode); 797 psFree(out); 798 out = NULL; 799 } 800 } 788 801 789 802 return out; 790 803 } 791 804 792 psImage* psImageShift(psImage* out, const psImage* in, float dx, float dy, psF64 unexposedValue, psImageInterpolateMode mode) 805 psImage *psImageShift(psImage * out, 806 const psImage * in, 807 float dx, float dy, psF64 unexposedValue, psImageInterpolateMode mode) 793 808 { 794 809 int outRows; … … 798 813 799 814 if (in == NULL) { 800 psError(__func__, "Input image can not be NULL.");815 psError(__func__, "Input image can not be NULL."); 801 816 return NULL; 802 817 } 803 804 // create an output image of the same sizeand type818 // create an output image of the same size 819 // and type 805 820 outRows = in->numRows; 806 821 outCols = in->numCols; 807 822 type = in->type.type; 808 823 elementSize = PSELEMTYPE_SIZEOF(type); 809 out = psImageRecycle(out, outCols, outRows, type);824 out = psImageRecycle(out, outCols, outRows, type); 810 825 811 826 #define PSIMAGE_SHIFT_CASE(TYPE) \ … … 842 857 PSIMAGE_SHIFT_CASE(C64); 843 858 default: 844 psError(__func__, "Image type (%d) not supported.",type);859 psError(__func__, "Image type (%d) not supported.", type); 845 860 psFree(out); 846 861 out = NULL; -
trunk/psLib/src/image/psImageManip.h
r1263 r1407 1 1 2 /** @file psImageManip.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1. 6$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-0 7-22 20:42:22$13 * @version $Revision: 1.7 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 #ifndef PS_IMAGE_MANIP_H 18 # define PS_IMAGE_MANIP_H19 # define PS_IMAGE_MANIP_H 19 20 20 # include "psImage.h"21 # include "psImage.h" 21 22 22 23 /// @addtogroup Image … … 31 32 * @return int The number of clipped pixels 32 33 */ 33 int psImageClip( 34 psImage* input, ///< the image to clip 35 psF64 min, ///< the minimum image value allowed 36 psF64 vmin, ///< the value pixels < min are set to 37 psF64 max, ///< the maximum image value allowed 38 psF64 vmax ///< the value pixels > max are set to 39 ); 34 int psImageClip(psImage * input, // /< the image to clip 35 psF64 min, // /< the minimum image value allowed 36 psF64 vmin, // /< the value pixels < min are set to 37 psF64 max, // /< the maximum image value allowed 38 psF64 vmax // /< the value pixels > max are set to 39 ); 40 40 41 41 /** Clip image values outside of a specified complex region … … 48 48 * @return int The number of clipped pixels 49 49 */ 50 int psImageClipComplexRegion( 51 psImage* input, ///< the image to clip 52 psC64 min, ///< the minimum image value allowed 53 psC64 vmin, ///< the value pixels < min are set to 54 psC64 max, ///< the maximum image value allowed 55 psC64 vmax ///< the value pixels > max are set to 56 ); 50 int psImageClipComplexRegion(psImage * input, // /< the image to clip 51 psC64 min, // /< the minimum image value allowed 52 psC64 vmin, // /< the value pixels < min are set to 53 psC64 max, // /< the maximum image value allowed 54 psC64 vmax // /< the value pixels > max are set to 55 ); 57 56 58 57 /** Clip NaN image pixels to given value. … … 63 62 * @return int The number of clipped pixels 64 63 */ 65 int psImageClipNaN( 66 psImage* input, ///< the image to clip 67 psF64 value ///< the value to set all NaN/Inf values to 68 ); 64 int psImageClipNaN(psImage * input, // /< the image to clip 65 psF64 value // /< the value to set all NaN/Inf values to 66 ); 69 67 70 68 /** Overlay subregion of image with another image … … 79 77 * @return int 0 if success, non-zero if failed. 80 78 */ 81 int psImageOverlaySection( 82 psImage* image, ///< target image 83 const psImage* overlay, ///< the overlay image 84 int col0, ///< the column to start overlay 85 int row0, ///< the row to start overlay 86 const char* op ///< the operation to perform for overlay 87 ); 79 int psImageOverlaySection(psImage * image, // /< target image 80 const psImage * overlay, // /< the overlay image 81 int col0, // /< the column to start overlay 82 int row0, // /< the row to start overlay 83 const char *op // /< the operation to perform for overlay 84 ); 88 85 89 86 /** Rebin image to new scale. … … 97 94 * @return psImage new image formed by rebinning input image. 98 95 */ 99 psImage * psImageRebin(100 psImage* out, ///< an psImage to recycle. If NULL, a new image is created101 const psImage* in, ///< input image102 unsigned int scale, ///< the scale to rebin for each dimension103 const psStats* stats ///< the statistic to perform when rebinning. Only onemethod should be set.104 );96 psImage *psImageRebin(psImage * out, // /< an psImage to recycle. If NULL, a new image is created 97 const psImage * in, // /< input image 98 unsigned int scale, // /< the scale to rebin for each dimension 99 const psStats * stats // /< the statistic to perform when rebinning. Only one 100 // method should be set. 101 ); 105 102 106 psImage* psImageResample( 107 psImage* out, ///< an psImage to recycle. If NULL, a new image is created 108 const psImage* in, ///< input image 109 int scale, 110 psImageInterpolateMode mode 111 ); 103 psImage *psImageResample(psImage * out, // /< an psImage to recycle. If NULL, a new image is created 104 const psImage * in, // /< input image 105 int scale, psImageInterpolateMode mode); 112 106 113 psImage* psImageRotate( 114 psImage* out, ///< an psImage to recycle. If NULL, a new image is created 115 const psImage* in, ///< input image 116 float angle, 117 float unexposedValue, 118 psImageInterpolateMode mode 119 ); 107 psImage *psImageRotate(psImage * out, // /< an psImage to recycle. If NULL, a new image is created 108 const psImage * in, // /< input image 109 float angle, float unexposedValue, psImageInterpolateMode mode); 120 110 121 psImage* psImageShift( 122 psImage* out, ///< an psImage to recycle. If NULL, a new image is created 123 const psImage* in, ///< input image 124 float dx, 125 float dy, 126 float unexposedValue, 127 psImageInterpolateMode mode 128 ); 111 psImage *psImageShift(psImage * out, // /< an psImage to recycle. If NULL, a new image is created 112 const psImage * in, // /< input image 113 float dx, float dy, float unexposedValue, psImageInterpolateMode mode); 129 114 130 115 /** Roll image by an integer number of pixels in either direction. … … 136 121 * @return psImage* the rolled version of the input image. 137 122 */ 138 psImage* psImageRoll( 139 psImage* out, ///< an psImage to recycle. If NULL, a new image is created 140 const psImage* in, ///< input image 141 int dx, ///< number of pixels to roll in the x-dimension 142 int dy ///< number of pixels to roll in the y-dimension 143 ); 123 psImage *psImageRoll(psImage * out, // /< an psImage to recycle. If NULL, a new image is created 124 const psImage * in, // /< input image 125 int dx, // /< number of pixels to roll in the x-dimension 126 int dy // /< number of pixels to roll in the y-dimension 127 ); 144 128 145 129 #endif 146 -
trunk/psLib/src/image/psImageStats.c
r1406 r1407 1 1 2 /** @file psImageStats.c 2 3 * \brief Routines for calculating statistics on images. … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1. 29$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.30 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 32 33 33 34 /// This routine must determine the various statistics for the image. 35 34 36 /***************************************************************************** 35 37 NOTE: verify that image/mask have the correct types, and sizes. 36 38 *****************************************************************************/ 37 psStats *psImageStats(psStats *stats, 38 psImage *in, 39 psImage *mask, 40 int maskVal) 41 { 42 psVector* junkData=NULL; 43 psVector* junkMask=NULL; 39 psStats *psImageStats(psStats * stats, psImage * in, psImage * mask, int maskVal) 40 { 41 psVector *junkData = NULL; 42 psVector *junkMask = NULL; 44 43 45 44 if (stats == NULL) { 46 psError(__func__, "The input psStats struct can not be NULL.");45 psError(__func__, "The input psStats struct can not be NULL."); 47 46 return NULL; 48 47 } 49 48 50 49 if (in == NULL) { 51 psError(__func__, "The input image can not be NULL.");50 psError(__func__, "The input image can not be NULL."); 52 51 return NULL; 53 52 } 54 53 55 54 if (stats->options == 0) { 56 psError(__func__, "No statistic option/operation was specified.");55 psError(__func__, "No statistic option/operation was specified."); 57 56 return stats; 58 57 } 59 60 // st uff the image data into a psVector struct.58 // stuff the image data into a psVector 59 // struct. 61 60 junkData = psAlloc(sizeof(psVector)); 62 61 junkData->type = in->type; 63 junkData->nalloc = in->numRows *in->numCols;62 junkData->nalloc = in->numRows * in->numCols; 64 63 junkData->n = junkData->nalloc; 65 junkData->data.V = in->data.V[0]; // since psImage data is contiguous... 64 junkData->data.V = in->data.V[0]; // since 65 // psImage 66 // data 67 // is 68 // contiguous... 66 69 67 70 if (mask != NULL) { 68 71 if (mask->type.type != PS_TYPE_MASK) { 69 psError(__func__, "Expected the mask image type not found (type=%x)", 70 mask->type.type); 72 psError(__func__, "Expected the mask image type not found (type=%x)", mask->type.type); 71 73 psFree(junkData); 72 74 return NULL; 73 75 } 74 75 // st uff the mask data into a psVector struct.76 // stuff the mask data into a psVector 77 // struct. 76 78 junkMask = psAlloc(sizeof(psVector)); 77 79 junkMask->type = mask->type; 78 junkMask->nalloc = mask->numRows *mask->numCols;80 junkMask->nalloc = mask->numRows * mask->numCols; 79 81 junkMask->n = junkMask->nalloc; 80 82 junkMask->data.V = mask->data.V[0]; … … 85 87 psFree(junkMask); 86 88 psFree(junkData); 87 return (stats);89 return (stats); 88 90 } 89 91 … … 93 95 NOTE: verify that image/mask have the, correct types and sizes. 94 96 *****************************************************************************/ 95 psHistogram *psImageHistogram(psHistogram *out, 96 psImage *in, 97 psImage *mask, 98 unsigned int maskVal) 99 { 100 psVector *junkData=NULL; 101 psVector *junkMask=NULL; 97 psHistogram *psImageHistogram(psHistogram * out, psImage * in, psImage * mask, unsigned int maskVal) 98 { 99 psVector *junkData = NULL; 100 psVector *junkMask = NULL; 102 101 103 102 // NOTE: Verify this action. 104 if ((out == NULL) || 105 (in == NULL)) { 106 return(NULL); 103 if ((out == NULL) || (in == NULL)) { 104 return (NULL); 107 105 } 108 106 109 107 junkData = psAlloc(sizeof(psVector)); 110 108 junkData->type = in->type; 111 junkData->nalloc = in->numRows *in->numCols;109 junkData->nalloc = in->numRows * in->numCols; 112 110 junkData->n = junkData->nalloc; 113 junkData->data.V = in->data.V[0]; // since psImage data is contiguous... 111 junkData->data.V = in->data.V[0]; // since 112 // psImage 113 // data 114 // is 115 // contiguous... 114 116 115 117 if (mask != NULL) { 116 118 if (mask->type.type != PS_TYPE_MASK) { 117 psError(__func__, "Expected the mask image type not found (type=%x)", 118 mask->type.type); 119 psError(__func__, "Expected the mask image type not found (type=%x)", mask->type.type); 119 120 psFree(junkData); 120 121 return NULL; 121 122 } 122 123 // st uff the mask data into a psVector struct.123 // stuff the mask data into a psVector 124 // struct. 124 125 junkMask = psAlloc(sizeof(psVector)); 125 126 junkMask->type = mask->type; 126 junkMask->nalloc = mask->numRows *mask->numCols;127 junkMask->nalloc = mask->numRows * mask->numCols; 127 128 junkMask->n = junkMask->nalloc; 128 129 junkMask->data.V = mask->data.V[0]; … … 134 135 psFree(junkData); 135 136 136 return (out);137 return (out); 137 138 } 138 139 … … 141 142 int i = 0; 142 143 float tmp = 0.0; 143 float *scalingFactors = (float *) psAlloc(n * sizeof(float)); 144 145 for (i=0;i<n;i++) { 146 // ((2.0 * (float) i) / ((float) (n-1))) - 1.0; 147 // tmp = (float) (i + 1); 148 tmp = (float) (n - i); 149 tmp = (M_PI * (tmp - 0.5)) / ((float) n); 144 float *scalingFactors = (float *)psAlloc(n * sizeof(float)); 145 146 for (i = 0; i < n; i++) { 147 // ((2.0 * (float) i) / ((float) (n-1))) 148 // - 1.0; 149 // tmp = (float) (i + 1); 150 tmp = (float)(n - i); 151 tmp = (M_PI * (tmp - 0.5)) / ((float)n); 150 152 scalingFactors[i] = cos(tmp); 151 153 } 152 154 153 return (scalingFactors);155 return (scalingFactors); 154 156 } 155 157 … … 165 167 int i = 0; 166 168 float tmp = 0.0; 169 167 170 return p_psCalcScaleFactorsFit(n); 168 171 169 172 printf("Should not get here\n"); 170 float *scalingFactors = (float *) psAlloc(n * sizeof(float)); 171 for (i=0;i<n;i++) { 172 // scalingFactors[i] = ((2.0 * (float) i) / ((float) (n-1))) - 1.0; 173 tmp = (float) (n - i); 174 tmp = (M_PI * (tmp - 0.5)) / ((float) n); 173 float *scalingFactors = (float *)psAlloc(n * sizeof(float)); 174 175 for (i = 0; i < n; i++) { 176 // scalingFactors[i] = ((2.0 * (float) i) 177 // / ((float) (n-1))) - 1.0; 178 tmp = (float)(n - i); 179 tmp = (M_PI * (tmp - 0.5)) / ((float)n); 175 180 scalingFactors[i] = cos(tmp); 176 181 } 177 return (scalingFactors);182 return (scalingFactors); 178 183 } 179 184 … … 184 189 int j = 0; 185 190 186 chebPolys = (psPolynomial1D **) psAlloc(maxChebyPoly * 187 sizeof(psPolynomial1D *));188 for (i=0;i<maxChebyPoly;i++) {189 chebPolys[i] = psPolynomial1DAlloc(i+1);190 } 191 192 // Create the Chebyshev polynomials.Polynomial i has i-th order.191 chebPolys = (psPolynomial1D **) psAlloc(maxChebyPoly * sizeof(psPolynomial1D *)); 192 for (i = 0; i < maxChebyPoly; i++) { 193 chebPolys[i] = psPolynomial1DAlloc(i + 1); 194 } 195 196 // Create the Chebyshev polynomials. 197 // Polynomial i has i-th order. 193 198 chebPolys[0]->coeff[0] = 1; 194 199 chebPolys[1]->coeff[1] = 1; 195 for (i=2;i<maxChebyPoly;i++) { 196 for (j=0;j<chebPolys[i-1]->n;j++) { 197 chebPolys[i]->coeff[j+1] = 2 * chebPolys[i-1]->coeff[j]; 198 } 199 for (j=0;j<chebPolys[i-2]->n;j++) { 200 chebPolys[i]->coeff[j]-= chebPolys[i-2]->coeff[j]; 201 } 202 } 203 204 return(chebPolys); 205 } 206 200 for (i = 2; i < maxChebyPoly; i++) { 201 for (j = 0; j < chebPolys[i - 1]->n; j++) { 202 chebPolys[i]->coeff[j + 1] = 2 * chebPolys[i - 1]->coeff[j]; 203 } 204 for (j = 0; j < chebPolys[i - 2]->n; j++) { 205 chebPolys[i]->coeff[j] -= chebPolys[i - 2]->coeff[j]; 206 } 207 } 208 209 return (chebPolys); 210 } 207 211 208 212 /***************************************************************************** … … 220 224 over all pixels (x,y) in the image. 221 225 *****************************************************************************/ 222 psPolynomial2D * 223 psImageFitPolynomial(const psImage *input, 224 psPolynomial2D *coeffs) 226 psPolynomial2D *psImageFitPolynomial(const psImage * input, psPolynomial2D * coeffs) 225 227 { 226 228 int x = 0; … … 235 237 float tmp = 0.0; 236 238 237 // Create the sums[][] data structure. This will hold the LHS of equation 238 // 29 in the ADD: sums[k][l] = SUM { image(x,y) * Tk(x) * Tl(y) } 239 sums = (float **) psAlloc(coeffs->nX * sizeof(float *)); 240 for (i=0;i<coeffs->nX;i++) { 241 sums[i] = (float *) psAlloc(coeffs->nY * sizeof(float)); 242 } 243 244 // We scale the pixel positions to values between -1.0 and 1.0 239 // Create the sums[][] data structure. This 240 // will hold the LHS of 241 // equation 242 // 29 in the ADD: sums[k][l] = SUM { 243 // image(x,y) * Tk(x) * Tl(y) } 244 sums = (float **)psAlloc(coeffs->nX * sizeof(float *)); 245 for (i = 0; i < coeffs->nX; i++) { 246 sums[i] = (float *)psAlloc(coeffs->nY * sizeof(float)); 247 } 248 249 // We scale the pixel positions to values 250 // between -1.0 and 1.0 245 251 rScalingFactors = p_psCalcScaleFactorsFit(input->numRows); 246 252 cScalingFactors = p_psCalcScaleFactorsFit(input->numCols); 247 253 248 // Determine how many Chebyshev polynomials are needed, then create them. 254 // Determine how many Chebyshev polynomials 255 // are needed, then create them. 249 256 maxChebyPoly = coeffs->nX; 250 257 if (coeffs->nY > coeffs->nX) { … … 254 261 255 262 // Sanity check for the Chebyshevs. 256 for (i =0;i<coeffs->nX;i++) {257 for (j =0;j<coeffs->nY;j++) {263 for (i = 0; i < coeffs->nX; i++) { 264 for (j = 0; j < coeffs->nY; j++) { 258 265 tmp = 0.0; 259 for (x=0;x<input->numRows;x++) { 260 tmp+= psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 261 psPolynomial1DEval(rScalingFactors[x], chebPolys[j]); 266 for (x = 0; x < input->numRows; x++) { 267 tmp += 268 psPolynomial1DEval 269 (rScalingFactors[x], chebPolys[i]) * psPolynomial1DEval(rScalingFactors[x], chebPolys[j]); 262 270 263 271 } 264 //printf("SUM(Cheby(%d) * Cheby(%d)) is %f\n", i, j, tmp); 272 // printf("SUM(Cheby(%d) * Cheby(%d)) 273 // is %f\n", i, j, tmp); 265 274 } 266 275 } 267 276 268 277 // Compute the sums[][] data structure. 269 for (i =0;i<coeffs->nX;i++) {270 for (j =0;j<coeffs->nY;j++) {278 for (i = 0; i < coeffs->nX; i++) { 279 for (j = 0; j < coeffs->nY; j++) { 271 280 sums[i][j] = 0.0; 272 for (x=0;x<input->numRows;x++) { 273 for (y=0;y<input->numCols;y++) { 274 sums[i][j]+= input->data.F32[x][y] * 275 psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 276 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]); 281 for (x = 0; x < input->numRows; x++) { 282 for (y = 0; y < input->numCols; y++) { 283 sums[i][j] += 284 input->data.F32[x][y] * 285 psPolynomial1DEval 286 (rScalingFactors[x], 287 chebPolys[i]) * psPolynomial1DEval(cScalingFactors[y], chebPolys[j]); 277 288 } 278 289 } … … 280 291 } 281 292 282 for (i =0;i<coeffs->nX;i++) {283 for (j =0;j<coeffs->nY;j++) {293 for (i = 0; i < coeffs->nX; i++) { 294 for (j = 0; j < coeffs->nY; j++) { 284 295 coeffs->coeff[i][j] = sums[i][j]; 285 coeffs->coeff[i][j] /= (float)(input->numRows * input->numCols);296 coeffs->coeff[i][j] /= (float)(input->numRows * input->numCols); 286 297 287 298 if ((i != 0) && (j != 0)) { 288 coeffs->coeff[i][j] *= 4.0;289 } else 290 if ((i == 0) && (j == 0)) {291 coeffs->coeff[i][j]*= 1.0;292 } else {293 coeffs->coeff[i][j]*= 2.0;294 }295 }296 } 297 298 // Free the Chebyshev polynomials that werecreated in this routine.299 for (i =0;i<maxChebyPoly;i++) {299 coeffs->coeff[i][j] *= 4.0; 300 } else if ((i == 0) && (j == 0)) { 301 coeffs->coeff[i][j] *= 1.0; 302 } else { 303 coeffs->coeff[i][j] *= 2.0; 304 } 305 } 306 } 307 308 // Free the Chebyshev polynomials that were 309 // created in this routine. 310 for (i = 0; i < maxChebyPoly; i++) { 300 311 psFree(chebPolys[i]); 301 312 } … … 303 314 304 315 // Free some data 305 for (i =0;i<coeffs->nX;i++) {316 for (i = 0; i < coeffs->nX; i++) { 306 317 psFree(sums[i]); 307 318 } … … 310 321 psFree(rScalingFactors); 311 322 312 return (coeffs);323 return (coeffs); 313 324 } 314 325 … … 316 327 317 328 *****************************************************************************/ 318 int 319 psImageEvalPolynomial(const psImage *input, 320 const psPolynomial2D *coeffs) 329 int psImageEvalPolynomial(const psImage * input, const psPolynomial2D * coeffs) 321 330 { 322 331 int x = 0; … … 331 340 float polySum = 0.0; 332 341 333 // Create the sums[][] data structure. This will hold the LHS of equation 334 // 29 in the ADD: sums[k][l] = SUM { image(x,y) * Tk(x) * Tl(y) } 335 sums = (float **) psAlloc(coeffs->nX * sizeof(float *)); 336 for (i=0;i<coeffs->nX;i++) { 337 sums[i] = (float *) psAlloc(coeffs->nY * sizeof(float)); 338 } 339 for (i=0;i<coeffs->nX;i++) { 340 for (j=0;j<coeffs->nY;j++) { 342 // Create the sums[][] data structure. This 343 // will hold the LHS of 344 // equation 345 // 29 in the ADD: sums[k][l] = SUM { 346 // image(x,y) * Tk(x) * Tl(y) } 347 sums = (float **)psAlloc(coeffs->nX * sizeof(float *)); 348 for (i = 0; i < coeffs->nX; i++) { 349 sums[i] = (float *)psAlloc(coeffs->nY * sizeof(float)); 350 } 351 for (i = 0; i < coeffs->nX; i++) { 352 for (j = 0; j < coeffs->nY; j++) { 341 353 sums[i][j] = 0.0; 342 354 } 343 355 } 344 356 345 // We scale the pixel positions to values between -1.0 and 1.0 357 // We scale the pixel positions to values 358 // between -1.0 and 1.0 346 359 rScalingFactors = p_psCalcScaleFactorsEval(input->numRows); 347 360 cScalingFactors = p_psCalcScaleFactorsEval(input->numCols); 348 361 349 // Determine how many Chebyshev polynomials are needed, then create them. 362 // Determine how many Chebyshev polynomials 363 // are needed, then create them. 350 364 maxChebyPoly = coeffs->nX; 351 365 if (coeffs->nY > coeffs->nX) { … … 355 369 chebPolys = p_psCreateChebyshevPolys(maxChebyPoly); 356 370 357 for (x =0;x<input->numRows;x++) {358 for (y =0;y<input->numCols;y++) {371 for (x = 0; x < input->numRows; x++) { 372 for (y = 0; y < input->numCols; y++) { 359 373 polySum = 0.0; 360 for (i=0;i<coeffs->nX;i++) { 361 for (j=0;j<coeffs->nY;j++) { 362 polySum+= psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 363 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]) * 364 coeffs->coeff[i][j]; 374 for (i = 0; i < coeffs->nX; i++) { 375 for (j = 0; j < coeffs->nY; j++) { 376 polySum += 377 psPolynomial1DEval 378 (rScalingFactors[x], 379 chebPolys[i]) * 380 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]) * coeffs->coeff[i][j]; 365 381 366 382 } … … 370 386 } 371 387 372 // Free the Chebyshev polynomials that were created in this routine. 373 for (i=0;i<maxChebyPoly;i++) { 388 // Free the Chebyshev polynomials that were 389 // created in this routine. 390 for (i = 0; i < maxChebyPoly; i++) { 374 391 psFree(chebPolys[i]); 375 392 } … … 377 394 378 395 // Free some data 379 for (i =0;i<coeffs->nX;i++) {396 for (i = 0; i < coeffs->nX; i++) { 380 397 psFree(sums[i]); 381 398 } … … 384 401 psFree(rScalingFactors); 385 402 386 return (0);387 } 403 return (0); 404 } -
trunk/psLib/src/image/psImageStats.h
r1374 r1407 1 1 2 /** @file psImageStats.h 2 3 * \brief Routines for calculating statistics on images. … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 0$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 4 00:55:17$12 * @version $Revision: 1.11 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_IMAGE_STATS_H) 17 # define PS_IMAGE_STATS_H18 # define PS_IMAGE_STATS_H 18 19 19 20 #include "psType.h" 21 #include "psVector.h" 22 #include "psImage.h" 23 #include "psStats.h" 24 #include "psFunctions.h" 20 # include "psType.h" 21 # include "psVector.h" 22 # include "psImage.h" 23 # include "psStats.h" 24 # include "psFunctions.h" 25 25 26 26 /// @addtogroup ImageStats … … 28 28 29 29 /// This routine must determine the various statistics for the image. 30 psStats *psImageStats( psStats *stats, ///< defines statistics to be calculated 31 psImage *in, ///< image (or subimage) to calculate stats 32 psImage *mask, ///< mask data for image (NULL ok) 33 int maskVal ); ///< mask Mask for mask 34 35 36 psHistogram *psImageHistogram( psHistogram *out, ///< input histogram description & target 37 psImage *in, ///< Image data to be histogramed. 38 psImage *mask, ///< mask data for image (NULL ok) 39 unsigned int maskVal ); ///< mask Mask for mask 40 30 psStats *psImageStats(psStats * stats, // /< defines statistics to be calculated 31 psImage * in, // /< image (or subimage) to calculate stats 32 psImage * mask, // /< mask data for image (NULL ok) 33 int maskVal); // /< mask Mask for mask 34 35 psHistogram *psImageHistogram(psHistogram * out, // /< input histogram description & target 36 psImage * in, // /< Image data to be histogramed. 37 psImage * mask, // /< mask data for image (NULL ok) 38 unsigned int maskVal); // /< mask Mask for mask 39 41 40 /// Fit a 2-D polynomial surface to an image. 42 psPolynomial2D * 43 psImageFitPolynomial( const psImage *input, ///< image to fit 44 psPolynomial2D *coeffs ///< coefficient structure carries indesired terms & target45 );46 41 psPolynomial2D *psImageFitPolynomial(const psImage * input, // /< image to fit 42 psPolynomial2D * coeffs // /< coefficient structure carries in 43 // desired terms & target 44 ); 45 47 46 /// Evaluate a 2-D polynomial surface to image pixels. 48 int 49 psImageEvalPolynomial( const psImage *input, ///< image to fit 50 const psPolynomial2D *coeffs ///< coefficient structure carries in desired terms 51 ); 52 47 int psImageEvalPolynomial(const psImage * input, // /< image to fit 48 const psPolynomial2D * coeffs // /< coefficient structure carries in desired terms 49 ); 50 53 51 /// @} 54 52 -
trunk/psLib/src/imageops/psImageStats.c
r1406 r1407 1 1 2 /** @file psImageStats.c 2 3 * \brief Routines for calculating statistics on images. … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1. 29$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.30 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 32 33 33 34 /// This routine must determine the various statistics for the image. 35 34 36 /***************************************************************************** 35 37 NOTE: verify that image/mask have the correct types, and sizes. 36 38 *****************************************************************************/ 37 psStats *psImageStats(psStats *stats, 38 psImage *in, 39 psImage *mask, 40 int maskVal) 41 { 42 psVector* junkData=NULL; 43 psVector* junkMask=NULL; 39 psStats *psImageStats(psStats * stats, psImage * in, psImage * mask, int maskVal) 40 { 41 psVector *junkData = NULL; 42 psVector *junkMask = NULL; 44 43 45 44 if (stats == NULL) { 46 psError(__func__, "The input psStats struct can not be NULL.");45 psError(__func__, "The input psStats struct can not be NULL."); 47 46 return NULL; 48 47 } 49 48 50 49 if (in == NULL) { 51 psError(__func__, "The input image can not be NULL.");50 psError(__func__, "The input image can not be NULL."); 52 51 return NULL; 53 52 } 54 53 55 54 if (stats->options == 0) { 56 psError(__func__, "No statistic option/operation was specified.");55 psError(__func__, "No statistic option/operation was specified."); 57 56 return stats; 58 57 } 59 60 // st uff the image data into a psVector struct.58 // stuff the image data into a psVector 59 // struct. 61 60 junkData = psAlloc(sizeof(psVector)); 62 61 junkData->type = in->type; 63 junkData->nalloc = in->numRows *in->numCols;62 junkData->nalloc = in->numRows * in->numCols; 64 63 junkData->n = junkData->nalloc; 65 junkData->data.V = in->data.V[0]; // since psImage data is contiguous... 64 junkData->data.V = in->data.V[0]; // since 65 // psImage 66 // data 67 // is 68 // contiguous... 66 69 67 70 if (mask != NULL) { 68 71 if (mask->type.type != PS_TYPE_MASK) { 69 psError(__func__, "Expected the mask image type not found (type=%x)", 70 mask->type.type); 72 psError(__func__, "Expected the mask image type not found (type=%x)", mask->type.type); 71 73 psFree(junkData); 72 74 return NULL; 73 75 } 74 75 // st uff the mask data into a psVector struct.76 // stuff the mask data into a psVector 77 // struct. 76 78 junkMask = psAlloc(sizeof(psVector)); 77 79 junkMask->type = mask->type; 78 junkMask->nalloc = mask->numRows *mask->numCols;80 junkMask->nalloc = mask->numRows * mask->numCols; 79 81 junkMask->n = junkMask->nalloc; 80 82 junkMask->data.V = mask->data.V[0]; … … 85 87 psFree(junkMask); 86 88 psFree(junkData); 87 return (stats);89 return (stats); 88 90 } 89 91 … … 93 95 NOTE: verify that image/mask have the, correct types and sizes. 94 96 *****************************************************************************/ 95 psHistogram *psImageHistogram(psHistogram *out, 96 psImage *in, 97 psImage *mask, 98 unsigned int maskVal) 99 { 100 psVector *junkData=NULL; 101 psVector *junkMask=NULL; 97 psHistogram *psImageHistogram(psHistogram * out, psImage * in, psImage * mask, unsigned int maskVal) 98 { 99 psVector *junkData = NULL; 100 psVector *junkMask = NULL; 102 101 103 102 // NOTE: Verify this action. 104 if ((out == NULL) || 105 (in == NULL)) { 106 return(NULL); 103 if ((out == NULL) || (in == NULL)) { 104 return (NULL); 107 105 } 108 106 109 107 junkData = psAlloc(sizeof(psVector)); 110 108 junkData->type = in->type; 111 junkData->nalloc = in->numRows *in->numCols;109 junkData->nalloc = in->numRows * in->numCols; 112 110 junkData->n = junkData->nalloc; 113 junkData->data.V = in->data.V[0]; // since psImage data is contiguous... 111 junkData->data.V = in->data.V[0]; // since 112 // psImage 113 // data 114 // is 115 // contiguous... 114 116 115 117 if (mask != NULL) { 116 118 if (mask->type.type != PS_TYPE_MASK) { 117 psError(__func__, "Expected the mask image type not found (type=%x)", 118 mask->type.type); 119 psError(__func__, "Expected the mask image type not found (type=%x)", mask->type.type); 119 120 psFree(junkData); 120 121 return NULL; 121 122 } 122 123 // st uff the mask data into a psVector struct.123 // stuff the mask data into a psVector 124 // struct. 124 125 junkMask = psAlloc(sizeof(psVector)); 125 126 junkMask->type = mask->type; 126 junkMask->nalloc = mask->numRows *mask->numCols;127 junkMask->nalloc = mask->numRows * mask->numCols; 127 128 junkMask->n = junkMask->nalloc; 128 129 junkMask->data.V = mask->data.V[0]; … … 134 135 psFree(junkData); 135 136 136 return (out);137 return (out); 137 138 } 138 139 … … 141 142 int i = 0; 142 143 float tmp = 0.0; 143 float *scalingFactors = (float *) psAlloc(n * sizeof(float)); 144 145 for (i=0;i<n;i++) { 146 // ((2.0 * (float) i) / ((float) (n-1))) - 1.0; 147 // tmp = (float) (i + 1); 148 tmp = (float) (n - i); 149 tmp = (M_PI * (tmp - 0.5)) / ((float) n); 144 float *scalingFactors = (float *)psAlloc(n * sizeof(float)); 145 146 for (i = 0; i < n; i++) { 147 // ((2.0 * (float) i) / ((float) (n-1))) 148 // - 1.0; 149 // tmp = (float) (i + 1); 150 tmp = (float)(n - i); 151 tmp = (M_PI * (tmp - 0.5)) / ((float)n); 150 152 scalingFactors[i] = cos(tmp); 151 153 } 152 154 153 return (scalingFactors);155 return (scalingFactors); 154 156 } 155 157 … … 165 167 int i = 0; 166 168 float tmp = 0.0; 169 167 170 return p_psCalcScaleFactorsFit(n); 168 171 169 172 printf("Should not get here\n"); 170 float *scalingFactors = (float *) psAlloc(n * sizeof(float)); 171 for (i=0;i<n;i++) { 172 // scalingFactors[i] = ((2.0 * (float) i) / ((float) (n-1))) - 1.0; 173 tmp = (float) (n - i); 174 tmp = (M_PI * (tmp - 0.5)) / ((float) n); 173 float *scalingFactors = (float *)psAlloc(n * sizeof(float)); 174 175 for (i = 0; i < n; i++) { 176 // scalingFactors[i] = ((2.0 * (float) i) 177 // / ((float) (n-1))) - 1.0; 178 tmp = (float)(n - i); 179 tmp = (M_PI * (tmp - 0.5)) / ((float)n); 175 180 scalingFactors[i] = cos(tmp); 176 181 } 177 return (scalingFactors);182 return (scalingFactors); 178 183 } 179 184 … … 184 189 int j = 0; 185 190 186 chebPolys = (psPolynomial1D **) psAlloc(maxChebyPoly * 187 sizeof(psPolynomial1D *));188 for (i=0;i<maxChebyPoly;i++) {189 chebPolys[i] = psPolynomial1DAlloc(i+1);190 } 191 192 // Create the Chebyshev polynomials.Polynomial i has i-th order.191 chebPolys = (psPolynomial1D **) psAlloc(maxChebyPoly * sizeof(psPolynomial1D *)); 192 for (i = 0; i < maxChebyPoly; i++) { 193 chebPolys[i] = psPolynomial1DAlloc(i + 1); 194 } 195 196 // Create the Chebyshev polynomials. 197 // Polynomial i has i-th order. 193 198 chebPolys[0]->coeff[0] = 1; 194 199 chebPolys[1]->coeff[1] = 1; 195 for (i=2;i<maxChebyPoly;i++) { 196 for (j=0;j<chebPolys[i-1]->n;j++) { 197 chebPolys[i]->coeff[j+1] = 2 * chebPolys[i-1]->coeff[j]; 198 } 199 for (j=0;j<chebPolys[i-2]->n;j++) { 200 chebPolys[i]->coeff[j]-= chebPolys[i-2]->coeff[j]; 201 } 202 } 203 204 return(chebPolys); 205 } 206 200 for (i = 2; i < maxChebyPoly; i++) { 201 for (j = 0; j < chebPolys[i - 1]->n; j++) { 202 chebPolys[i]->coeff[j + 1] = 2 * chebPolys[i - 1]->coeff[j]; 203 } 204 for (j = 0; j < chebPolys[i - 2]->n; j++) { 205 chebPolys[i]->coeff[j] -= chebPolys[i - 2]->coeff[j]; 206 } 207 } 208 209 return (chebPolys); 210 } 207 211 208 212 /***************************************************************************** … … 220 224 over all pixels (x,y) in the image. 221 225 *****************************************************************************/ 222 psPolynomial2D * 223 psImageFitPolynomial(const psImage *input, 224 psPolynomial2D *coeffs) 226 psPolynomial2D *psImageFitPolynomial(const psImage * input, psPolynomial2D * coeffs) 225 227 { 226 228 int x = 0; … … 235 237 float tmp = 0.0; 236 238 237 // Create the sums[][] data structure. This will hold the LHS of equation 238 // 29 in the ADD: sums[k][l] = SUM { image(x,y) * Tk(x) * Tl(y) } 239 sums = (float **) psAlloc(coeffs->nX * sizeof(float *)); 240 for (i=0;i<coeffs->nX;i++) { 241 sums[i] = (float *) psAlloc(coeffs->nY * sizeof(float)); 242 } 243 244 // We scale the pixel positions to values between -1.0 and 1.0 239 // Create the sums[][] data structure. This 240 // will hold the LHS of 241 // equation 242 // 29 in the ADD: sums[k][l] = SUM { 243 // image(x,y) * Tk(x) * Tl(y) } 244 sums = (float **)psAlloc(coeffs->nX * sizeof(float *)); 245 for (i = 0; i < coeffs->nX; i++) { 246 sums[i] = (float *)psAlloc(coeffs->nY * sizeof(float)); 247 } 248 249 // We scale the pixel positions to values 250 // between -1.0 and 1.0 245 251 rScalingFactors = p_psCalcScaleFactorsFit(input->numRows); 246 252 cScalingFactors = p_psCalcScaleFactorsFit(input->numCols); 247 253 248 // Determine how many Chebyshev polynomials are needed, then create them. 254 // Determine how many Chebyshev polynomials 255 // are needed, then create them. 249 256 maxChebyPoly = coeffs->nX; 250 257 if (coeffs->nY > coeffs->nX) { … … 254 261 255 262 // Sanity check for the Chebyshevs. 256 for (i =0;i<coeffs->nX;i++) {257 for (j =0;j<coeffs->nY;j++) {263 for (i = 0; i < coeffs->nX; i++) { 264 for (j = 0; j < coeffs->nY; j++) { 258 265 tmp = 0.0; 259 for (x=0;x<input->numRows;x++) { 260 tmp+= psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 261 psPolynomial1DEval(rScalingFactors[x], chebPolys[j]); 266 for (x = 0; x < input->numRows; x++) { 267 tmp += 268 psPolynomial1DEval 269 (rScalingFactors[x], chebPolys[i]) * psPolynomial1DEval(rScalingFactors[x], chebPolys[j]); 262 270 263 271 } 264 //printf("SUM(Cheby(%d) * Cheby(%d)) is %f\n", i, j, tmp); 272 // printf("SUM(Cheby(%d) * Cheby(%d)) 273 // is %f\n", i, j, tmp); 265 274 } 266 275 } 267 276 268 277 // Compute the sums[][] data structure. 269 for (i =0;i<coeffs->nX;i++) {270 for (j =0;j<coeffs->nY;j++) {278 for (i = 0; i < coeffs->nX; i++) { 279 for (j = 0; j < coeffs->nY; j++) { 271 280 sums[i][j] = 0.0; 272 for (x=0;x<input->numRows;x++) { 273 for (y=0;y<input->numCols;y++) { 274 sums[i][j]+= input->data.F32[x][y] * 275 psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 276 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]); 281 for (x = 0; x < input->numRows; x++) { 282 for (y = 0; y < input->numCols; y++) { 283 sums[i][j] += 284 input->data.F32[x][y] * 285 psPolynomial1DEval 286 (rScalingFactors[x], 287 chebPolys[i]) * psPolynomial1DEval(cScalingFactors[y], chebPolys[j]); 277 288 } 278 289 } … … 280 291 } 281 292 282 for (i =0;i<coeffs->nX;i++) {283 for (j =0;j<coeffs->nY;j++) {293 for (i = 0; i < coeffs->nX; i++) { 294 for (j = 0; j < coeffs->nY; j++) { 284 295 coeffs->coeff[i][j] = sums[i][j]; 285 coeffs->coeff[i][j] /= (float)(input->numRows * input->numCols);296 coeffs->coeff[i][j] /= (float)(input->numRows * input->numCols); 286 297 287 298 if ((i != 0) && (j != 0)) { 288 coeffs->coeff[i][j] *= 4.0;289 } else 290 if ((i == 0) && (j == 0)) {291 coeffs->coeff[i][j]*= 1.0;292 } else {293 coeffs->coeff[i][j]*= 2.0;294 }295 }296 } 297 298 // Free the Chebyshev polynomials that werecreated in this routine.299 for (i =0;i<maxChebyPoly;i++) {299 coeffs->coeff[i][j] *= 4.0; 300 } else if ((i == 0) && (j == 0)) { 301 coeffs->coeff[i][j] *= 1.0; 302 } else { 303 coeffs->coeff[i][j] *= 2.0; 304 } 305 } 306 } 307 308 // Free the Chebyshev polynomials that were 309 // created in this routine. 310 for (i = 0; i < maxChebyPoly; i++) { 300 311 psFree(chebPolys[i]); 301 312 } … … 303 314 304 315 // Free some data 305 for (i =0;i<coeffs->nX;i++) {316 for (i = 0; i < coeffs->nX; i++) { 306 317 psFree(sums[i]); 307 318 } … … 310 321 psFree(rScalingFactors); 311 322 312 return (coeffs);323 return (coeffs); 313 324 } 314 325 … … 316 327 317 328 *****************************************************************************/ 318 int 319 psImageEvalPolynomial(const psImage *input, 320 const psPolynomial2D *coeffs) 329 int psImageEvalPolynomial(const psImage * input, const psPolynomial2D * coeffs) 321 330 { 322 331 int x = 0; … … 331 340 float polySum = 0.0; 332 341 333 // Create the sums[][] data structure. This will hold the LHS of equation 334 // 29 in the ADD: sums[k][l] = SUM { image(x,y) * Tk(x) * Tl(y) } 335 sums = (float **) psAlloc(coeffs->nX * sizeof(float *)); 336 for (i=0;i<coeffs->nX;i++) { 337 sums[i] = (float *) psAlloc(coeffs->nY * sizeof(float)); 338 } 339 for (i=0;i<coeffs->nX;i++) { 340 for (j=0;j<coeffs->nY;j++) { 342 // Create the sums[][] data structure. This 343 // will hold the LHS of 344 // equation 345 // 29 in the ADD: sums[k][l] = SUM { 346 // image(x,y) * Tk(x) * Tl(y) } 347 sums = (float **)psAlloc(coeffs->nX * sizeof(float *)); 348 for (i = 0; i < coeffs->nX; i++) { 349 sums[i] = (float *)psAlloc(coeffs->nY * sizeof(float)); 350 } 351 for (i = 0; i < coeffs->nX; i++) { 352 for (j = 0; j < coeffs->nY; j++) { 341 353 sums[i][j] = 0.0; 342 354 } 343 355 } 344 356 345 // We scale the pixel positions to values between -1.0 and 1.0 357 // We scale the pixel positions to values 358 // between -1.0 and 1.0 346 359 rScalingFactors = p_psCalcScaleFactorsEval(input->numRows); 347 360 cScalingFactors = p_psCalcScaleFactorsEval(input->numCols); 348 361 349 // Determine how many Chebyshev polynomials are needed, then create them. 362 // Determine how many Chebyshev polynomials 363 // are needed, then create them. 350 364 maxChebyPoly = coeffs->nX; 351 365 if (coeffs->nY > coeffs->nX) { … … 355 369 chebPolys = p_psCreateChebyshevPolys(maxChebyPoly); 356 370 357 for (x =0;x<input->numRows;x++) {358 for (y =0;y<input->numCols;y++) {371 for (x = 0; x < input->numRows; x++) { 372 for (y = 0; y < input->numCols; y++) { 359 373 polySum = 0.0; 360 for (i=0;i<coeffs->nX;i++) { 361 for (j=0;j<coeffs->nY;j++) { 362 polySum+= psPolynomial1DEval(rScalingFactors[x], chebPolys[i]) * 363 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]) * 364 coeffs->coeff[i][j]; 374 for (i = 0; i < coeffs->nX; i++) { 375 for (j = 0; j < coeffs->nY; j++) { 376 polySum += 377 psPolynomial1DEval 378 (rScalingFactors[x], 379 chebPolys[i]) * 380 psPolynomial1DEval(cScalingFactors[y], chebPolys[j]) * coeffs->coeff[i][j]; 365 381 366 382 } … … 370 386 } 371 387 372 // Free the Chebyshev polynomials that were created in this routine. 373 for (i=0;i<maxChebyPoly;i++) { 388 // Free the Chebyshev polynomials that were 389 // created in this routine. 390 for (i = 0; i < maxChebyPoly; i++) { 374 391 psFree(chebPolys[i]); 375 392 } … … 377 394 378 395 // Free some data 379 for (i =0;i<coeffs->nX;i++) {396 for (i = 0; i < coeffs->nX; i++) { 380 397 psFree(sums[i]); 381 398 } … … 384 401 psFree(rScalingFactors); 385 402 386 return (0);387 } 403 return (0); 404 } -
trunk/psLib/src/imageops/psImageStats.h
r1374 r1407 1 1 2 /** @file psImageStats.h 2 3 * \brief Routines for calculating statistics on images. … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 0$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 4 00:55:17$12 * @version $Revision: 1.11 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_IMAGE_STATS_H) 17 # define PS_IMAGE_STATS_H18 # define PS_IMAGE_STATS_H 18 19 19 20 #include "psType.h" 21 #include "psVector.h" 22 #include "psImage.h" 23 #include "psStats.h" 24 #include "psFunctions.h" 20 # include "psType.h" 21 # include "psVector.h" 22 # include "psImage.h" 23 # include "psStats.h" 24 # include "psFunctions.h" 25 25 26 26 /// @addtogroup ImageStats … … 28 28 29 29 /// This routine must determine the various statistics for the image. 30 psStats *psImageStats( psStats *stats, ///< defines statistics to be calculated 31 psImage *in, ///< image (or subimage) to calculate stats 32 psImage *mask, ///< mask data for image (NULL ok) 33 int maskVal ); ///< mask Mask for mask 34 35 36 psHistogram *psImageHistogram( psHistogram *out, ///< input histogram description & target 37 psImage *in, ///< Image data to be histogramed. 38 psImage *mask, ///< mask data for image (NULL ok) 39 unsigned int maskVal ); ///< mask Mask for mask 40 30 psStats *psImageStats(psStats * stats, // /< defines statistics to be calculated 31 psImage * in, // /< image (or subimage) to calculate stats 32 psImage * mask, // /< mask data for image (NULL ok) 33 int maskVal); // /< mask Mask for mask 34 35 psHistogram *psImageHistogram(psHistogram * out, // /< input histogram description & target 36 psImage * in, // /< Image data to be histogramed. 37 psImage * mask, // /< mask data for image (NULL ok) 38 unsigned int maskVal); // /< mask Mask for mask 39 41 40 /// Fit a 2-D polynomial surface to an image. 42 psPolynomial2D * 43 psImageFitPolynomial( const psImage *input, ///< image to fit 44 psPolynomial2D *coeffs ///< coefficient structure carries indesired terms & target45 );46 41 psPolynomial2D *psImageFitPolynomial(const psImage * input, // /< image to fit 42 psPolynomial2D * coeffs // /< coefficient structure carries in 43 // desired terms & target 44 ); 45 47 46 /// Evaluate a 2-D polynomial surface to image pixels. 48 int 49 psImageEvalPolynomial( const psImage *input, ///< image to fit 50 const psPolynomial2D *coeffs ///< coefficient structure carries in desired terms 51 ); 52 47 int psImageEvalPolynomial(const psImage * input, // /< image to fit 48 const psPolynomial2D * coeffs // /< coefficient structure carries in desired terms 49 ); 50 53 51 /// @} 54 52 -
trunk/psLib/src/math/psCompare.c
r1393 r1407 1 1 2 /** @file psCompare.c 2 3 * @brief Comparison functions for sorting routines … … 6 7 * @author Robert Daniel DeSonia, MHPCC 7 8 * 8 * @version $Revision: 1. 3$ $Name: not supported by cvs2svn $9 * @date $Date: 2004-08-0 5 19:38:52$9 * @version $Revision: 1.4 $ $Name: not supported by cvs2svn $ 10 * @date $Date: 2004-08-07 00:06:06 $ 10 11 * 11 12 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii -
trunk/psLib/src/math/psCompare.h
r1111 r1407 1 1 #if !defined(PS_COMPARE_H) 2 # define PS_COMPARE_H2 # define PS_COMPARE_H 3 3 4 4 /** @file psCompare.h … … 9 9 * @ingroup Compare 10 10 * 11 * @version $Revision: 1. 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-0 6-28 20:36:37$11 * @version $Revision: 1.2 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 13 13 * 14 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 26 26 * than, equal to, or greater than the second. 27 27 */ 28 typedef int (*psComparePtrFcn) (const void** a, const void**b);28 typedef int (*psComparePtrFcn) (const void **a, const void **b); 29 29 30 30 /** A comparison function for sorting. … … 34 34 * than, equal to, or greater than the second. 35 35 */ 36 typedef int (*psCompareFcn) (const void* a, const void*b);36 typedef int (*psCompareFcn) (const void *a, const void *b); 37 37 38 38 /** Compare function of psS8 data. For use with psListSort. … … 42 42 * than, equal to, or greater than the second. 43 43 */ 44 int psCompareS8Ptr(const void ** a, const void**b);44 int psCompareS8Ptr(const void **a, const void **b); 45 45 46 46 /** Compare function of psS16 data. For use with psListSort. … … 50 50 * than, equal to, or greater than the second. 51 51 */ 52 int psCompareS16Ptr(const void ** a, const void**b);52 int psCompareS16Ptr(const void **a, const void **b); 53 53 54 54 /** Compare function of psS32 data. For use with psListSort. … … 58 58 * than, equal to, or greater than the second. 59 59 */ 60 int psCompareS32Ptr(const void ** a, const void**b);60 int psCompareS32Ptr(const void **a, const void **b); 61 61 62 62 /** Compare function of psS64 data. For use with psListSort. … … 66 66 * than, equal to, or greater than the second. 67 67 */ 68 int psCompareS64Ptr(const void ** a, const void**b);68 int psCompareS64Ptr(const void **a, const void **b); 69 69 70 70 /** Compare function of psU8 data. For use with psListSort. … … 74 74 * than, equal to, or greater than the second. 75 75 */ 76 int psCompareU8Ptr(const void ** a, const void**b);76 int psCompareU8Ptr(const void **a, const void **b); 77 77 78 78 /** Compare function of psU16 data. For use with psListSort. … … 82 82 * than, equal to, or greater than the second. 83 83 */ 84 int psCompareU16Ptr(const void ** a, const void**b);84 int psCompareU16Ptr(const void **a, const void **b); 85 85 86 86 /** Compare function of psU32 data. For use with psListSort. … … 90 90 * than, equal to, or greater than the second. 91 91 */ 92 int psCompareU32Ptr(const void ** a, const void**b);92 int psCompareU32Ptr(const void **a, const void **b); 93 93 94 94 /** Compare function of psU64 data. For use with psListSort. … … 98 98 * than, equal to, or greater than the second. 99 99 */ 100 int psCompareU64Ptr(const void ** a, const void**b);100 int psCompareU64Ptr(const void **a, const void **b); 101 101 102 102 /** Compare function of psF32 data. For use with psListSort. … … 106 106 * than, equal to, or greater than the second. 107 107 */ 108 int psCompareF32Ptr(const void ** a, const void**b);108 int psCompareF32Ptr(const void **a, const void **b); 109 109 110 110 /** Compare function of psF64 data. For use with psListSort. … … 114 114 * than, equal to, or greater than the second. 115 115 */ 116 int psCompareF64Ptr(const void ** a, const void**b);116 int psCompareF64Ptr(const void **a, const void **b); 117 117 118 118 /** Compare function of psS8 data. For use with psListSort for descending ordering. … … 122 122 * than, equal to, or less than the second. 123 123 */ 124 int psCompareDescendingS8Ptr(const void ** a, const void**b);124 int psCompareDescendingS8Ptr(const void **a, const void **b); 125 125 126 126 /** Compare function of psS16 data. For use with psListSort for descending ordering. … … 130 130 * than, equal to, or less than the second. 131 131 */ 132 int psCompareDescendingS16Ptr(const void ** a, const void**b);132 int psCompareDescendingS16Ptr(const void **a, const void **b); 133 133 134 134 /** Compare function of psS32 data. For use with psListSort for descending ordering. … … 138 138 * than, equal to, or less than the second. 139 139 */ 140 int psCompareDescendingS32Ptr(const void ** a, const void**b);140 int psCompareDescendingS32Ptr(const void **a, const void **b); 141 141 142 142 /** Compare function of psS64 data. For use with psListSort for descending ordering. … … 146 146 * than, equal to, or less than the second. 147 147 */ 148 int psCompareDescendingS64Ptr(const void ** a, const void**b);148 int psCompareDescendingS64Ptr(const void **a, const void **b); 149 149 150 150 /** Compare function of psU8 data. For use with psListSort for descending ordering. … … 154 154 * than, equal to, or less than the second. 155 155 */ 156 int psCompareDescendingU8Ptr(const void ** a, const void**b);156 int psCompareDescendingU8Ptr(const void **a, const void **b); 157 157 158 158 /** Compare function of psU16 data. For use with psListSort for descending ordering. … … 162 162 * than, equal to, or less than the second. 163 163 */ 164 int psCompareDescendingU16Ptr(const void ** a, const void**b);164 int psCompareDescendingU16Ptr(const void **a, const void **b); 165 165 166 166 /** Compare function of psU32 data. For use with psListSort for descending ordering. … … 170 170 * than, equal to, or lessg than the second. 171 171 */ 172 int psCompareDescendingU32Ptr(const void ** a, const void**b);172 int psCompareDescendingU32Ptr(const void **a, const void **b); 173 173 174 174 /** Compare function of psU64 data. For use with psListSort for descending ordering. … … 178 178 * than, equal to, or lessg than the second. 179 179 */ 180 int psCompareDescendingU64Ptr(const void ** a, const void**b);180 int psCompareDescendingU64Ptr(const void **a, const void **b); 181 181 182 182 /** Compare function of psF32 data. For use with psListSort for descending ordering. … … 186 186 * than, equal to, or lessg than the second. 187 187 */ 188 int psCompareDescendingF32Ptr(const void ** a, const void**b);188 int psCompareDescendingF32Ptr(const void **a, const void **b); 189 189 190 190 /** Compare function of psF64 data. For use with psListSort for descending ordering. … … 194 194 * than, equal to, or lessg than the second. 195 195 */ 196 int psCompareDescendingF64Ptr(const void ** a, const void**b);196 int psCompareDescendingF64Ptr(const void **a, const void **b); 197 197 198 198 /** Compare function of psS8 data. … … 202 202 * than, equal to, or greater than the second. 203 203 */ 204 int psCompareS8(const void * a, const void*b);204 int psCompareS8(const void *a, const void *b); 205 205 206 206 /** Compare function of psS16 data. … … 210 210 * than, equal to, or greater than the second. 211 211 */ 212 int psCompareS16(const void * a, const void*b);212 int psCompareS16(const void *a, const void *b); 213 213 214 214 /** Compare function of psS32 data. … … 218 218 * than, equal to, or greater than the second. 219 219 */ 220 int psCompareS32(const void * a, const void*b);220 int psCompareS32(const void *a, const void *b); 221 221 222 222 /** Compare function of psS64 data. … … 226 226 * than, equal to, or greater than the second. 227 227 */ 228 int psCompareS64(const void * a, const void*b);228 int psCompareS64(const void *a, const void *b); 229 229 230 230 /** Compare function of psU8 data. … … 234 234 * than, equal to, or greater than the second. 235 235 */ 236 int psCompareU8(const void * a, const void*b);236 int psCompareU8(const void *a, const void *b); 237 237 238 238 /** Compare function of psU16 data. … … 242 242 * than, equal to, or greater than the second. 243 243 */ 244 int psCompareU16(const void * a, const void*b);244 int psCompareU16(const void *a, const void *b); 245 245 246 246 /** Compare function of psU32 data. … … 250 250 * than, equal to, or greater than the second. 251 251 */ 252 int psCompareU32(const void * a, const void*b);252 int psCompareU32(const void *a, const void *b); 253 253 254 254 /** Compare function of psU64 data. … … 258 258 * than, equal to, or greater than the second. 259 259 */ 260 int psCompareU64(const void * a, const void*b);260 int psCompareU64(const void *a, const void *b); 261 261 262 262 /** Compare function of psF32 data. … … 266 266 * than, equal to, or greater than the second. 267 267 */ 268 int psCompareF32(const void * a, const void*b);268 int psCompareF32(const void *a, const void *b); 269 269 270 270 /** Compare function of psF64 data. … … 274 274 * than, equal to, or greater than the second. 275 275 */ 276 int psCompareF64(const void * a, const void*b);276 int psCompareF64(const void *a, const void *b); 277 277 278 278 /** Compare function of psS8 data. … … 282 282 * than, equal to, or less than the second. 283 283 */ 284 int psCompareDescendingS8(const void * a, const void*b);284 int psCompareDescendingS8(const void *a, const void *b); 285 285 286 286 /** Compare function of psS16 data. … … 290 290 * than, equal to, or less than the second. 291 291 */ 292 int psCompareDescendingS16(const void * a, const void*b);292 int psCompareDescendingS16(const void *a, const void *b); 293 293 294 294 /** Compare function of psS32 data. … … 298 298 * than, equal to, or less than the second. 299 299 */ 300 int psCompareDescendingS32(const void * a, const void*b);300 int psCompareDescendingS32(const void *a, const void *b); 301 301 302 302 /** Compare function of psS64 data. … … 306 306 * than, equal to, or less than the second. 307 307 */ 308 int psCompareDescendingS64(const void * a, const void*b);308 int psCompareDescendingS64(const void *a, const void *b); 309 309 310 310 /** Compare function of psU8 data. … … 314 314 * than, equal to, or less than the second. 315 315 */ 316 int psCompareDescendingU8(const void * a, const void*b);316 int psCompareDescendingU8(const void *a, const void *b); 317 317 318 318 /** Compare function of psU16 data. … … 322 322 * than, equal to, or less than the second. 323 323 */ 324 int psCompareDescendingU16(const void * a, const void*b);324 int psCompareDescendingU16(const void *a, const void *b); 325 325 326 326 /** Compare function of psU32 data. … … 330 330 * than, equal to, or lessg than the second. 331 331 */ 332 int psCompareDescendingU32(const void * a, const void*b);332 int psCompareDescendingU32(const void *a, const void *b); 333 333 334 334 /** Compare function of psU64 data. … … 338 338 * than, equal to, or lessg than the second. 339 339 */ 340 int psCompareDescendingU64(const void * a, const void*b);340 int psCompareDescendingU64(const void *a, const void *b); 341 341 342 342 /** Compare function of psF32 data. … … 346 346 * than, equal to, or lessg than the second. 347 347 */ 348 int psCompareDescendingF32(const void * a, const void*b);348 int psCompareDescendingF32(const void *a, const void *b); 349 349 350 350 /** Compare function of psF64 data. … … 354 354 * than, equal to, or lessg than the second. 355 355 */ 356 int psCompareDescendingF64(const void* a, const void* b); 357 358 356 int psCompareDescendingF64(const void *a, const void *b); 359 357 360 358 /// @} -
trunk/psLib/src/math/psMatrix.c
r1406 r1407 1 1 2 /** @file psMatrix.c 2 3 * … … 20 21 * @author Ross Harman, MHPCC 21 22 * 22 * @version $Revision: 1.1 0$ $Name: not supported by cvs2svn $23 * @date $Date: 2004-08-0 6 22:34:05$23 * @version $Revision: 1.11 $ $Name: not supported by cvs2svn $ 24 * @date $Date: 2004-08-07 00:06:06 $ 24 25 * 25 26 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 27 28 28 29 /******************************************************************************/ 30 29 31 /* INCLUDE FILES */ 32 30 33 /******************************************************************************/ 31 34 #include <string.h> … … 42 45 43 46 /******************************************************************************/ 47 44 48 /* DEFINE STATEMENTS */ 49 45 50 /******************************************************************************/ 46 51 … … 48 53 49 54 /******************************************************************************/ 55 50 56 /* TYPE DEFINITIONS */ 57 51 58 /******************************************************************************/ 52 59 … … 54 61 55 62 /*****************************************************************************/ 63 56 64 /* GLOBAL VARIABLES */ 65 57 66 /*****************************************************************************/ 58 67 … … 60 69 61 70 /*****************************************************************************/ 71 62 72 /* FILE STATIC VARIABLES */ 73 63 74 /*****************************************************************************/ 64 75 … … 66 77 67 78 /*****************************************************************************/ 79 68 80 /* FUNCTION IMPLEMENTATION - LOCAL */ 81 69 82 /*****************************************************************************/ 70 83 … … 142 155 143 156 /*****************************************************************************/ 157 144 158 /* FUNCTION IMPLEMENTATION - PUBLIC */ 145 /*****************************************************************************/ 146 147 psImage *psMatrixLUD(psImage *outImage, psVector *outPerm, psImage *inImage) 159 160 /*****************************************************************************/ 161 162 psImage *psMatrixLUD(psImage * outImage, psVector * outPerm, psImage * inImage) 148 163 { 149 164 int signum = 0; … … 169 184 numRows = inImage->numRows; 170 185 numCols = inImage->numCols; 171 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;186 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 172 187 173 188 // Initialize GSL data … … 190 205 } 191 206 192 psVector *psMatrixLUSolve(psVector * outVector, const psImage *inImage, const psVector *inVector, const193 psVector * inPerm)207 psVector *psMatrixLUSolve(psVector * outVector, const psImage * inImage, const psVector * inVector, const 208 psVector * inPerm) 194 209 { 195 210 int arraySize = 0; … … 219 234 numRows = inImage->numRows; 220 235 numCols = inImage->numCols; 221 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;236 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 222 237 223 238 // Initialize GSL data … … 243 258 } 244 259 245 psImage *psMatrixInvert(psImage * outImage, const psImage *inImage, float *restrict det)260 psImage *psMatrixInvert(psImage * outImage, const psImage * inImage, float *restrict det) 246 261 { 247 262 int signum = 0; … … 254 269 255 270 // Error checks 256 if (det == NULL) {271 if (det == NULL) { 257 272 psError(__func__, "Invalid operation: determinant argument is NULL."); 258 273 return outImage; … … 269 284 numRows = inImage->numRows; 270 285 numCols = inImage->numCols; 271 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;286 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 272 287 273 288 // Allocate GSL structs … … 297 312 } 298 313 299 float * psMatrixDeterminant(const psImage *restrict inImage)314 float *psMatrixDeterminant(const psImage * restrict inImage) 300 315 { 301 316 int signum = 0; … … 315 330 numRows = inImage->numRows; 316 331 numCols = inImage->numCols; 317 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;332 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 318 333 319 334 // Allocate GSL structs … … 328 343 329 344 // Calculate determinant 330 det = (float *)psAlloc(sizeof(float));345 det = (float *)psAlloc(sizeof(float)); 331 346 gsl_linalg_LU_decomp(lu, perm, &signum); 332 347 *det = (float)gsl_linalg_LU_det(lu, signum); … … 339 354 } 340 355 341 psImage * psMatrixMultiply(psImage *outImage, psImage *inImage1, psImage *inImage2)356 psImage *psMatrixMultiply(psImage * outImage, psImage * inImage1, psImage * inImage2) 342 357 { 343 358 int arraySize = 0; … … 364 379 numRows = inImage1->numRows; 365 380 numCols = inImage1->numCols; 366 arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) *numRows*numCols;381 arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) * numRows * numCols; 367 382 368 383 // Initialize GSL data … … 381 396 } 382 397 383 psImage * psMatrixTranspose(psImage *outImage, const psImage *inImage)398 psImage *psMatrixTranspose(psImage * outImage, const psImage * inImage) 384 399 { 385 400 int arraySize = 0; … … 400 415 numRows = inImage->numRows; 401 416 numCols = inImage->numCols; 402 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) *numRows*numCols;417 arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols; 403 418 404 419 // Initialize GSL data … … 418 433 } 419 434 420 psImage *psMatrixEigenvectors(psImage * outImage, psImage *inImage)435 psImage *psMatrixEigenvectors(psImage * outImage, psImage * inImage) 421 436 { 422 437 int numRows = 0; … … 462 477 } 463 478 464 psVector *psMatrixToVector(psVector * outVector, psImage *inImage)479 psVector *psMatrixToVector(psVector * outVector, psImage * inImage) 465 480 { 466 481 int size = 0; … … 471 486 PS_CHECK_SIZE_IMAGE(inImage, outVector); 472 487 473 if (inImage->numRows == 1) {488 if (inImage->numRows == 1) { 474 489 // Create transposed row vector 475 490 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numCols, inImage->type.type); 476 491 outVector->type.dimen = PS_DIMEN_TRANSV; 477 } else 478 if(inImage->numCols == 1) { 479 // Create non-transposed column vector 480 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numRows, inImage->type.type); 481 } else { 482 psError(__func__, "Image does not have dim with 1 col or 1 row: (%d x %d).", inImage->numRows, 483 inImage->numCols); 484 return outVector; 485 } 492 } else if (inImage->numCols == 1) { 493 // Create non-transposed column vector 494 PS_CHECK_ALLOC_VECTOR(outVector, inImage->numRows, inImage->type.type); 495 } else { 496 psError(__func__, "Image does not have dim with 1 col or 1 row: (%d x %d).", inImage->numRows, 497 inImage->numCols); 498 return outVector; 499 } 486 500 487 501 PS_CHECK_NULL_VECTOR(outVector, outVector); 488 502 489 490 503 // More checks 491 if (outVector->type.dimen == PS_DIMEN_VECTOR) {504 if (outVector->type.dimen == PS_DIMEN_VECTOR) { 492 505 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector); 493 506 494 if (outVector->n == 0) {507 if (outVector->n == 0) { 495 508 outVector->n = inImage->numRows; 496 509 } 497 510 498 if (outVector->n != inImage->numRows) {511 if (outVector->n != inImage->numRows) { 499 512 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numRows, outVector->n); 500 513 return outVector; 501 514 } 502 515 503 size = PSELEMTYPE_SIZEOF(inImage->type.type)*inImage->numRows; 504 505 } else 506 if(outVector->type.dimen == PS_DIMEN_TRANSV) { 507 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_TRANSV, outVector); 508 509 if(outVector->n == 0) { 510 outVector->n = inImage->numCols; 511 } 512 513 if(outVector->n != inImage->numCols) { 514 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numCols, outVector->n); 515 return outVector; 516 } 517 518 size = PSELEMTYPE_SIZEOF(inImage->type.type)*inImage->numCols; 516 size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numRows; 517 518 } else if (outVector->type.dimen == PS_DIMEN_TRANSV) { 519 PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_TRANSV, outVector); 520 521 if (outVector->n == 0) { 522 outVector->n = inImage->numCols; 519 523 } 520 524 525 if (outVector->n != inImage->numCols) { 526 psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numCols, outVector->n); 527 return outVector; 528 } 529 530 size = PSELEMTYPE_SIZEOF(inImage->type.type) * inImage->numCols; 531 } 532 521 533 memcpy(outVector->data.V, inImage->data.V[0], size); 522 534 … … 524 536 } 525 537 526 psImage *psVectorToMatrix(psImage * outImage, psVector *inVector)538 psImage *psVectorToMatrix(psImage * outImage, psVector * inVector) 527 539 { 528 540 int size = 0; … … 531 543 PS_CHECK_NULL_VECTOR(inVector, outImage); 532 544 533 if (inVector->type.dimen == PS_DIMEN_VECTOR) {545 if (inVector->type.dimen == PS_DIMEN_VECTOR) { 534 546 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outImage); 535 547 PS_CHECK_SIZE_VECTOR(inVector, outImage); 536 548 PS_CHECK_ALLOC_IMAGE(outImage, 1, inVector->n, PS_TYPE_F64) 537 538 549 // More checks for PS_DIMEN_VECTOR 539 if (outImage->numCols > 1) {550 if (outImage->numCols > 1) { 540 551 psError(__func__, "Image has more than 1 column: numCols = %d.", outImage->numCols); 541 552 return outImage; 542 } else 543 if(outImage->numRows != inVector->n) { 544 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numRows, inVector->n); 545 return outImage; 546 } 547 548 size = PSELEMTYPE_SIZEOF(outImage->type.type)*outImage->numRows; 549 550 } else 551 if(inVector->type.dimen == PS_DIMEN_TRANSV) { 552 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_TRANSV, outImage); 553 PS_CHECK_SIZE_VECTOR(inVector, outImage); 554 PS_CHECK_ALLOC_IMAGE(outImage, inVector->n, 1, PS_TYPE_F64) 555 556 // More checks for PS_DIMEN_TRANSV 557 if(outImage->numRows > 1) { 558 psError(__func__, "Image has more than 1 row: numRows = %d.", outImage->numRows); 559 return outImage; 560 } else 561 if(outImage->numCols != inVector->n) { 562 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numCols, inVector->n); 563 return outImage; 564 } 565 566 size = PSELEMTYPE_SIZEOF(outImage->type.type)*outImage->numCols; 553 } else if (outImage->numRows != inVector->n) { 554 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numRows, inVector->n); 555 return outImage; 567 556 } 557 558 size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numRows; 559 560 } else if (inVector->type.dimen == PS_DIMEN_TRANSV) { 561 PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_TRANSV, outImage); 562 PS_CHECK_SIZE_VECTOR(inVector, outImage); 563 PS_CHECK_ALLOC_IMAGE(outImage, inVector->n, 1, PS_TYPE_F64) 564 // More checks for PS_DIMEN_TRANSV 565 if (outImage->numRows > 1) { 566 psError(__func__, "Image has more than 1 row: numRows = %d.", outImage->numRows); 567 return outImage; 568 } else if (outImage->numCols != inVector->n) { 569 psError(__func__, "Image and vector sizes differ: (%d vs %d).", outImage->numCols, inVector->n); 570 return outImage; 571 } 572 573 size = PSELEMTYPE_SIZEOF(outImage->type.type) * outImage->numCols; 574 } 568 575 569 576 PS_CHECK_NULL_IMAGE(outImage, outImage); … … 574 581 return outImage; 575 582 } 576 -
trunk/psLib/src/math/psMatrix.h
r974 r1407 1 1 2 /** @file psMatrix.h 2 3 * … … 21 22 * @author Ross Harman, MHPCC 22 23 * 23 * @version $Revision: 1. 6$ $Name: not supported by cvs2svn $24 * @date $Date: 2004-0 6-10 01:58:06 $24 * @version $Revision: 1.7 $ $Name: not supported by cvs2svn $ 25 * @date $Date: 2004-08-07 00:06:06 $ 25 26 * 26 27 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 28 29 29 30 #ifndef PSMATRIX_H 30 # define PSMATRIX_H31 # define PSMATRIX_H 31 32 32 33 /// @addtogroup Matrix … … 42 43 * @return psImage*: Pointer to LU decomposed psImage. 43 44 */ 44 psImage *psMatrixLUD( 45 psImage *outImage, ///< Image to return, or NULL. 46 psVector *outPerm, ///< Output permutation vector used by psMatrixLUSolve. 47 psImage *inImage ///< Image to decompose. 48 ); 45 psImage *psMatrixLUD(psImage * outImage, // /< Image to return, or NULL. 46 psVector * outPerm, // /< Output permutation vector used by psMatrixLUSolve. 47 psImage * inImage // /< Image to decompose. 48 ); 49 49 50 50 /** LU Solution of psImage matrix. … … 57 57 * @return psVector*: Pointer to psVector solution of matrix equation. 58 58 */ 59 psVector *psMatrixLUSolve( 60 psVector *outVector, ///< Vector to return, or NULL.61 const psImage *luImage, ///< LU-decomposed matrix.62 const psVector *inVector, ///< Vector right-hand-side of equation.63 const psVector *inPerm ///< Permutation vector resulting from psMatrixLUDfunction.64 );59 psVector *psMatrixLUSolve(psVector * outVector, // /< Vector to return, or NULL. 60 const psImage * luImage, // /< LU-decomposed matrix. 61 const psVector * inVector, // /< Vector right-hand-side of equation. 62 const psVector * inPerm // /< Permutation vector resulting from psMatrixLUD 63 // function. 64 ); 65 65 66 66 /** Invert psImage matrix. … … 73 73 * @return psImage*: Pointer to inverted psImage. 74 74 */ 75 psImage *psMatrixInvert( 76 psImage *outImage, ///< Image to return, or NULL for in-place substitution. 77 const psImage *inImage, ///< Image to be inverted 78 float *restrict det ///< Determinant to return, or NULL 79 ); 75 psImage *psMatrixInvert(psImage * outImage, // /< Image to return, or NULL for in-place substitution. 76 const psImage * inImage, // /< Image to be inverted 77 float *restrict det // /< Determinant to return, or NULL 78 ); 80 79 81 80 /** Calculate psImage matrix determinant. … … 87 86 * @return float: Determinant from psImage. 88 87 */ 89 float* psMatrixDeterminant( 90 const psImage *restrict inMatrix ///< Image used to calculate determinant. 91 ); 88 float *psMatrixDeterminant(const psImage * restrict inMatrix // /< Image used to calculate determinant. 89 ); 92 90 93 91 /** Performs psImage matrix multiplication. … … 100 98 * @return psImage*: Pointer to resulting psImage. 101 99 */ 102 psImage *psMatrixMultiply( 103 psImage *outImage, ///< Matrix to return, or NULL. 104 psImage *inImage1, ///< First input image. 105 psImage *inImage2 ///< Second input image. 106 ); 100 psImage *psMatrixMultiply(psImage * outImage, // /< Matrix to return, or NULL. 101 psImage * inImage1, // /< First input image. 102 psImage * inImage2 // /< Second input image. 103 ); 107 104 108 105 /** Transpose matrix. … … 115 112 * @return psImage*: Pointer to transposed psImage. 116 113 */ 117 psImage *psMatrixTranspose( 118 psImage *outImage, ///< Image to return, or NULL 119 const psImage *inImage ///< Image to transpose 120 ); 114 psImage *psMatrixTranspose(psImage * outImage, // /< Image to return, or NULL 115 const psImage * inImage // /< Image to transpose 116 ); 121 117 122 118 /** Calculate matrix eigenvectors. … … 128 124 * @return psImage*: Pointer to matrix of Eigenvectors. 129 125 */ 130 psImage *psMatrixEigenvectors( 131 psImage *outImage, ///< Eigenvectors to return, or NULL. 132 psImage *inImage ///< Input image. 133 ); 126 psImage *psMatrixEigenvectors(psImage * outImage, // /< Eigenvectors to return, or NULL. 127 psImage * inImage // /< Input image. 128 ); 134 129 135 130 /** Convert matrix to vector. … … 142 137 * @return psVector*: Pointer to psVector. 143 138 */ 144 psVector *psMatrixToVector( 145 psVector *outVector, ///< Vector to return, or NULL. 146 psImage *inImage ///< Image to convert. 147 ); 139 psVector *psMatrixToVector(psVector * outVector, // /< Vector to return, or NULL. 140 psImage * inImage // /< Image to convert. 141 ); 148 142 149 143 /** Convert vector to matrix. … … 156 150 * @return psVector*: Pointer to psIamge. 157 151 */ 158 psImage *psVectorToMatrix( 159 psImage *outImage, ///< Matrix to return, or NULL. 160 psVector *inVector ///< Vector to convert. 161 ); 152 psImage *psVectorToMatrix(psImage * outImage, // /< Matrix to return, or NULL. 153 psVector * inVector // /< Vector to convert. 154 ); 162 155 163 156 /// @} -
trunk/psLib/src/math/psMinimize.c
r1406 r1407 1 1 2 /** @file psMinimize.c 2 3 * \brief basic minimization functions … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.2 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.28 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 /*****************************************************************************/ 17 18 /*****************************************************************************/ 19 17 20 /* INCLUDE FILES */ 21 18 22 /*****************************************************************************/ 19 23 #include <stdlib.h> … … 40 44 #include "psMinimize.h" 41 45 #include "psMatrix.h" 42 /*****************************************************************************/ 46 47 /*****************************************************************************/ 48 43 49 /* DEFINE STATEMENTS */ 50 44 51 /*****************************************************************************/ 45 52 #define MAX_LMM_ITERATIONS 100 … … 83 90 } 84 91 85 86 /*****************************************************************************/ 92 /*****************************************************************************/ 93 87 94 /* TYPE DEFINITIONS */ 95 88 96 /*****************************************************************************/ 89 97 typedef struct 90 98 { 91 size_t n; // Number of data points points in domain.92 int paramCount; // Number of non-masked parameters.93 psVector *restrict initialGuess;94 const psImage *restrict domain;99 size_t n; // Number of data points points in domain. 100 int paramCount; // Number of non-masked parameters. 101 psVector *restrict initialGuess; 102 const psImage *restrict domain; 95 103 const psVector *restrict data; 96 const psVector *restrict errors;104 const psVector *restrict errors; 97 105 const psVector *restrict paramMask; 98 106 float (*evalModel) (const psVector *, const psVector *); … … 103 111 typedef struct 104 112 { 105 int paramCount; // Number of non-masked parameters.106 psVector *restrict initialGuess;107 const psVector *restrict coord;113 int paramCount; // Number of non-masked parameters. 114 psVector *restrict initialGuess; 115 const psVector *restrict coord; 108 116 const psVector *restrict paramMask; 109 117 float (*evalModel) (const psVector *, const psVector *); … … 113 121 114 122 /*****************************************************************************/ 123 115 124 /* GLOBAL VARIABLES */ 125 116 126 /*****************************************************************************/ 117 127 … … 119 129 120 130 /*****************************************************************************/ 131 121 132 /* FILE STATIC VARIABLES */ 133 122 134 /*****************************************************************************/ 123 135 … … 125 137 126 138 /*****************************************************************************/ 139 127 140 /* FUNCTION IMPLEMENTATION - LOCAL */ 141 128 142 /*****************************************************************************/ 129 143 … … 143 157 guess at the parameters, an option parameter mask, etc. 144 158 *****************************************************************************/ 145 double p_psMinFunc(const gsl_vector *params, 146 void *funcData) 147 { 148 int i; // Loop index variable. 149 int j; // Loop index variable. 150 float tmpf; // Temporary floating point variable. 151 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 152 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 153 psVector *restrict initialGuess = ((psMinimizeData *)funcData)->initialGuess; 154 float (*evalModel)(const psVector *, const psVector *) = 155 ((psMinimizeData *) funcData)->evalModel; 159 double p_psMinFunc(const gsl_vector * params, void *funcData) 160 { 161 int i; // Loop index variable. 162 int j; // Loop index variable. 163 float tmpf; // Temporary floating point variable. 164 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 165 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 166 psVector *restrict initialGuess = ((psMinimizeData *) funcData)->initialGuess; 167 float (*evalModel) (const psVector *, const psVector *) = ((psMinimizeData *) funcData)->evalModel; 156 168 psVector *inputParameterList = NULL; 157 169 … … 163 175 if (mask != NULL) { 164 176 j = 0; 165 for (i =0;i<mask->n;i++) {177 for (i = 0; i < mask->n; i++) { 166 178 if (mask->data.U8[i] != 0) { 167 179 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 171 183 } 172 184 } else { 173 for (i =0;i<initialGuess->n;i++) {185 for (i = 0; i < initialGuess->n; i++) { 174 186 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 175 187 } … … 181 193 // Free allocated memory and return the value of the function. 182 194 psFree(inputParameterList); 183 return (tmpf);195 return (tmpf); 184 196 } 185 197 … … 199 211 in "params" and return those derivatives in this psVector. 200 212 *****************************************************************************/ 201 void p_psMinFuncDeriv(const gsl_vector *params, 202 void *funcData, 203 gsl_vector *df) 204 { 205 int i; // Loop index variable. 206 int j; // Loop index variable. 207 float tmpf; // Temporary floating point variable. 208 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 209 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 210 psVector *restrict initialGuess = ((psMinimizeData *)funcData)->initialGuess; 211 float (*d_evalModel)(const psVector *, const psVector *, int) = 213 void p_psMinFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * df) 214 { 215 int i; // Loop index variable. 216 int j; // Loop index variable. 217 float tmpf; // Temporary floating point variable. 218 const psVector *restrict coord = ((psMinimizeData *) funcData)->coord; 219 const psVector *restrict mask = ((psMinimizeData *) funcData)->paramMask; 220 psVector *restrict initialGuess = ((psMinimizeData *) funcData)->initialGuess; 221 float (*d_evalModel) (const psVector *, const psVector *, int) = 212 222 ((psMinimizeData *) funcData)->d_evalModel; 213 223 psVector *inputParameterList = NULL; … … 220 230 if (mask != NULL) { 221 231 j = 0; 222 for (i =0;i<mask->n;i++) {232 for (i = 0; i < mask->n; i++) { 223 233 if (mask->data.U8[i] != 0) { 224 234 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 228 238 } 229 239 } else { 230 for (i =0;i<initialGuess->n;i++) {240 for (i = 0; i < initialGuess->n; i++) { 231 241 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 232 242 } … … 235 245 // Evaluate the derivative w.r.t. each parameter. 236 246 // NOTE: we can probably remove the calls for masked parameters. 237 for (i =0;i<initialGuess->n;i++) {247 for (i = 0; i < initialGuess->n; i++) { 238 248 tmpf = d_evalModel(inputParameterList, coord, i); 239 249 gsl_vector_set(df, i, tmpf); … … 247 257 Compute both p_psMinFunc and p_psMinFuncDeriv together. 248 258 *****************************************************************************/ 249 void p_psMinFuncFuncDeriv(const gsl_vector *params, 250 void *funcData, 251 double *f, 252 gsl_vector *df) 259 void p_psMinFuncFuncDeriv(const gsl_vector * params, void *funcData, double *f, gsl_vector * df) 253 260 { 254 261 *f = p_psMinFunc(params, funcData); … … 281 288 expected value and divide by the error. 282 289 *****************************************************************************/ 283 int p_psMinChi2Func(const gsl_vector *params, 284 void *funcData, 285 gsl_vector *outData) 286 { 287 int i; // Loop index variable. 288 int j; // Loop index variable. 289 float tmpf; // Temporary floating point variable. 290 const psImage *restrict domain = ((psMinChi2Data *)funcData)->domain; 291 const psVector *restrict data = ((psMinChi2Data *)funcData)->data; 292 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 293 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 294 psVector *restrict initialGuess = ((psMinChi2Data *)funcData)->initialGuess; 295 float (*evalModel)(const psVector *, const psVector *) = ((psMinChi2Data *) funcData)->evalModel; 290 int p_psMinChi2Func(const gsl_vector * params, void *funcData, gsl_vector * outData) 291 { 292 int i; // Loop index variable. 293 int j; // Loop index variable. 294 float tmpf; // Temporary floating point variable. 295 const psImage *restrict domain = ((psMinChi2Data *) funcData)->domain; 296 const psVector *restrict data = ((psMinChi2Data *) funcData)->data; 297 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 298 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 299 psVector *restrict initialGuess = ((psMinChi2Data *) funcData)->initialGuess; 300 float (*evalModel) (const psVector *, const psVector *) = ((psMinChi2Data *) funcData)->evalModel; 296 301 psVector *inputParameterList = NULL; 297 302 psVector *tmpVecPtr = NULL; … … 307 312 if (mask != NULL) { 308 313 j = 0; 309 for (i =0;i<mask->n;i++) {314 for (i = 0; i < mask->n; i++) { 310 315 if (mask->data.U8[i] != 0) { 311 316 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 315 320 } 316 321 } else { 317 for (i =0;i<initialGuess->n;i++) {322 for (i = 0; i < initialGuess->n; i++) { 318 323 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 319 324 } … … 321 326 322 327 // Evaluate the function at each data point. 323 for (i =0;i<domain->numRows;i++) {324 for (j =0;j<domain->numCols;j++) {328 for (i = 0; i < domain->numRows; i++) { 329 for (j = 0; j < domain->numCols; j++) { 325 330 tmpVecPtr->data.F32[j] = domain->data.F32[i][j]; 326 331 } 327 332 tmpf = evalModel(tmpVecPtr, inputParameterList); 328 333 329 gsl_vector_set(outData, i, (tmpf - data->data.F32[i])/ 330 errors->data.F32[i]); 334 gsl_vector_set(outData, i, (tmpf - data->data.F32[i]) / errors->data.F32[i]); 331 335 } 332 336 … … 354 358 and returned in this data structure. 355 359 *****************************************************************************/ 356 int p_psMinChi2FuncDeriv(const gsl_vector *params, 357 void *funcData, 358 gsl_matrix *J) 359 { 360 const psImage *restrict domain = ((psMinChi2Data *)funcData)->domain; 361 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 362 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 363 psVector *restrict initialGuess = ((psMinChi2Data *)funcData)->initialGuess; 360 int p_psMinChi2FuncDeriv(const gsl_vector * params, void *funcData, gsl_matrix * J) 361 { 362 const psImage *restrict domain = ((psMinChi2Data *) funcData)->domain; 363 const psVector *restrict errors = ((psMinChi2Data *) funcData)->errors; 364 const psVector *restrict mask = ((psMinChi2Data *) funcData)->paramMask; 365 psVector *restrict initialGuess = ((psMinChi2Data *) funcData)->initialGuess; 364 366 psVector *inputParameterList = NULL; 365 367 psVector *tmpVecPtr = NULL; 366 float (*d_evalModel)(const psVector *, const psVector *, int) = ((psMinChi2Data *) funcData)->d_evalModel; 368 float (*d_evalModel) (const psVector *, const psVector *, int) = 369 ((psMinChi2Data *) funcData)->d_evalModel; 367 370 368 371 size_t i; … … 380 383 if (mask != NULL) { 381 384 j = 0; 382 for (i =0;i<mask->n;i++) {385 for (i = 0; i < mask->n; i++) { 383 386 if (mask->data.U8[i] != 0) { 384 387 inputParameterList->data.F32[i] = initialGuess->data.F32[i]; … … 388 391 } 389 392 } else { 390 for (i =0;i<initialGuess->n;i++) {393 for (i = 0; i < initialGuess->n; i++) { 391 394 inputParameterList->data.F32[i] = gsl_vector_get(params, i); 392 395 } … … 394 397 395 398 // Evaluate the derivtaive at each data point, and w.r.t. each parameter. 396 for (i =0;i<domain->numRows;i++) {397 for (j =0;j<tmpVecPtr->n;j++) {399 for (i = 0; i < domain->numRows; i++) { 400 for (j = 0; j < tmpVecPtr->n; j++) { 398 401 tmpVecPtr->data.F32[j] = domain->data.F32[i][j]; 399 402 } 400 403 401 for (j =0;j<inputParameterList->n;j++) {404 for (j = 0; j < inputParameterList->n; j++) { 402 405 tmpf = d_evalModel(tmpVecPtr, inputParameterList, j); 403 gsl_matrix_set(J, i, j, (tmpf /errors->data.F32[i]));406 gsl_matrix_set(J, i, j, (tmpf / errors->data.F32[i])); 404 407 } 405 408 } … … 410 413 } 411 414 412 413 int p_psMinChi2FuncFuncDeriv(const gsl_vector *params, 414 void *funcData, 415 gsl_vector *f, 416 gsl_matrix *J) 415 int p_psMinChi2FuncFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * f, gsl_matrix * J) 417 416 { 418 417 p_psMinChi2Func(params, funcData, f); … … 421 420 return GSL_SUCCESS; 422 421 } 423 424 422 425 423 /****************************************************************************** … … 428 426 returned as a psVector sums. 429 427 *****************************************************************************/ 430 void p_psBuildSums1D(double x, 431 int polyOrder, 432 psVector *sums) 433 { 434 int i = 0; 435 double xSum = 0.0; 428 void p_psBuildSums1D(double x, int polyOrder, psVector * sums) 429 { 430 int i = 0; 431 double xSum = 0.0; 436 432 437 433 xSum = 1.0; 438 for (i=0;i<=polyOrder;i++) {434 for (i = 0; i <= polyOrder; i++) { 439 435 sums->data.F64[i] = xSum; 440 xSum*= x; 441 } 442 } 443 436 xSum *= x; 437 } 438 } 444 439 445 440 /****************************************************************************** … … 448 443 *****************************************************************************/ 449 444 psVector *psBuildImageScalingFactors(int x) 450 451 445 { 452 446 int i = 0; // loop index variable. 453 447 psVector *imageScalingFactors = NULL; 454 448 455 456 449 imageScalingFactors = psVectorAlloc(x, PS_TYPE_F32); 457 450 458 for (i =0;i<x;i++) {459 imageScalingFactors->data.F32[i] = (((float) 2*i) / ((float)x)) - 1.0;460 } 461 462 return (imageScalingFactors);451 for (i = 0; i < x; i++) { 452 imageScalingFactors->data.F32[i] = (((float)2 * i) / ((float)x)) - 1.0; 453 } 454 455 return (imageScalingFactors); 463 456 } 464 457 … … 481 474 *flag Set this to 1 if we must recalculate the coefficients. 482 475 *****************************************************************************/ 483 void p_psPolyOrderCheck(float **A, 484 int N, 485 int *indx, 486 float *B, 487 int polyOrder, 488 int *flag) 489 { 490 float **y = NULL; // This 2-D matrix will hold A^-1 491 float *col = NULL; // misc NumerRecipes data structure 492 float *error=NULL; // will hold the sqrt() of the 476 void p_psPolyOrderCheck(float **A, int N, int *indx, float *B, int polyOrder, int *flag) 477 { 478 float **y = NULL; // This 2-D matrix will hold A^-1 479 float *col = NULL; // misc NumerRecipes data structure 480 float *error = NULL; // will hold the sqrt() of the 481 493 482 // diagonal of y[][]. 494 int i=0; // loop-index variable 495 int j=0; // loop-index variable 496 int numPolyTerms = 0; // The number of terms in the 483 int i = 0; // loop-index variable 484 int j = 0; // loop-index variable 485 int numPolyTerms = 0; // The number of terms in the 486 497 487 // polynomial. 498 int lastTerm = 0; // The index location of the first 488 int lastTerm = 0; // The index location of the first 489 499 490 // n-th order term in array B[]. 500 int firstTerm = 0; // Index location of last such term.491 int firstTerm = 0; // Index location of last such term. 501 492 502 493 // Allocate the necessary data structures for this procedure... 503 error = (float *) psAlloc((N + 1) * sizeof(float));504 col = (float *) psAlloc((N + 1) * sizeof(float));505 y = (float **) psAlloc((N + 1) * sizeof(float *));506 for (i=1;i<=N;i++) {507 y[i] = (float *) psAlloc((N + 1) * sizeof(float));494 error = (float *)psAlloc((N + 1) * sizeof(float)); 495 col = (float *)psAlloc((N + 1) * sizeof(float)); 496 y = (float **)psAlloc((N + 1) * sizeof(float *)); 497 for (i = 1; i <= N; i++) { 498 y[i] = (float *)psAlloc((N + 1) * sizeof(float)); 508 499 } 509 500 510 501 // Invert the matrix A and put the result in y[][]. This code is taken 511 502 // from Numerical Recipes in C page 48. 512 for (j=1;j<=N;j++) {513 for (i=1;i<=N;i++) {503 for (j = 1; j <= N; j++) { 504 for (i = 1; i <= N; i++) { 514 505 col[i] = 0.0; 515 506 } 516 507 col[j] = 1.0; 517 508 // NOTE: substitue the LUD rotine 518 // lubksb(A, N, indx, col);519 for (i=1;i<=N;i++) {509 // lubksb(A, N, indx, col); 510 for (i = 1; i <= N; i++) { 520 511 y[i][j] = col[i]; 521 512 } … … 527 518 // terms and check if they are consistent with zero. 528 519 529 numPolyTerms = (((polyOrder +1) * (polyOrder + 2)) / 2);520 numPolyTerms = (((polyOrder + 1) * (polyOrder + 2)) / 2); 530 521 lastTerm = numPolyTerms + 1; 531 522 firstTerm = lastTerm - polyOrder; 532 523 *flag = 1; 533 for (i =firstTerm; i<=lastTerm; i++) {524 for (i = firstTerm; i <= lastTerm; i++) { 534 525 #ifdef DARWIN 535 526 error[i] = (float)sqrt(y[i][i]); … … 539 530 #endif 540 531 541 if (!((B[i] <= (2.0f * error[i])) && 542 ((-2.0f * error[i]) <= B[i]))) { 532 if (!((B[i] <= (2.0f * error[i])) && ((-2.0f * error[i]) <= B[i]))) { 543 533 *flag = 0; 544 534 } … … 548 538 psFree(error); 549 539 psFree(col); 550 for (j=1;j<=N;j++) {540 for (j = 1; j <= N; j++) { 551 541 psFree(y[j]); 552 542 } … … 554 544 } 555 545 556 557 558 559 /*****************************************************************************/ 546 /*****************************************************************************/ 547 560 548 /* FUNCTION IMPLEMENTATION - PUBLIC */ 561 /*****************************************************************************/ 562 563 549 550 /*****************************************************************************/ 564 551 565 552 /****************************************************************************** … … 569 556 parameters of that function such that the ... 570 557 *****************************************************************************/ 571 psVector * 572 psMinimize(psVector *restrict initialGuess, 573 float (*myFunction)(const psVector *restrict, const psVector *restrict), 574 float (*myFunctionDeriv)(const psVector *restrict, const psVector *restrict, int), 575 const psVector *restrict coord, 576 const psVector *restrict paramMask) 558 psVector *psMinimize(psVector * restrict initialGuess, 559 float (*myFunction) (const psVector * restrict, const psVector * restrict), 560 float (*myFunctionDeriv) (const psVector * restrict, const psVector * restrict, int), 561 const psVector * restrict coord, const psVector * restrict paramMask) 577 562 { 578 563 int status; … … 607 592 // for the parameters. 608 593 if (paramMask != NULL) { 609 for (i =0;i<paramMask->n;i++) {594 for (i = 0; i < paramMask->n; i++) { 610 595 if (paramMask->data.U8[i] != 0) { 611 596 inputData.paramCount++; … … 613 598 } 614 599 } else { 615 inputData.paramCount = initialGuess->n;600 inputData.paramCount = initialGuess->n; 616 601 } 617 602 … … 622 607 if (paramMask != NULL) { 623 608 j = 0; 624 for (i =0;i<initialGuess->n;i++) {609 for (i = 0; i < initialGuess->n; i++) { 625 610 if (paramMask->data.U8[i] == 0) { 626 611 gsl_vector_set(x, j++, initialGuess->data.F32[i]); … … 628 613 } 629 614 } else { 630 for (i =0;i<initialGuess->n;i++) {615 for (i = 0; i < initialGuess->n; i++) { 631 616 gsl_vector_set(x, i, initialGuess->data.F32[i]); 632 617 } … … 651 636 652 637 if (status == GSL_SUCCESS) 653 printf ("Minimum found at:\n");638 printf("Minimum found at:\n"); 654 639 655 640 } while (status == GSL_CONTINUE && iter < MAX_MINIMIZE_ITERATIONS); … … 660 645 if (paramMask != NULL) { 661 646 j = 0; 662 for (i =0;i<initialGuess->n;i++) {647 for (i = 0; i < initialGuess->n; i++) { 663 648 if (paramMask->data.U8[i] == 0) { 664 649 initialGuess->data.F32[i] = gsl_vector_get(s->x, j++); … … 668 653 } 669 654 } else { 670 for (i =0;i<initialGuess->n;i++) {655 for (i = 0; i < initialGuess->n; i++) { 671 656 initialGuess->data.F32[i] = gsl_vector_get(s->x, i); 672 657 } 673 658 } 674 return(initialGuess); 675 } 676 677 678 679 680 659 return (initialGuess); 660 } 681 661 682 662 /****************************************************************************** … … 684 664 such that they best fit the supplied data points. 685 665 *****************************************************************************/ 686 psVector * 687 psMinimizeChi2(float (*evalModel)(const psVector *restrict, const psVector *restrict), 688 float (*DevalModel)(const psVector *restrict, const psVector *restrict, int), 689 const psImage *restrict domain, 690 const psVector *restrict data, 691 const psVector *restrict errors, 692 psVector *restrict initialGuess, 693 const psVector *restrict paramMask, 694 float *chiSq) 695 { 696 int numData = domain->numRows; // Number of data points 697 int status; // Return status for the GSL solver. 698 int i = 0; // Loop index variable. 699 int j = 0; // Loop index variable. 700 int iter = 0; // Iteration counter. 701 gsl_multifit_function_fdf f; // GSL structure that contains the 666 psVector *psMinimizeChi2(float (*evalModel) (const psVector * restrict, const psVector * restrict), 667 float (*DevalModel) (const psVector * restrict, const psVector * restrict, int), 668 const psImage * restrict domain, 669 const psVector * restrict data, 670 const psVector * restrict errors, 671 psVector * restrict initialGuess, const psVector * restrict paramMask, float *chiSq) 672 { 673 int numData = domain->numRows; // Number of data points 674 int status; // Return status for the GSL solver. 675 int i = 0; // Loop index variable. 676 int j = 0; // Loop index variable. 677 int iter = 0; // Iteration counter. 678 gsl_multifit_function_fdf f; // GSL structure that contains the 679 702 680 // functions/derivative to be solved. 703 double *xInit = NULL; // The initial guess at the parameters 681 double *xInit = NULL; // The initial guess at the parameters 682 704 683 // with masked parameters removed. 705 684 const gsl_multifit_fdfsolver_type *T; 685 706 686 // This tells GSL to use the Levenberg- 707 687 // Marquardt algorithm for chi2 708 688 // minimization. 709 gsl_multifit_fdfsolver *s; // GSL data structure.689 gsl_multifit_fdfsolver *s; // GSL data structure. 710 690 psMinChi2Data inputData; 711 691 float chiSqOld = 0.0; … … 721 701 PS_CHECK_VECTOR_SIZE_EQUAL(data, errors); 722 702 if (domain->numRows != data->n) { 723 psAbort(__func__, "Number of data points and data values not equal.");703 psAbort(__func__, "Number of data points and data values not equal."); 724 704 } 725 705 if (paramMask != NULL) { … … 743 723 // for the parameters. 744 724 if (paramMask != NULL) { 745 for (i =0;i<paramMask->n;i++) {725 for (i = 0; i < paramMask->n; i++) { 746 726 if (paramMask->data.U8[i] != 0) { 747 727 inputData.paramCount++; … … 749 729 } 750 730 } else { 751 inputData.paramCount = initialGuess->n;731 inputData.paramCount = initialGuess->n; 752 732 } 753 733 … … 755 735 // the vector inputParameterList. If the paramMask is not NULL, then those 756 736 // parameters are masked out. 757 xInit = (double *) psAlloc(inputData.paramCount * sizeof(double));737 xInit = (double *)psAlloc(inputData.paramCount * sizeof(double)); 758 738 if (paramMask != NULL) { 759 739 j = 0; 760 for (i =0;i<initialGuess->n;i++) {740 for (i = 0; i < initialGuess->n; i++) { 761 741 if (paramMask->data.U8[i] == 0) { 762 742 xInit[j++] = initialGuess->data.F32[i]; … … 764 744 } 765 745 } else { 766 for (i =0;i<initialGuess->n;i++) {746 for (i = 0; i < initialGuess->n; i++) { 767 747 xInit[i] = initialGuess->data.F32[i]; 768 748 } … … 771 751 const gsl_rng_type *type; 772 752 gsl_rng *r; 753 773 754 gsl_rng_env_setup(); 774 755 … … 789 770 790 771 gsl_vector_view x = gsl_vector_view_array(xInit, inputData.paramCount); 772 791 773 T = gsl_multifit_fdfsolver_lmsder; 792 774 s = gsl_multifit_fdfsolver_alloc(T, numData, inputData.paramCount); … … 796 778 do { 797 779 iter++; 798 for (i =0;i<initialGuess->n;i++) {780 for (i = 0; i < initialGuess->n; i++) { 799 781 printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i)); 800 782 } … … 802 784 status = gsl_multifit_fdfsolver_iterate(s); 803 785 printf("gsl_multifit_fdfsolver_iterate() status is %s\n", gsl_strerror(status)); 804 for (i =0;i<initialGuess->n;i++) {786 for (i = 0; i < initialGuess->n; i++) { 805 787 printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i)); 806 788 } … … 810 792 psAbort(__func__, "gsl_multifit_fdfsolver_iterate(%s)\n", gsl_strerror(status)); 811 793 } 812 813 794 // Test if the parameters changed by a small enough amount. 814 795 // NOTE: This wasn't working right when the parameters fit exactly. 815 796 // Figure out why. 816 // status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4);797 // status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4); 817 798 818 799 // We test for convergence if chiSquared changes by less than 1.0 … … 829 810 } while (status == GSL_CONTINUE && iter < MAX_LMM_ITERATIONS); 830 811 831 832 812 // In the above steps we had removed the masked elements from the 833 813 // the solver. This next code blocks puts those masked elements … … 835 815 if (paramMask != NULL) { 836 816 j = 0; 837 for (i =0;i<initialGuess->n;i++) {817 for (i = 0; i < initialGuess->n; i++) { 838 818 if (paramMask->data.U8[i] == 0) { 839 819 initialGuess->data.F32[i] = gsl_vector_get(s->x, j++); … … 843 823 } 844 824 } else { 845 for (i =0;i<initialGuess->n;i++) {825 for (i = 0; i < initialGuess->n; i++) { 846 826 initialGuess->data.F32[i] = gsl_vector_get(s->x, i); 847 827 } … … 857 837 858 838 // Bye bye. 859 return(initialGuess); 860 } 861 839 return (initialGuess); 840 } 862 841 863 842 /****************************************************************************** … … 868 847 NOTE: yErr is currently ignored. 869 848 *****************************************************************************/ 870 psPolynomial1D * 871 psVectorFitPolynomial1D(psPolynomial1D *myPoly, 872 const psVector *restrict x, 873 const psVector *restrict y, 874 const psVector *restrict yErr) 849 psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly, 850 const psVector * restrict x, 851 const psVector * restrict y, const psVector * restrict yErr) 875 852 { 876 853 int polyOrder = myPoly->n; … … 879 856 psVector *B = NULL; 880 857 psVector *outPerm = NULL; 881 psVector *X = NULL; // NOTE: do we need this?858 psVector *X = NULL; // NOTE: do we need this? 882 859 psVector *coeffs = NULL; 883 860 int i = 0; … … 886 863 psVector *xSums = NULL; 887 864 888 // printf("psVectorFitPolynomial1D()\n");889 // for (i=0;i<x->n;i++) {890 // printf("(x, y, yErr) is (%f, %f, %f)\n", x->data.F64[i], y->data.F64[i], yErr->data.F64[i]);891 // }865 // printf("psVectorFitPolynomial1D()\n"); 866 // for (i=0;i<x->n;i++) { 867 // printf("(x, y, yErr) is (%f, %f, %f)\n", x->data.F64[i], y->data.F64[i], yErr->data.F64[i]); 868 // } 892 869 893 870 PS_CHECK_NULL_1DPOLY(myPoly); … … 901 878 PS_CHECK_VECTOR_SIZE_EQUAL(y, yErr); 902 879 903 A = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64);904 ALUD = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64);905 B = psVectorAlloc(polyOrder, PS_TYPE_F64);906 coeffs = psVectorAlloc(polyOrder, PS_TYPE_F64);907 X = psVectorAlloc(x->n, PS_TYPE_F64);880 A = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64); 881 ALUD = psImageAlloc(polyOrder, polyOrder, PS_TYPE_F64); 882 B = psVectorAlloc(polyOrder, PS_TYPE_F64); 883 coeffs = psVectorAlloc(polyOrder, PS_TYPE_F64); 884 X = psVectorAlloc(x->n, PS_TYPE_F64); 908 885 outPerm = psVectorAlloc(polyOrder, PS_TYPE_F64); 909 xSums = psVectorAlloc(1+2*polyOrder, PS_TYPE_F64);886 xSums = psVectorAlloc(1 + 2 * polyOrder, PS_TYPE_F64); 910 887 911 888 // Initialize data structures. 912 for (i=0;i<(polyOrder);i++) {889 for (i = 0; i < (polyOrder); i++) { 913 890 B->data.F64[i] = 0.0; 914 891 coeffs->data.F64[i] = 0.0; 915 892 outPerm->data.F64[i] = 0.0; 916 for (j=0;j<(polyOrder);j++) {893 for (j = 0; j < (polyOrder); j++) { 917 894 A->data.F64[i][j] = 0.0; 918 895 ALUD->data.F64[i][j] = 0.0; 919 896 } 920 897 } 921 for (i =0;i<X->n;i++) {898 for (i = 0; i < X->n; i++) { 922 899 X->data.F64[i] = x->data.F64[i]; 923 900 } 924 901 925 902 // Build the B and A data structs. 926 for (i =0;i<X->n;i++) {927 p_psBuildSums1D(X->data.F64[i], 2 *polyOrder, xSums);928 929 for (k=0;k<(polyOrder);k++) {930 B->data.F64[k] += y->data.F64[i] * xSums->data.F64[k];931 } 932 933 for (k=0;k<(polyOrder);k++) {934 for (j=0;j<(polyOrder);j++) {935 A->data.F64[k][j] += xSums->data.F64[k+j];903 for (i = 0; i < X->n; i++) { 904 p_psBuildSums1D(X->data.F64[i], 2 * polyOrder, xSums); 905 906 for (k = 0; k < (polyOrder); k++) { 907 B->data.F64[k] += y->data.F64[i] * xSums->data.F64[k]; 908 } 909 910 for (k = 0; k < (polyOrder); k++) { 911 for (j = 0; j < (polyOrder); j++) { 912 A->data.F64[k][j] += xSums->data.F64[k + j]; 936 913 } 937 914 } … … 941 918 coeffs = psMatrixLUSolve(coeffs, ALUD, B, outPerm); 942 919 943 for (k=0;k<(polyOrder);k++) {920 for (k = 0; k < (polyOrder); k++) { 944 921 myPoly->coeff[k] = coeffs->data.F64[k]; 945 // printf("myPoly->coeff[%d] is %f\n", k, myPoly->coeff[k]);946 } 947 948 949 // for (i=0;i<x->n;i++) {950 // printf("HMMM: psEvalPolynomial1D(%f) is %f\n", x->data.F64[i], psEvalPolynomial1D(x->data.F64[i],myPoly));951 // }922 // printf("myPoly->coeff[%d] is %f\n", k, myPoly->coeff[k]); 923 } 924 925 // for (i=0;i<x->n;i++) { 926 // printf("HMMM: psEvalPolynomial1D(%f) is %f\n", x->data.F64[i], psEvalPolynomial1D(x->data.F64[i], 927 // myPoly)); 928 // } 952 929 953 930 psFree(A); … … 959 936 psFree(xSums); 960 937 961 return (myPoly);962 } 938 return (myPoly); 939 } -
trunk/psLib/src/math/psMinimize.h
r1406 r1407 1 1 #if !defined(PS_MINIMIZE_H) 2 # define PS_MINIMIZE_H2 # define PS_MINIMIZE_H 3 3 4 #include "psFunctions.h" 4 # include "psFunctions.h" 5 5 6 /** \file psMinimize.h 6 7 * \brief minimization operations … … 9 10 10 11 /** Functions **************************************************************/ 12 11 13 /** \addtogroup Stats 12 14 * \{ … … 14 16 15 17 /** This routine must minimize a non-linear function */ 16 psVector * 17 psMinimize(psVector *restrict initialGuess, 18 float (*myFunction)(const psVector *restrict, const psVector *restrict), 19 float (*myFunctionDeriv)(const psVector *restrict, const psVector *restrict, int), 20 const psVector *restrict coord, 21 const psVector *restrict paramMask); 22 18 psVector *psMinimize(psVector * restrict initialGuess, 19 float (*myFunction) (const psVector * restrict, const psVector * restrict), 20 float (*myFunctionDeriv) (const psVector * restrict, const psVector * restrict, int), 21 const psVector * restrict coord, const psVector * restrict paramMask); 23 22 24 23 /** Minimize chi^2 for input data */ 25 psVector * 26 psMinimizeChi2(float (*evalModel)(const psVector *restrict, 27 const psVector *restrict), ///< Model to fit; (domain and params) 28 float (*DevalModel)(const psVector *restrict, 29 const psVector *restrict, 30 int), ///< Derivative of model to fit; (domain and params) 31 const psImage *restrict domain, ///< The domain values for the corresponding measurements 32 const psVector *restrict data, ///< Data to fit 33 const psVector *restrict errors, ///< Errors in the data 34 psVector *restrict initialGuess, ///< Initial guess 35 const psVector *restrict paramMask, ///< 1 = fit for parameter, 0 = hold parameter constant 36 float *chiSq 37 ); 24 psVector *psMinimizeChi2(float (*evalModel) (const psVector * restrict, const psVector * restrict), // /< 25 // Model 26 // to 27 // fit; 28 // (domain 29 // and 30 // params) 31 float (*DevalModel) (const psVector * restrict, const psVector * restrict, int), // /< 32 // Derivative 33 // of 34 // model 35 // to 36 // fit; 37 // (domain 38 // and 39 // params) 40 const psImage * restrict domain, // /< The domain values for the corresponding 41 // measurements 42 const psVector * restrict data, // /< Data to fit 43 const psVector * restrict errors, // /< Errors in the data 44 psVector * restrict initialGuess, // /< Initial guess 45 const psVector * restrict paramMask, // /< 1 = fit for parameter, 0 = hold 46 // parameter constant 47 float *chiSq); 38 48 39 49 /** Derive a polynomial fit by chi^2 minimisation (analytically) */ 40 psPolynomial1D * 41 psVectorFitPolynomial1D(psPolynomial1D *myPoly, ///< Polynomial to fit 42 const psVector *restrict x, ///< Ordinates (or NULL to just usethe indices)43 const psVector *restrict y, ///< Coordinates44 const psVector *restrict yErr ///< Errors in coordinates, or NULL45 );50 psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly, // /< Polynomial to fit 51 const psVector * restrict x, // /< Ordinates (or NULL to just use 52 // the indices) 53 const psVector * restrict y, // /< Coordinates 54 const psVector * restrict yErr // /< Errors in coordinates, or NULL 55 ); 46 56 47 /* \} */ // End of MathGroup Functions57 /* \} */// End of MathGroup Functions 48 58 49 59 #endif -
trunk/psLib/src/math/psPolynomial.c
r1406 r1407 1 1 2 /** @file psFunctions.c 2 3 * … … 7 8 * polynomials. It also contains a Gaussian functions. 8 9 * 9 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 13 14 */ 14 /*****************************************************************************/ 15 16 /*****************************************************************************/ 17 15 18 /* INCLUDE FILES */ 19 16 20 /*****************************************************************************/ 17 21 #include <stdlib.h> … … 31 35 #include <gsl/gsl_rng.h> 32 36 #include <gsl/gsl_randist.h> 33 /*****************************************************************************/ 37 38 /*****************************************************************************/ 39 34 40 /* DEFINE STATEMENTS */ 41 35 42 /*****************************************************************************/ 36 43 … … 38 45 39 46 /*****************************************************************************/ 47 40 48 /* TYPE DEFINITIONS */ 41 /*****************************************************************************/ 42 static void polynomial1DFree(psPolynomial1D *myPoly); 43 static void polynomial2DFree(psPolynomial2D *myPoly); 44 static void polynomial3DFree(psPolynomial3D *myPoly); 45 static void polynomial4DFree(psPolynomial4D *myPoly); 46 static void dPolynomial1DFree(psDPolynomial1D *myPoly); 47 static void dPolynomial2DFree(psDPolynomial2D *myPoly); 48 static void dPolynomial3DFree(psDPolynomial3D *myPoly); 49 static void dPolynomial4DFree(psDPolynomial4D *myPoly); 50 51 /*****************************************************************************/ 49 50 /*****************************************************************************/ 51 static void polynomial1DFree(psPolynomial1D * myPoly); 52 static void polynomial2DFree(psPolynomial2D * myPoly); 53 static void polynomial3DFree(psPolynomial3D * myPoly); 54 static void polynomial4DFree(psPolynomial4D * myPoly); 55 static void dPolynomial1DFree(psDPolynomial1D * myPoly); 56 static void dPolynomial2DFree(psDPolynomial2D * myPoly); 57 static void dPolynomial3DFree(psDPolynomial3D * myPoly); 58 static void dPolynomial4DFree(psDPolynomial4D * myPoly); 59 60 /*****************************************************************************/ 61 52 62 /* GLOBAL VARIABLES */ 63 53 64 /*****************************************************************************/ 54 65 … … 56 67 57 68 /*****************************************************************************/ 69 58 70 /* FILE STATIC VARIABLES */ 71 59 72 /*****************************************************************************/ 60 73 … … 62 75 63 76 /*****************************************************************************/ 77 64 78 /* FUNCTION IMPLEMENTATION - LOCAL */ 79 65 80 /*****************************************************************************/ 66 81 … … 68 83 69 84 /*****************************************************************************/ 85 70 86 /* FUNCTION IMPLEMENTATION - PUBLIC */ 87 71 88 /*****************************************************************************/ 72 89 … … 76 93 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] 77 94 *****************************************************************************/ 78 float 79 psGaussian(float x, 80 float mean, 81 float sigma, 82 bool normal) 95 float psGaussian(float x, float mean, float sigma, bool normal) 83 96 { 84 97 float tmp = 1.0; … … 94 107 } 95 108 96 return (tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));109 return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma))); 97 110 } 98 111 … … 107 120 NOTE: There is no way to seed the random generator. 108 121 *****************************************************************************/ 109 psVector *psGaussianDev(float mean, 110 float sigma, 111 int Npts) 122 psVector *psGaussianDev(float mean, float sigma, int Npts) 112 123 { 113 124 psVector *gauss = NULL; … … 127 138 128 139 // NOTE: Should I free r as well? 129 return(gauss); 130 } 131 140 return (gauss); 141 } 132 142 133 143 /***************************************************************************** … … 140 150 141 151 newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D)); 142 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial1DFree);152 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree); 143 153 newPoly->n = n; 144 newPoly->coeff = (float *)psAlloc(n * sizeof(float));145 newPoly->coeffErr = (float *) psAlloc(n * sizeof(float));146 newPoly->mask = (char *)psAlloc(n * sizeof(char));147 for (i =0;i<n;i++) {154 newPoly->coeff = (float *)psAlloc(n * sizeof(float)); 155 newPoly->coeffErr = (float *)psAlloc(n * sizeof(float)); 156 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 157 for (i = 0; i < n; i++) { 148 158 newPoly->coeff[i] = 0.0; 149 159 newPoly->coeffErr[i] = 0.0; … … 151 161 } 152 162 153 return (newPoly);163 return (newPoly); 154 164 } 155 165 … … 161 171 162 172 newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D)); 163 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial2DFree);173 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree); 164 174 newPoly->nX = nX; 165 175 newPoly->nY = nY; 166 176 167 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *));168 newPoly->coeffErr = (float **) psAlloc(nX * sizeof(float *));169 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));170 for (x =0;x<nX;x++) {171 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float));172 newPoly->coeffErr[x] = (float *) psAlloc(nY * sizeof(float));173 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));174 } 175 for (x =0;x<nX;x++) {176 for (y =0;y<nY;y++) {177 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *)); 178 newPoly->coeffErr = (float **)psAlloc(nX * sizeof(float *)); 179 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 180 for (x = 0; x < nX; x++) { 181 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float)); 182 newPoly->coeffErr[x] = (float *)psAlloc(nY * sizeof(float)); 183 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 184 } 185 for (x = 0; x < nX; x++) { 186 for (y = 0; y < nY; y++) { 177 187 newPoly->coeff[x][y] = 0.0; 178 188 newPoly->coeffErr[x][y] = 0.0; … … 181 191 } 182 192 183 return (newPoly);193 return (newPoly); 184 194 } 185 195 … … 192 202 193 203 newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D)); 194 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial3DFree);204 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree); 195 205 newPoly->nX = nX; 196 206 newPoly->nY = nY; 197 207 newPoly->nZ = nZ; 198 208 199 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **));200 newPoly->coeffErr = (float ***) psAlloc(nX * sizeof(float **));201 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));202 for (x =0;x<nX;x++) {203 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *));204 newPoly->coeffErr[x] = (float **) psAlloc(nY * sizeof(float *));205 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));206 for (y =0;y<nY;y++) {207 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float));208 newPoly->coeffErr[x][y] = (float *) psAlloc(nZ * sizeof(float));209 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));210 } 211 } 212 for (x =0;x<nX;x++) {213 for (y =0;y<nY;y++) {214 for (z =0;z<nZ;z++) {209 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **)); 210 newPoly->coeffErr = (float ***)psAlloc(nX * sizeof(float **)); 211 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 212 for (x = 0; x < nX; x++) { 213 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *)); 214 newPoly->coeffErr[x] = (float **)psAlloc(nY * sizeof(float *)); 215 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 216 for (y = 0; y < nY; y++) { 217 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float)); 218 newPoly->coeffErr[x][y] = (float *)psAlloc(nZ * sizeof(float)); 219 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 220 } 221 } 222 for (x = 0; x < nX; x++) { 223 for (y = 0; y < nY; y++) { 224 for (z = 0; z < nZ; z++) { 215 225 newPoly->coeff[x][y][z] = 0.0; 216 226 newPoly->coeffErr[x][y][z] = 0.0; … … 220 230 } 221 231 222 return (newPoly);232 return (newPoly); 223 233 } 224 234 … … 232 242 233 243 newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D)); 234 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial4DFree);244 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree); 235 245 newPoly->nW = nW; 236 246 newPoly->nX = nX; … … 238 248 newPoly->nZ = nZ; 239 249 240 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***));241 newPoly->coeffErr = (float ****) psAlloc(nW * sizeof(float ***));242 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));243 for (w =0;w<nW;w++) {244 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **));245 newPoly->coeffErr[w] = (float ***) psAlloc(nX * sizeof(float **));246 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));247 for (x =0;x<nX;x++) {248 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *));249 newPoly->coeffErr[w][x] = (float **) psAlloc(nY * sizeof(float *));250 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));251 for (y =0;y<nY;y++) {252 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float));253 newPoly->coeffErr[w][x][y] = (float *) psAlloc(nZ * sizeof(float));254 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));255 } 256 } 257 } 258 for (w =0;w<nW;w++) {259 for (x =0;x<nX;x++) {260 for (y =0;y<nY;y++) {261 for (z =0;z<nZ;z++) {250 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***)); 251 newPoly->coeffErr = (float ****)psAlloc(nW * sizeof(float ***)); 252 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 253 for (w = 0; w < nW; w++) { 254 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **)); 255 newPoly->coeffErr[w] = (float ***)psAlloc(nX * sizeof(float **)); 256 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 257 for (x = 0; x < nX; x++) { 258 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *)); 259 newPoly->coeffErr[w][x] = (float **)psAlloc(nY * sizeof(float *)); 260 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 261 for (y = 0; y < nY; y++) { 262 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 263 newPoly->coeffErr[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 264 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 265 } 266 } 267 } 268 for (w = 0; w < nW; w++) { 269 for (x = 0; x < nX; x++) { 270 for (y = 0; y < nY; y++) { 271 for (z = 0; z < nZ; z++) { 262 272 newPoly->coeff[w][x][y][z] = 0.0; 263 273 newPoly->coeffErr[w][x][y][z] = 0.0; … … 268 278 } 269 279 270 return (newPoly);271 } 272 273 static void polynomial1DFree(psPolynomial1D * myPoly)280 return (newPoly); 281 } 282 283 static void polynomial1DFree(psPolynomial1D * myPoly) 274 284 { 275 285 psFree(myPoly->coeff); … … 278 288 } 279 289 280 static void polynomial2DFree(psPolynomial2D * myPoly)281 { 282 int x = 0; 283 284 for (x =0;x<myPoly->nX;x++) {290 static void polynomial2DFree(psPolynomial2D * myPoly) 291 { 292 int x = 0; 293 294 for (x = 0; x < myPoly->nX; x++) { 285 295 psFree(myPoly->coeff[x]); 286 296 psFree(myPoly->coeffErr[x]); … … 292 302 } 293 303 294 static void polynomial3DFree(psPolynomial3D * myPoly)295 { 296 int x = 0; 297 int y = 0; 298 299 for (x =0;x<myPoly->nX;x++) {300 for (y =0;y<myPoly->nY;y++) {304 static void polynomial3DFree(psPolynomial3D * myPoly) 305 { 306 int x = 0; 307 int y = 0; 308 309 for (x = 0; x < myPoly->nX; x++) { 310 for (y = 0; y < myPoly->nY; y++) { 301 311 psFree(myPoly->coeff[x][y]); 302 312 psFree(myPoly->coeffErr[x][y]); … … 313 323 } 314 324 315 static void polynomial4DFree(psPolynomial4D * myPoly)325 static void polynomial4DFree(psPolynomial4D * myPoly) 316 326 { 317 327 int w = 0; … … 319 329 int y = 0; 320 330 321 for (w =0;w<myPoly->nW;w++) {322 for (x =0;x<myPoly->nX;x++) {323 for (y =0;y<myPoly->nY;y++) {331 for (w = 0; w < myPoly->nW; w++) { 332 for (x = 0; x < myPoly->nX; x++) { 333 for (y = 0; y < myPoly->nY; y++) { 324 334 psFree(myPoly->coeff[w][x][y]); 325 335 psFree(myPoly->coeffErr[w][x][y]); … … 343 353 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 344 354 *****************************************************************************/ 345 float 346 psPolynomial1DEval(float x, 347 const psPolynomial1D *myPoly) 355 float psPolynomial1DEval(float x, const psPolynomial1D * myPoly) 348 356 { 349 357 int loop_x = 0; … … 355 363 } 356 364 357 358 365 // NOTE: Do we want to flag this case? 359 366 if (myPoly->n == 0) { 360 return (1.0);367 return (1.0); 361 368 } 362 369 … … 365 372 } 366 373 367 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 368 polySum+= xSum * myPoly->coeff[loop_x]; 369 xSum*=x; 370 } 371 372 return(polySum); 373 } 374 375 376 float 377 psPolynomial2DEval(float x, 378 float y, 379 const psPolynomial2D *myPoly) 374 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 375 polySum += xSum * myPoly->coeff[loop_x]; 376 xSum *= x; 377 } 378 379 return (polySum); 380 } 381 382 float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly) 380 383 { 381 384 int loop_x = 0; … … 385 388 float ySum = 1.0; 386 389 387 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {390 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 388 391 ySum = xSum; 389 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 390 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 391 ySum*=y; 392 } 393 xSum*=x; 394 } 395 396 return(polySum); 397 } 398 399 float 400 psPolynomial3DEval(float x, 401 float y, 402 float z, 403 const psPolynomial3D *myPoly) 392 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 393 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 394 ySum *= y; 395 } 396 xSum *= x; 397 } 398 399 return (polySum); 400 } 401 402 float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly) 404 403 { 405 404 int loop_x = 0; … … 411 410 float zSum = 1.0; 412 411 413 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {412 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 414 413 ySum = xSum; 415 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {414 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 416 415 zSum = ySum; 417 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 418 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 419 zSum*=z; 420 } 421 ySum*=y; 422 } 423 xSum*=x; 424 } 425 426 return(polySum); 427 } 428 429 float 430 psPolynomial4DEval(float w, 431 float x, 432 float y, 433 float z, 434 const psPolynomial4D *myPoly) 416 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 417 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 418 zSum *= z; 419 } 420 ySum *= y; 421 } 422 xSum *= x; 423 } 424 425 return (polySum); 426 } 427 428 float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly) 435 429 { 436 430 int loop_w = 0; … … 444 438 float zSum = 1.0; 445 439 446 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {440 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 447 441 xSum = wSum; 448 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {442 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 449 443 ySum = xSum; 450 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {444 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 451 445 zSum = ySum; 452 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 453 polySum+= zSum * 454 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 455 zSum*=z; 446 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 447 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 448 zSum *= z; 456 449 } 457 ySum*=y; 458 } 459 xSum*=x; 460 } 461 wSum*=w; 462 } 463 464 return(polySum); 465 } 466 467 468 450 ySum *= y; 451 } 452 xSum *= x; 453 } 454 wSum *= w; 455 } 456 457 return (polySum); 458 } 469 459 470 460 psDPolynomial1D *psDPolynomial1DAlloc(int n) … … 474 464 475 465 newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D)); 476 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial1DFree);466 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree); 477 467 newPoly->n = n; 478 newPoly->coeff = (double *)psAlloc(n * sizeof(double));479 newPoly->coeffErr = (double *) psAlloc(n * sizeof(double));480 newPoly->mask = (char *)psAlloc(n * sizeof(char));481 for (i =0;i<n;i++) {468 newPoly->coeff = (double *)psAlloc(n * sizeof(double)); 469 newPoly->coeffErr = (double *)psAlloc(n * sizeof(double)); 470 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 471 for (i = 0; i < n; i++) { 482 472 newPoly->coeff[i] = 0.0; 483 473 newPoly->coeffErr[i] = 0.0; … … 485 475 } 486 476 487 return (newPoly);477 return (newPoly); 488 478 } 489 479 … … 495 485 496 486 newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D)); 497 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial2DFree);487 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree); 498 488 newPoly->nX = nX; 499 489 newPoly->nY = nY; 500 490 501 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *));502 newPoly->coeffErr = (double **) psAlloc(nX * sizeof(double *));503 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));504 for (x =0;x<nX;x++) {505 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double));506 newPoly->coeffErr[x] = (double *) psAlloc(nY * sizeof(double));507 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));508 } 509 for (x =0;x<nX;x++) {510 for (y =0;y<nY;y++) {491 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *)); 492 newPoly->coeffErr = (double **)psAlloc(nX * sizeof(double *)); 493 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 494 for (x = 0; x < nX; x++) { 495 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double)); 496 newPoly->coeffErr[x] = (double *)psAlloc(nY * sizeof(double)); 497 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 498 } 499 for (x = 0; x < nX; x++) { 500 for (y = 0; y < nY; y++) { 511 501 newPoly->coeff[x][y] = 0.0; 512 502 newPoly->coeffErr[x][y] = 0.0; … … 515 505 } 516 506 517 return (newPoly);507 return (newPoly); 518 508 } 519 509 … … 526 516 527 517 newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D)); 528 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial3DFree);518 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree); 529 519 newPoly->nX = nX; 530 520 newPoly->nY = nY; 531 521 newPoly->nZ = nZ; 532 522 533 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **));534 newPoly->coeffErr = (double ***) psAlloc(nX * sizeof(double **));535 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));536 for (x =0;x<nX;x++) {537 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *));538 newPoly->coeffErr[x] = (double **) psAlloc(nY * sizeof(double *));539 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));540 for (y =0;y<nY;y++) {541 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double));542 newPoly->coeffErr[x][y] = (double *) psAlloc(nZ * sizeof(double));543 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));544 } 545 } 546 for (x =0;x<nX;x++) {547 for (y =0;y<nY;y++) {548 for (z =0;z<nZ;z++) {523 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **)); 524 newPoly->coeffErr = (double ***)psAlloc(nX * sizeof(double **)); 525 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 526 for (x = 0; x < nX; x++) { 527 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *)); 528 newPoly->coeffErr[x] = (double **)psAlloc(nY * sizeof(double *)); 529 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 530 for (y = 0; y < nY; y++) { 531 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double)); 532 newPoly->coeffErr[x][y] = (double *)psAlloc(nZ * sizeof(double)); 533 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 534 } 535 } 536 for (x = 0; x < nX; x++) { 537 for (y = 0; y < nY; y++) { 538 for (z = 0; z < nZ; z++) { 549 539 newPoly->coeff[x][y][z] = 0.0; 550 540 newPoly->coeffErr[x][y][z] = 0.0; … … 554 544 } 555 545 556 return (newPoly);546 return (newPoly); 557 547 } 558 548 … … 566 556 567 557 newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D)); 568 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial4DFree);558 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree); 569 559 newPoly->nW = nW; 570 560 newPoly->nX = nX; … … 572 562 newPoly->nZ = nZ; 573 563 574 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***));575 newPoly->coeffErr = (double ****) psAlloc(nW * sizeof(double ***));576 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));577 for (w =0;w<nW;w++) {578 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **));579 newPoly->coeffErr[w] = (double ***) psAlloc(nX * sizeof(double **));580 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));581 for (x =0;x<nX;x++) {582 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *));583 newPoly->coeffErr[w][x] = (double **) psAlloc(nY * sizeof(double *));584 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));585 for (y =0;y<nY;y++) {586 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double));587 newPoly->coeffErr[w][x][y] = (double *) psAlloc(nZ * sizeof(double));588 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));589 } 590 } 591 } 592 for (w =0;w<nW;w++) {593 for (x =0;x<nX;x++) {594 for (y =0;y<nY;y++) {595 for (z =0;z<nZ;z++) {564 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***)); 565 newPoly->coeffErr = (double ****)psAlloc(nW * sizeof(double ***)); 566 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 567 for (w = 0; w < nW; w++) { 568 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **)); 569 newPoly->coeffErr[w] = (double ***)psAlloc(nX * sizeof(double **)); 570 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 571 for (x = 0; x < nX; x++) { 572 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *)); 573 newPoly->coeffErr[w][x] = (double **)psAlloc(nY * sizeof(double *)); 574 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 575 for (y = 0; y < nY; y++) { 576 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 577 newPoly->coeffErr[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 578 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 579 } 580 } 581 } 582 for (w = 0; w < nW; w++) { 583 for (x = 0; x < nX; x++) { 584 for (y = 0; y < nY; y++) { 585 for (z = 0; z < nZ; z++) { 596 586 newPoly->coeff[w][x][y][z] = 0.0; 597 587 newPoly->coeffErr[w][x][y][z] = 0.0; … … 602 592 } 603 593 604 return (newPoly);605 } 606 607 static void dPolynomial1DFree(psDPolynomial1D * myPoly)594 return (newPoly); 595 } 596 597 static void dPolynomial1DFree(psDPolynomial1D * myPoly) 608 598 { 609 599 psFree(myPoly->coeff); … … 612 602 } 613 603 614 static void dPolynomial2DFree(psDPolynomial2D * myPoly)615 { 616 int x = 0; 617 618 for (x =0;x<myPoly->nX;x++) {604 static void dPolynomial2DFree(psDPolynomial2D * myPoly) 605 { 606 int x = 0; 607 608 for (x = 0; x < myPoly->nX; x++) { 619 609 psFree(myPoly->coeff[x]); 620 610 psFree(myPoly->coeffErr[x]); … … 626 616 } 627 617 628 static void dPolynomial3DFree(psDPolynomial3D * myPoly)629 { 630 int x = 0; 631 int y = 0; 632 633 for (x =0;x<myPoly->nX;x++) {634 for (y =0;y<myPoly->nY;y++) {618 static void dPolynomial3DFree(psDPolynomial3D * myPoly) 619 { 620 int x = 0; 621 int y = 0; 622 623 for (x = 0; x < myPoly->nX; x++) { 624 for (y = 0; y < myPoly->nY; y++) { 635 625 psFree(myPoly->coeff[x][y]); 636 626 psFree(myPoly->coeffErr[x][y]); … … 647 637 } 648 638 649 static void dPolynomial4DFree(psDPolynomial4D * myPoly)639 static void dPolynomial4DFree(psDPolynomial4D * myPoly) 650 640 { 651 641 int w = 0; … … 653 643 int y = 0; 654 644 655 for (w =0;w<myPoly->nW;w++) {656 for (x =0;x<myPoly->nX;x++) {657 for (y =0;y<myPoly->nY;y++) {645 for (w = 0; w < myPoly->nW; w++) { 646 for (x = 0; x < myPoly->nX; x++) { 647 for (y = 0; y < myPoly->nY; y++) { 658 648 psFree(myPoly->coeff[w][x][y]); 659 649 psFree(myPoly->coeffErr[w][x][y]); … … 677 667 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 678 668 *****************************************************************************/ 679 double 680 psDPolynomial1DEval(double x, 681 const psDPolynomial1D *myPoly) 669 double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly) 682 670 { 683 671 int loop_x = 0; … … 687 675 // NOTE: Do we want to flag this case? 688 676 if (myPoly->n == 0) { 689 return(1.0); 690 } 691 692 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 693 polySum+= xSum * myPoly->coeff[loop_x]; 694 xSum*=x; 695 } 696 697 return(polySum); 698 } 699 700 701 double 702 psDPolynomial2DEval(double x, 703 double y, 704 const psDPolynomial2D *myPoly) 677 return (1.0); 678 } 679 680 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 681 polySum += xSum * myPoly->coeff[loop_x]; 682 xSum *= x; 683 } 684 685 return (polySum); 686 } 687 688 double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly) 705 689 { 706 690 int loop_x = 0; … … 710 694 double ySum = 1.0; 711 695 712 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {696 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 713 697 ySum = xSum; 714 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 715 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 716 ySum*=y; 717 } 718 xSum*=x; 719 } 720 721 return(polySum); 722 } 723 724 double 725 psDPolynomial3DEval(double x, 726 double y, 727 double z, 728 const psDPolynomial3D *myPoly) 698 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 699 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 700 ySum *= y; 701 } 702 xSum *= x; 703 } 704 705 return (polySum); 706 } 707 708 double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly) 729 709 { 730 710 int loop_x = 0; … … 736 716 double zSum = 1.0; 737 717 738 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {718 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 739 719 ySum = xSum; 740 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {720 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 741 721 zSum = ySum; 742 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 743 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 744 zSum*=z; 745 } 746 ySum*=y; 747 } 748 xSum*=x; 749 } 750 751 return(polySum); 752 } 753 754 double 755 psDPolynomial4DEval(double w, 756 double x, 757 double y, 758 double z, 759 const psDPolynomial4D *myPoly) 722 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 723 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 724 zSum *= z; 725 } 726 ySum *= y; 727 } 728 xSum *= x; 729 } 730 731 return (polySum); 732 } 733 734 double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly) 760 735 { 761 736 int loop_w = 0; … … 769 744 double zSum = 1.0; 770 745 771 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {746 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 772 747 xSum = wSum; 773 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {748 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 774 749 ySum = xSum; 775 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {750 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 776 751 zSum = ySum; 777 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 778 polySum+= zSum * 779 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 780 zSum*=z; 752 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 753 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 754 zSum *= z; 781 755 } 782 ySum *=y;783 } 784 xSum *=x;785 } 786 wSum *=w;787 } 788 789 return (polySum);790 } 756 ySum *= y; 757 } 758 xSum *= x; 759 } 760 wSum *= w; 761 } 762 763 return (polySum); 764 } -
trunk/psLib/src/math/psPolynomial.h
r1406 r1407 1 1 2 /** @file psFunctions.h 2 3 * \brief Standard Mathematical Functions. … … 12 13 * @author George Gusciora, MHPCC 13 14 * 14 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #if !defined(PS_FUNCTIONS_H) 21 # define PS_FUNCTIONS_H22 23 # include <stdbool.h>24 25 # include "psVector.h"22 # define PS_FUNCTIONS_H 23 24 # include <stdbool.h> 25 26 # include "psVector.h" 26 27 27 28 /** \addtogroup Stats … … 33 34 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */ 34 35 35 float 36 psGaussian( float x, ///< Value at which to evaluate 37 float mean, ///< Mean for the Gaussian 38 float stddev, ///< Standard deviation for the Gaussian 39 bool normal ///< Indicates whether result should be normalized 40 ); 41 36 float psGaussian(float x, // /< Value at which to evaluate 37 float mean, // /< Mean for the Gaussian 38 float stddev, // /< Standard deviation for the Gaussian 39 bool normal // /< Indicates whether result should be normalized 40 ); 42 41 43 42 /** Produce a vector of random numbers from a Gaussian distribution with 44 43 the specified mean and sigma */ 45 psVector *psGaussianDev( float mean, ///< The mean of the Gaussian 46 float sigma, ///< The sigma of the Gaussian 47 int Npts ); ///< The size of the vector 48 49 50 51 44 psVector *psGaussianDev(float mean, // /< The mean of the Gaussian 45 float sigma, // /< The sigma of the Gaussian 46 int Npts); // /< The size of the vector 52 47 53 48 /** One-dimensional polynomial */ 54 49 typedef struct 55 50 { 56 int n; ///< Number of terms57 float *coeff; ///< Coefficients58 float *coeffErr; ///< Error in coefficients59 char *mask; ///< Coefficient mask51 int n; // /< Number of terms 52 float *coeff; // /< Coefficients 53 float *coeffErr; // /< Error in coefficients 54 char *mask; // /< Coefficient mask 60 55 } 61 56 psPolynomial1D; … … 64 59 typedef struct 65 60 { 66 int nX, nY; ///< Number of terms in x and y 67 float **coeff; ///< Coefficients 68 float **coeffErr; ///< Error in coefficients 69 char **mask; ///< Coefficients mask 61 int nX, 62 nY; // /< Number of terms in x and y 63 float **coeff; // /< Coefficients 64 float **coeffErr; // /< Error in coefficients 65 char **mask; // /< Coefficients mask 70 66 } 71 67 psPolynomial2D; … … 74 70 typedef struct 75 71 { 76 int nX, nY, nZ; ///< Number of terms in x, y and z 77 float ***coeff; ///< Coefficients 78 float ***coeffErr; ///< Error in coefficients 79 char ***mask; ///< Coefficients mask 72 int nX, 73 nY, 74 nZ; // /< Number of terms in x, y and z 75 float ***coeff; // /< Coefficients 76 float ***coeffErr; // /< Error in coefficients 77 char ***mask; // /< Coefficients mask 80 78 } 81 79 psPolynomial3D; … … 84 82 typedef struct 85 83 { 86 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 87 float ****coeff; ///< Coefficients 88 float ****coeffErr; ///< Error in coefficients 89 char ****mask; ///< Coefficients mask 84 int nW, 85 nX, 86 nY, 87 nZ; // /< Number of terms in w, x, y and z 88 float ****coeff; // /< Coefficients 89 float ****coeffErr; // /< Error in coefficients 90 char ****mask; // /< Coefficients mask 90 91 } 91 92 psPolynomial4D; 92 93 93 94 94 /** Functions **************************************************************/ 95 95 96 96 /** Constructor */ 97 psPolynomial1D *psPolynomial1DAlloc( int n ///< Number of terms 98 ); 99 /** Constructor */ 100 psPolynomial2D *psPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 101 ); 102 /** Constructor */ 103 psPolynomial3D *psPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 104 ); 105 /** Constructor */ 106 psPolynomial4D *psPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 97 psPolynomial1D *psPolynomial1DAlloc(int n // /< Number of terms 98 ); 99 100 /** Constructor */ 101 psPolynomial2D *psPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 102 ); 103 104 /** Constructor */ 105 psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 106 ); 107 108 /** Constructor */ 109 psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 110 // z 107 111 ); 108 112 109 113 /** Evaluate 1D polynomial */ 110 float 111 psPolynomial1DEval( float x, ///< Value at which to evaluate 112 const psPolynomial1D *myPoly ///< Coefficients for the polynomial 113 ); 114 float psPolynomial1DEval(float x, // /< Value at which to evaluate 115 const psPolynomial1D * myPoly // /< Coefficients for the polynomial 116 ); 114 117 115 118 /** Evaluate 2D polynomial */ 116 float 117 psPolynomial2DEval( float x, ///< Value x at which to evaluate 118 float y, ///< Value y at which to evaluate 119 const psPolynomial2D *myPoly ///< Coefficients for the polynomial 120 ); 119 float psPolynomial2DEval(float x, // /< Value x at which to evaluate 120 float y, // /< Value y at which to evaluate 121 const psPolynomial2D * myPoly // /< Coefficients for the polynomial 122 ); 121 123 122 124 /** Evaluate 3D polynomial */ 123 float 124 psPolynomial3DEval( float x, ///< Value x at which to evaluate 125 float y, ///< Value y at which to evaluate 126 float z, ///< Value z at which to evaluate 127 const psPolynomial3D *myPoly ///< Coefficients for the polynomial 128 ); 125 float psPolynomial3DEval(float x, // /< Value x at which to evaluate 126 float y, // /< Value y at which to evaluate 127 float z, // /< Value z at which to evaluate 128 const psPolynomial3D * myPoly // /< Coefficients for the polynomial 129 ); 129 130 130 131 /** Evaluate 4D polynomial */ 131 float 132 psPolynomial4DEval( float w, ///< Value w at which to evaluate 133 float x, ///< Value x at which to evaluate 134 float y, ///< Value y at which to evaluate 135 float z, ///< Value z at which to evaluate 136 const psPolynomial4D *myPoly ///< Coefficients for the polynomial 137 ); 132 float psPolynomial4DEval(float w, // /< Value w at which to evaluate 133 float x, // /< Value x at which to evaluate 134 float y, // /< Value y at which to evaluate 135 float z, // /< Value z at which to evaluate 136 const psPolynomial4D * myPoly // /< Coefficients for the polynomial 137 ); 138 138 139 139 /*****************************************************************************/ … … 144 144 typedef struct 145 145 { 146 int n; ///< Number of terms147 double *coeff; ///< Coefficients148 double *coeffErr; ///< Error in coefficients149 char *mask; ///< Coefficient mask146 int n; // /< Number of terms 147 double *coeff; // /< Coefficients 148 double *coeffErr; // /< Error in coefficients 149 char *mask; // /< Coefficient mask 150 150 } 151 151 psDPolynomial1D; … … 154 154 typedef struct 155 155 { 156 int nX, nY; ///< Number of terms in x and y 157 double **coeff; ///< Coefficients 158 double **coeffErr; ///< Error in coefficients 159 char **mask; ///< Coefficients mask 156 int nX, 157 nY; // /< Number of terms in x and y 158 double **coeff; // /< Coefficients 159 double **coeffErr; // /< Error in coefficients 160 char **mask; // /< Coefficients mask 160 161 } 161 162 psDPolynomial2D; … … 164 165 typedef struct 165 166 { 166 int nX, nY, nZ; ///< Number of terms in x, y and z 167 double ***coeff; ///< Coefficients 168 double ***coeffErr; ///< Error in coefficients 169 char ***mask; ///< Coefficient mask 167 int nX, 168 nY, 169 nZ; // /< Number of terms in x, y and z 170 double ***coeff; // /< Coefficients 171 double ***coeffErr; // /< Error in coefficients 172 char ***mask; // /< Coefficient mask 170 173 } 171 174 psDPolynomial3D; … … 174 177 typedef struct 175 178 { 176 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 177 double ****coeff; ///< Coefficients 178 double ****coeffErr; ///< Error in coefficients 179 char ****mask; ///< Coefficients mask 179 int nW, 180 nX, 181 nY, 182 nZ; // /< Number of terms in w, x, y and z 183 double ****coeff; // /< Coefficients 184 double ****coeffErr; // /< Error in coefficients 185 char ****mask; // /< Coefficients mask 180 186 } 181 187 psDPolynomial4D; 182 188 183 189 /** Constructor */ 184 psDPolynomial1D *psDPolynomial1DAlloc( int n ///< Number of terms 185 ); 186 /** Constructor */ 187 psDPolynomial2D *psDPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 188 ); 189 /** Constructor */ 190 psDPolynomial3D *psDPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 191 ); 192 /** Constructor */ 193 psDPolynomial4D *psDPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 190 psDPolynomial1D *psDPolynomial1DAlloc(int n // /< Number of terms 191 ); 192 193 /** Constructor */ 194 psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 195 ); 196 197 /** Constructor */ 198 psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 199 ); 200 201 /** Constructor */ 202 psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 203 // z 194 204 ); 195 205 196 206 /** Evaluate 1D polynomial (double precision) */ 197 double 198 psDPolynomial1DEval( double x, ///< Value at which to evaluate 199 const psDPolynomial1D *myPoly ///< Coefficients for the polynomial 200 ); 207 double psDPolynomial1DEval(double x, // /< Value at which to evaluate 208 const psDPolynomial1D * myPoly // /< Coefficients for the polynomial 209 ); 201 210 202 211 /** Evaluate 2D polynomial (double precision) */ 203 double 204 psDPolynomial2DEval( double x, ///< Value x at which to evaluate 205 double y, ///< Value y at which to evaluate 206 const psDPolynomial2D *myPoly ///< Coefficients for the polynomial 207 ); 212 double psDPolynomial2DEval(double x, // /< Value x at which to evaluate 213 double y, // /< Value y at which to evaluate 214 const psDPolynomial2D * myPoly // /< Coefficients for the polynomial 215 ); 208 216 209 217 /** Evaluate 3D polynomial (double precision) */ 210 double 211 psDPolynomial3DEval( double x, ///< Value x at which to evaluate 212 double y, ///< Value y at which to evaluate 213 double z, ///< Value z at which to evaluate 214 const psDPolynomial3D *myPoly ///< Coefficients for the polynomial 215 ); 218 double psDPolynomial3DEval(double x, // /< Value x at which to evaluate 219 double y, // /< Value y at which to evaluate 220 double z, // /< Value z at which to evaluate 221 const psDPolynomial3D * myPoly // /< Coefficients for the polynomial 222 ); 216 223 217 224 /** Evaluate 4D polynomial (double precision) */ 218 double 219 psDPolynomial4DEval( double w, ///< Value w at which to evaluate 220 double x, ///< Value x at which to evaluate 221 double y, ///< Value y at which to evaluate 222 double z, ///< Value z at which to evaluate 223 const psDPolynomial4D *myPoly ///< Coefficients for the polynomial 224 ); 225 226 /* \} */ // End of MathGroup Functions 225 double psDPolynomial4DEval(double w, // /< Value w at which to evaluate 226 double x, // /< Value x at which to evaluate 227 double y, // /< Value y at which to evaluate 228 double z, // /< Value z at which to evaluate 229 const psDPolynomial4D * myPoly // /< Coefficients for the polynomial 230 ); 231 232 /* \} */// End of MathGroup Functions 227 233 228 234 #endif -
trunk/psLib/src/math/psSpline.c
r1406 r1407 1 1 2 /** @file psFunctions.c 2 3 * … … 7 8 * polynomials. It also contains a Gaussian functions. 8 9 * 9 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $10 * @date $Date: 2004-08-0 6 22:34:05$10 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 11 * @date $Date: 2004-08-07 00:06:06 $ 11 12 * 12 13 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 13 14 */ 14 /*****************************************************************************/ 15 16 /*****************************************************************************/ 17 15 18 /* INCLUDE FILES */ 19 16 20 /*****************************************************************************/ 17 21 #include <stdlib.h> … … 31 35 #include <gsl/gsl_rng.h> 32 36 #include <gsl/gsl_randist.h> 33 /*****************************************************************************/ 37 38 /*****************************************************************************/ 39 34 40 /* DEFINE STATEMENTS */ 41 35 42 /*****************************************************************************/ 36 43 … … 38 45 39 46 /*****************************************************************************/ 47 40 48 /* TYPE DEFINITIONS */ 41 /*****************************************************************************/ 42 static void polynomial1DFree(psPolynomial1D *myPoly); 43 static void polynomial2DFree(psPolynomial2D *myPoly); 44 static void polynomial3DFree(psPolynomial3D *myPoly); 45 static void polynomial4DFree(psPolynomial4D *myPoly); 46 static void dPolynomial1DFree(psDPolynomial1D *myPoly); 47 static void dPolynomial2DFree(psDPolynomial2D *myPoly); 48 static void dPolynomial3DFree(psDPolynomial3D *myPoly); 49 static void dPolynomial4DFree(psDPolynomial4D *myPoly); 50 51 /*****************************************************************************/ 49 50 /*****************************************************************************/ 51 static void polynomial1DFree(psPolynomial1D * myPoly); 52 static void polynomial2DFree(psPolynomial2D * myPoly); 53 static void polynomial3DFree(psPolynomial3D * myPoly); 54 static void polynomial4DFree(psPolynomial4D * myPoly); 55 static void dPolynomial1DFree(psDPolynomial1D * myPoly); 56 static void dPolynomial2DFree(psDPolynomial2D * myPoly); 57 static void dPolynomial3DFree(psDPolynomial3D * myPoly); 58 static void dPolynomial4DFree(psDPolynomial4D * myPoly); 59 60 /*****************************************************************************/ 61 52 62 /* GLOBAL VARIABLES */ 63 53 64 /*****************************************************************************/ 54 65 … … 56 67 57 68 /*****************************************************************************/ 69 58 70 /* FILE STATIC VARIABLES */ 71 59 72 /*****************************************************************************/ 60 73 … … 62 75 63 76 /*****************************************************************************/ 77 64 78 /* FUNCTION IMPLEMENTATION - LOCAL */ 79 65 80 /*****************************************************************************/ 66 81 … … 68 83 69 84 /*****************************************************************************/ 85 70 86 /* FUNCTION IMPLEMENTATION - PUBLIC */ 87 71 88 /*****************************************************************************/ 72 89 … … 76 93 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] 77 94 *****************************************************************************/ 78 float 79 psGaussian(float x, 80 float mean, 81 float sigma, 82 bool normal) 95 float psGaussian(float x, float mean, float sigma, bool normal) 83 96 { 84 97 float tmp = 1.0; … … 94 107 } 95 108 96 return (tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));109 return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma))); 97 110 } 98 111 … … 107 120 NOTE: There is no way to seed the random generator. 108 121 *****************************************************************************/ 109 psVector *psGaussianDev(float mean, 110 float sigma, 111 int Npts) 122 psVector *psGaussianDev(float mean, float sigma, int Npts) 112 123 { 113 124 psVector *gauss = NULL; … … 127 138 128 139 // NOTE: Should I free r as well? 129 return(gauss); 130 } 131 140 return (gauss); 141 } 132 142 133 143 /***************************************************************************** … … 140 150 141 151 newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D)); 142 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial1DFree);152 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree); 143 153 newPoly->n = n; 144 newPoly->coeff = (float *)psAlloc(n * sizeof(float));145 newPoly->coeffErr = (float *) psAlloc(n * sizeof(float));146 newPoly->mask = (char *)psAlloc(n * sizeof(char));147 for (i =0;i<n;i++) {154 newPoly->coeff = (float *)psAlloc(n * sizeof(float)); 155 newPoly->coeffErr = (float *)psAlloc(n * sizeof(float)); 156 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 157 for (i = 0; i < n; i++) { 148 158 newPoly->coeff[i] = 0.0; 149 159 newPoly->coeffErr[i] = 0.0; … … 151 161 } 152 162 153 return (newPoly);163 return (newPoly); 154 164 } 155 165 … … 161 171 162 172 newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D)); 163 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial2DFree);173 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree); 164 174 newPoly->nX = nX; 165 175 newPoly->nY = nY; 166 176 167 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *));168 newPoly->coeffErr = (float **) psAlloc(nX * sizeof(float *));169 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));170 for (x =0;x<nX;x++) {171 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float));172 newPoly->coeffErr[x] = (float *) psAlloc(nY * sizeof(float));173 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));174 } 175 for (x =0;x<nX;x++) {176 for (y =0;y<nY;y++) {177 newPoly->coeff = (float **)psAlloc(nX * sizeof(float *)); 178 newPoly->coeffErr = (float **)psAlloc(nX * sizeof(float *)); 179 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 180 for (x = 0; x < nX; x++) { 181 newPoly->coeff[x] = (float *)psAlloc(nY * sizeof(float)); 182 newPoly->coeffErr[x] = (float *)psAlloc(nY * sizeof(float)); 183 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 184 } 185 for (x = 0; x < nX; x++) { 186 for (y = 0; y < nY; y++) { 177 187 newPoly->coeff[x][y] = 0.0; 178 188 newPoly->coeffErr[x][y] = 0.0; … … 181 191 } 182 192 183 return (newPoly);193 return (newPoly); 184 194 } 185 195 … … 192 202 193 203 newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D)); 194 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial3DFree);204 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree); 195 205 newPoly->nX = nX; 196 206 newPoly->nY = nY; 197 207 newPoly->nZ = nZ; 198 208 199 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **));200 newPoly->coeffErr = (float ***) psAlloc(nX * sizeof(float **));201 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));202 for (x =0;x<nX;x++) {203 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *));204 newPoly->coeffErr[x] = (float **) psAlloc(nY * sizeof(float *));205 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));206 for (y =0;y<nY;y++) {207 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float));208 newPoly->coeffErr[x][y] = (float *) psAlloc(nZ * sizeof(float));209 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));210 } 211 } 212 for (x =0;x<nX;x++) {213 for (y =0;y<nY;y++) {214 for (z =0;z<nZ;z++) {209 newPoly->coeff = (float ***)psAlloc(nX * sizeof(float **)); 210 newPoly->coeffErr = (float ***)psAlloc(nX * sizeof(float **)); 211 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 212 for (x = 0; x < nX; x++) { 213 newPoly->coeff[x] = (float **)psAlloc(nY * sizeof(float *)); 214 newPoly->coeffErr[x] = (float **)psAlloc(nY * sizeof(float *)); 215 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 216 for (y = 0; y < nY; y++) { 217 newPoly->coeff[x][y] = (float *)psAlloc(nZ * sizeof(float)); 218 newPoly->coeffErr[x][y] = (float *)psAlloc(nZ * sizeof(float)); 219 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 220 } 221 } 222 for (x = 0; x < nX; x++) { 223 for (y = 0; y < nY; y++) { 224 for (z = 0; z < nZ; z++) { 215 225 newPoly->coeff[x][y][z] = 0.0; 216 226 newPoly->coeffErr[x][y][z] = 0.0; … … 220 230 } 221 231 222 return (newPoly);232 return (newPoly); 223 233 } 224 234 … … 232 242 233 243 newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D)); 234 p_psMemSetDeallocator(newPoly, (psFreeFcn)polynomial4DFree);244 p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree); 235 245 newPoly->nW = nW; 236 246 newPoly->nX = nX; … … 238 248 newPoly->nZ = nZ; 239 249 240 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***));241 newPoly->coeffErr = (float ****) psAlloc(nW * sizeof(float ***));242 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));243 for (w =0;w<nW;w++) {244 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **));245 newPoly->coeffErr[w] = (float ***) psAlloc(nX * sizeof(float **));246 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));247 for (x =0;x<nX;x++) {248 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *));249 newPoly->coeffErr[w][x] = (float **) psAlloc(nY * sizeof(float *));250 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));251 for (y =0;y<nY;y++) {252 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float));253 newPoly->coeffErr[w][x][y] = (float *) psAlloc(nZ * sizeof(float));254 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));255 } 256 } 257 } 258 for (w =0;w<nW;w++) {259 for (x =0;x<nX;x++) {260 for (y =0;y<nY;y++) {261 for (z =0;z<nZ;z++) {250 newPoly->coeff = (float ****)psAlloc(nW * sizeof(float ***)); 251 newPoly->coeffErr = (float ****)psAlloc(nW * sizeof(float ***)); 252 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 253 for (w = 0; w < nW; w++) { 254 newPoly->coeff[w] = (float ***)psAlloc(nX * sizeof(float **)); 255 newPoly->coeffErr[w] = (float ***)psAlloc(nX * sizeof(float **)); 256 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 257 for (x = 0; x < nX; x++) { 258 newPoly->coeff[w][x] = (float **)psAlloc(nY * sizeof(float *)); 259 newPoly->coeffErr[w][x] = (float **)psAlloc(nY * sizeof(float *)); 260 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 261 for (y = 0; y < nY; y++) { 262 newPoly->coeff[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 263 newPoly->coeffErr[w][x][y] = (float *)psAlloc(nZ * sizeof(float)); 264 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 265 } 266 } 267 } 268 for (w = 0; w < nW; w++) { 269 for (x = 0; x < nX; x++) { 270 for (y = 0; y < nY; y++) { 271 for (z = 0; z < nZ; z++) { 262 272 newPoly->coeff[w][x][y][z] = 0.0; 263 273 newPoly->coeffErr[w][x][y][z] = 0.0; … … 268 278 } 269 279 270 return (newPoly);271 } 272 273 static void polynomial1DFree(psPolynomial1D * myPoly)280 return (newPoly); 281 } 282 283 static void polynomial1DFree(psPolynomial1D * myPoly) 274 284 { 275 285 psFree(myPoly->coeff); … … 278 288 } 279 289 280 static void polynomial2DFree(psPolynomial2D * myPoly)281 { 282 int x = 0; 283 284 for (x =0;x<myPoly->nX;x++) {290 static void polynomial2DFree(psPolynomial2D * myPoly) 291 { 292 int x = 0; 293 294 for (x = 0; x < myPoly->nX; x++) { 285 295 psFree(myPoly->coeff[x]); 286 296 psFree(myPoly->coeffErr[x]); … … 292 302 } 293 303 294 static void polynomial3DFree(psPolynomial3D * myPoly)295 { 296 int x = 0; 297 int y = 0; 298 299 for (x =0;x<myPoly->nX;x++) {300 for (y =0;y<myPoly->nY;y++) {304 static void polynomial3DFree(psPolynomial3D * myPoly) 305 { 306 int x = 0; 307 int y = 0; 308 309 for (x = 0; x < myPoly->nX; x++) { 310 for (y = 0; y < myPoly->nY; y++) { 301 311 psFree(myPoly->coeff[x][y]); 302 312 psFree(myPoly->coeffErr[x][y]); … … 313 323 } 314 324 315 static void polynomial4DFree(psPolynomial4D * myPoly)325 static void polynomial4DFree(psPolynomial4D * myPoly) 316 326 { 317 327 int w = 0; … … 319 329 int y = 0; 320 330 321 for (w =0;w<myPoly->nW;w++) {322 for (x =0;x<myPoly->nX;x++) {323 for (y =0;y<myPoly->nY;y++) {331 for (w = 0; w < myPoly->nW; w++) { 332 for (x = 0; x < myPoly->nX; x++) { 333 for (y = 0; y < myPoly->nY; y++) { 324 334 psFree(myPoly->coeff[w][x][y]); 325 335 psFree(myPoly->coeffErr[w][x][y]); … … 343 353 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 344 354 *****************************************************************************/ 345 float 346 psPolynomial1DEval(float x, 347 const psPolynomial1D *myPoly) 355 float psPolynomial1DEval(float x, const psPolynomial1D * myPoly) 348 356 { 349 357 int loop_x = 0; … … 355 363 } 356 364 357 358 365 // NOTE: Do we want to flag this case? 359 366 if (myPoly->n == 0) { 360 return (1.0);367 return (1.0); 361 368 } 362 369 … … 365 372 } 366 373 367 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 368 polySum+= xSum * myPoly->coeff[loop_x]; 369 xSum*=x; 370 } 371 372 return(polySum); 373 } 374 375 376 float 377 psPolynomial2DEval(float x, 378 float y, 379 const psPolynomial2D *myPoly) 374 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 375 polySum += xSum * myPoly->coeff[loop_x]; 376 xSum *= x; 377 } 378 379 return (polySum); 380 } 381 382 float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly) 380 383 { 381 384 int loop_x = 0; … … 385 388 float ySum = 1.0; 386 389 387 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {390 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 388 391 ySum = xSum; 389 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 390 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 391 ySum*=y; 392 } 393 xSum*=x; 394 } 395 396 return(polySum); 397 } 398 399 float 400 psPolynomial3DEval(float x, 401 float y, 402 float z, 403 const psPolynomial3D *myPoly) 392 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 393 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 394 ySum *= y; 395 } 396 xSum *= x; 397 } 398 399 return (polySum); 400 } 401 402 float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly) 404 403 { 405 404 int loop_x = 0; … … 411 410 float zSum = 1.0; 412 411 413 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {412 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 414 413 ySum = xSum; 415 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {414 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 416 415 zSum = ySum; 417 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 418 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 419 zSum*=z; 420 } 421 ySum*=y; 422 } 423 xSum*=x; 424 } 425 426 return(polySum); 427 } 428 429 float 430 psPolynomial4DEval(float w, 431 float x, 432 float y, 433 float z, 434 const psPolynomial4D *myPoly) 416 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 417 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 418 zSum *= z; 419 } 420 ySum *= y; 421 } 422 xSum *= x; 423 } 424 425 return (polySum); 426 } 427 428 float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly) 435 429 { 436 430 int loop_w = 0; … … 444 438 float zSum = 1.0; 445 439 446 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {440 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 447 441 xSum = wSum; 448 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {442 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 449 443 ySum = xSum; 450 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {444 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 451 445 zSum = ySum; 452 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 453 polySum+= zSum * 454 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 455 zSum*=z; 446 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 447 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 448 zSum *= z; 456 449 } 457 ySum*=y; 458 } 459 xSum*=x; 460 } 461 wSum*=w; 462 } 463 464 return(polySum); 465 } 466 467 468 450 ySum *= y; 451 } 452 xSum *= x; 453 } 454 wSum *= w; 455 } 456 457 return (polySum); 458 } 469 459 470 460 psDPolynomial1D *psDPolynomial1DAlloc(int n) … … 474 464 475 465 newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D)); 476 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial1DFree);466 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree); 477 467 newPoly->n = n; 478 newPoly->coeff = (double *)psAlloc(n * sizeof(double));479 newPoly->coeffErr = (double *) psAlloc(n * sizeof(double));480 newPoly->mask = (char *)psAlloc(n * sizeof(char));481 for (i =0;i<n;i++) {468 newPoly->coeff = (double *)psAlloc(n * sizeof(double)); 469 newPoly->coeffErr = (double *)psAlloc(n * sizeof(double)); 470 newPoly->mask = (char *)psAlloc(n * sizeof(char)); 471 for (i = 0; i < n; i++) { 482 472 newPoly->coeff[i] = 0.0; 483 473 newPoly->coeffErr[i] = 0.0; … … 485 475 } 486 476 487 return (newPoly);477 return (newPoly); 488 478 } 489 479 … … 495 485 496 486 newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D)); 497 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial2DFree);487 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree); 498 488 newPoly->nX = nX; 499 489 newPoly->nY = nY; 500 490 501 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *));502 newPoly->coeffErr = (double **) psAlloc(nX * sizeof(double *));503 newPoly->mask = (char **)psAlloc(nX * sizeof(char *));504 for (x =0;x<nX;x++) {505 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double));506 newPoly->coeffErr[x] = (double *) psAlloc(nY * sizeof(double));507 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char));508 } 509 for (x =0;x<nX;x++) {510 for (y =0;y<nY;y++) {491 newPoly->coeff = (double **)psAlloc(nX * sizeof(double *)); 492 newPoly->coeffErr = (double **)psAlloc(nX * sizeof(double *)); 493 newPoly->mask = (char **)psAlloc(nX * sizeof(char *)); 494 for (x = 0; x < nX; x++) { 495 newPoly->coeff[x] = (double *)psAlloc(nY * sizeof(double)); 496 newPoly->coeffErr[x] = (double *)psAlloc(nY * sizeof(double)); 497 newPoly->mask[x] = (char *)psAlloc(nY * sizeof(char)); 498 } 499 for (x = 0; x < nX; x++) { 500 for (y = 0; y < nY; y++) { 511 501 newPoly->coeff[x][y] = 0.0; 512 502 newPoly->coeffErr[x][y] = 0.0; … … 515 505 } 516 506 517 return (newPoly);507 return (newPoly); 518 508 } 519 509 … … 526 516 527 517 newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D)); 528 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial3DFree);518 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree); 529 519 newPoly->nX = nX; 530 520 newPoly->nY = nY; 531 521 newPoly->nZ = nZ; 532 522 533 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **));534 newPoly->coeffErr = (double ***) psAlloc(nX * sizeof(double **));535 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **));536 for (x =0;x<nX;x++) {537 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *));538 newPoly->coeffErr[x] = (double **) psAlloc(nY * sizeof(double *));539 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *));540 for (y =0;y<nY;y++) {541 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double));542 newPoly->coeffErr[x][y] = (double *) psAlloc(nZ * sizeof(double));543 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char));544 } 545 } 546 for (x =0;x<nX;x++) {547 for (y =0;y<nY;y++) {548 for (z =0;z<nZ;z++) {523 newPoly->coeff = (double ***)psAlloc(nX * sizeof(double **)); 524 newPoly->coeffErr = (double ***)psAlloc(nX * sizeof(double **)); 525 newPoly->mask = (char ***)psAlloc(nX * sizeof(char **)); 526 for (x = 0; x < nX; x++) { 527 newPoly->coeff[x] = (double **)psAlloc(nY * sizeof(double *)); 528 newPoly->coeffErr[x] = (double **)psAlloc(nY * sizeof(double *)); 529 newPoly->mask[x] = (char **)psAlloc(nY * sizeof(char *)); 530 for (y = 0; y < nY; y++) { 531 newPoly->coeff[x][y] = (double *)psAlloc(nZ * sizeof(double)); 532 newPoly->coeffErr[x][y] = (double *)psAlloc(nZ * sizeof(double)); 533 newPoly->mask[x][y] = (char *)psAlloc(nZ * sizeof(char)); 534 } 535 } 536 for (x = 0; x < nX; x++) { 537 for (y = 0; y < nY; y++) { 538 for (z = 0; z < nZ; z++) { 549 539 newPoly->coeff[x][y][z] = 0.0; 550 540 newPoly->coeffErr[x][y][z] = 0.0; … … 554 544 } 555 545 556 return (newPoly);546 return (newPoly); 557 547 } 558 548 … … 566 556 567 557 newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D)); 568 p_psMemSetDeallocator(newPoly, (psFreeFcn)dPolynomial4DFree);558 p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree); 569 559 newPoly->nW = nW; 570 560 newPoly->nX = nX; … … 572 562 newPoly->nZ = nZ; 573 563 574 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***));575 newPoly->coeffErr = (double ****) psAlloc(nW * sizeof(double ***));576 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***));577 for (w =0;w<nW;w++) {578 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **));579 newPoly->coeffErr[w] = (double ***) psAlloc(nX * sizeof(double **));580 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **));581 for (x =0;x<nX;x++) {582 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *));583 newPoly->coeffErr[w][x] = (double **) psAlloc(nY * sizeof(double *));584 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *));585 for (y =0;y<nY;y++) {586 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double));587 newPoly->coeffErr[w][x][y] = (double *) psAlloc(nZ * sizeof(double));588 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char));589 } 590 } 591 } 592 for (w =0;w<nW;w++) {593 for (x =0;x<nX;x++) {594 for (y =0;y<nY;y++) {595 for (z =0;z<nZ;z++) {564 newPoly->coeff = (double ****)psAlloc(nW * sizeof(double ***)); 565 newPoly->coeffErr = (double ****)psAlloc(nW * sizeof(double ***)); 566 newPoly->mask = (char ****)psAlloc(nW * sizeof(char ***)); 567 for (w = 0; w < nW; w++) { 568 newPoly->coeff[w] = (double ***)psAlloc(nX * sizeof(double **)); 569 newPoly->coeffErr[w] = (double ***)psAlloc(nX * sizeof(double **)); 570 newPoly->mask[w] = (char ***)psAlloc(nX * sizeof(char **)); 571 for (x = 0; x < nX; x++) { 572 newPoly->coeff[w][x] = (double **)psAlloc(nY * sizeof(double *)); 573 newPoly->coeffErr[w][x] = (double **)psAlloc(nY * sizeof(double *)); 574 newPoly->mask[w][x] = (char **)psAlloc(nY * sizeof(char *)); 575 for (y = 0; y < nY; y++) { 576 newPoly->coeff[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 577 newPoly->coeffErr[w][x][y] = (double *)psAlloc(nZ * sizeof(double)); 578 newPoly->mask[w][x][y] = (char *)psAlloc(nZ * sizeof(char)); 579 } 580 } 581 } 582 for (w = 0; w < nW; w++) { 583 for (x = 0; x < nX; x++) { 584 for (y = 0; y < nY; y++) { 585 for (z = 0; z < nZ; z++) { 596 586 newPoly->coeff[w][x][y][z] = 0.0; 597 587 newPoly->coeffErr[w][x][y][z] = 0.0; … … 602 592 } 603 593 604 return (newPoly);605 } 606 607 static void dPolynomial1DFree(psDPolynomial1D * myPoly)594 return (newPoly); 595 } 596 597 static void dPolynomial1DFree(psDPolynomial1D * myPoly) 608 598 { 609 599 psFree(myPoly->coeff); … … 612 602 } 613 603 614 static void dPolynomial2DFree(psDPolynomial2D * myPoly)615 { 616 int x = 0; 617 618 for (x =0;x<myPoly->nX;x++) {604 static void dPolynomial2DFree(psDPolynomial2D * myPoly) 605 { 606 int x = 0; 607 608 for (x = 0; x < myPoly->nX; x++) { 619 609 psFree(myPoly->coeff[x]); 620 610 psFree(myPoly->coeffErr[x]); … … 626 616 } 627 617 628 static void dPolynomial3DFree(psDPolynomial3D * myPoly)629 { 630 int x = 0; 631 int y = 0; 632 633 for (x =0;x<myPoly->nX;x++) {634 for (y =0;y<myPoly->nY;y++) {618 static void dPolynomial3DFree(psDPolynomial3D * myPoly) 619 { 620 int x = 0; 621 int y = 0; 622 623 for (x = 0; x < myPoly->nX; x++) { 624 for (y = 0; y < myPoly->nY; y++) { 635 625 psFree(myPoly->coeff[x][y]); 636 626 psFree(myPoly->coeffErr[x][y]); … … 647 637 } 648 638 649 static void dPolynomial4DFree(psDPolynomial4D * myPoly)639 static void dPolynomial4DFree(psDPolynomial4D * myPoly) 650 640 { 651 641 int w = 0; … … 653 643 int y = 0; 654 644 655 for (w =0;w<myPoly->nW;w++) {656 for (x =0;x<myPoly->nX;x++) {657 for (y =0;y<myPoly->nY;y++) {645 for (w = 0; w < myPoly->nW; w++) { 646 for (x = 0; x < myPoly->nX; x++) { 647 for (y = 0; y < myPoly->nY; y++) { 658 648 psFree(myPoly->coeff[w][x][y]); 659 649 psFree(myPoly->coeffErr[w][x][y]); … … 677 667 Polynomial coefficients will be accessed in [w][x][y][z] fashion. 678 668 *****************************************************************************/ 679 double 680 psDPolynomial1DEval(double x, 681 const psDPolynomial1D *myPoly) 669 double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly) 682 670 { 683 671 int loop_x = 0; … … 687 675 // NOTE: Do we want to flag this case? 688 676 if (myPoly->n == 0) { 689 return(1.0); 690 } 691 692 for (loop_x=0;loop_x<myPoly->n;loop_x++) { 693 polySum+= xSum * myPoly->coeff[loop_x]; 694 xSum*=x; 695 } 696 697 return(polySum); 698 } 699 700 701 double 702 psDPolynomial2DEval(double x, 703 double y, 704 const psDPolynomial2D *myPoly) 677 return (1.0); 678 } 679 680 for (loop_x = 0; loop_x < myPoly->n; loop_x++) { 681 polySum += xSum * myPoly->coeff[loop_x]; 682 xSum *= x; 683 } 684 685 return (polySum); 686 } 687 688 double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly) 705 689 { 706 690 int loop_x = 0; … … 710 694 double ySum = 1.0; 711 695 712 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {696 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 713 697 ySum = xSum; 714 for (loop_y=0;loop_y<myPoly->nY;loop_y++) { 715 polySum+= ySum * myPoly->coeff[loop_x][loop_y]; 716 ySum*=y; 717 } 718 xSum*=x; 719 } 720 721 return(polySum); 722 } 723 724 double 725 psDPolynomial3DEval(double x, 726 double y, 727 double z, 728 const psDPolynomial3D *myPoly) 698 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 699 polySum += ySum * myPoly->coeff[loop_x][loop_y]; 700 ySum *= y; 701 } 702 xSum *= x; 703 } 704 705 return (polySum); 706 } 707 708 double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly) 729 709 { 730 710 int loop_x = 0; … … 736 716 double zSum = 1.0; 737 717 738 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {718 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 739 719 ySum = xSum; 740 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {720 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 741 721 zSum = ySum; 742 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 743 polySum+= zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 744 zSum*=z; 745 } 746 ySum*=y; 747 } 748 xSum*=x; 749 } 750 751 return(polySum); 752 } 753 754 double 755 psDPolynomial4DEval(double w, 756 double x, 757 double y, 758 double z, 759 const psDPolynomial4D *myPoly) 722 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 723 polySum += zSum * myPoly->coeff[loop_x][loop_y][loop_z]; 724 zSum *= z; 725 } 726 ySum *= y; 727 } 728 xSum *= x; 729 } 730 731 return (polySum); 732 } 733 734 double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly) 760 735 { 761 736 int loop_w = 0; … … 769 744 double zSum = 1.0; 770 745 771 for (loop_w =0;loop_w<myPoly->nW;loop_w++) {746 for (loop_w = 0; loop_w < myPoly->nW; loop_w++) { 772 747 xSum = wSum; 773 for (loop_x =0;loop_x<myPoly->nX;loop_x++) {748 for (loop_x = 0; loop_x < myPoly->nX; loop_x++) { 774 749 ySum = xSum; 775 for (loop_y =0;loop_y<myPoly->nY;loop_y++) {750 for (loop_y = 0; loop_y < myPoly->nY; loop_y++) { 776 751 zSum = ySum; 777 for (loop_z=0;loop_z<myPoly->nZ;loop_z++) { 778 polySum+= zSum * 779 myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 780 zSum*=z; 752 for (loop_z = 0; loop_z < myPoly->nZ; loop_z++) { 753 polySum += zSum * myPoly->coeff[loop_w][loop_x][loop_y][loop_z]; 754 zSum *= z; 781 755 } 782 ySum *=y;783 } 784 xSum *=x;785 } 786 wSum *=w;787 } 788 789 return (polySum);790 } 756 ySum *= y; 757 } 758 xSum *= x; 759 } 760 wSum *= w; 761 } 762 763 return (polySum); 764 } -
trunk/psLib/src/math/psSpline.h
r1406 r1407 1 1 2 /** @file psFunctions.h 2 3 * \brief Standard Mathematical Functions. … … 12 13 * @author George Gusciora, MHPCC 13 14 * 14 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-08-0 6 22:34:05$15 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #if !defined(PS_FUNCTIONS_H) 21 # define PS_FUNCTIONS_H22 23 # include <stdbool.h>24 25 # include "psVector.h"22 # define PS_FUNCTIONS_H 23 24 # include <stdbool.h> 25 26 # include "psVector.h" 26 27 27 28 /** \addtogroup Stats … … 33 34 evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */ 34 35 35 float 36 psGaussian( float x, ///< Value at which to evaluate 37 float mean, ///< Mean for the Gaussian 38 float stddev, ///< Standard deviation for the Gaussian 39 bool normal ///< Indicates whether result should be normalized 40 ); 41 36 float psGaussian(float x, // /< Value at which to evaluate 37 float mean, // /< Mean for the Gaussian 38 float stddev, // /< Standard deviation for the Gaussian 39 bool normal // /< Indicates whether result should be normalized 40 ); 42 41 43 42 /** Produce a vector of random numbers from a Gaussian distribution with 44 43 the specified mean and sigma */ 45 psVector *psGaussianDev( float mean, ///< The mean of the Gaussian 46 float sigma, ///< The sigma of the Gaussian 47 int Npts ); ///< The size of the vector 48 49 50 51 44 psVector *psGaussianDev(float mean, // /< The mean of the Gaussian 45 float sigma, // /< The sigma of the Gaussian 46 int Npts); // /< The size of the vector 52 47 53 48 /** One-dimensional polynomial */ 54 49 typedef struct 55 50 { 56 int n; ///< Number of terms57 float *coeff; ///< Coefficients58 float *coeffErr; ///< Error in coefficients59 char *mask; ///< Coefficient mask51 int n; // /< Number of terms 52 float *coeff; // /< Coefficients 53 float *coeffErr; // /< Error in coefficients 54 char *mask; // /< Coefficient mask 60 55 } 61 56 psPolynomial1D; … … 64 59 typedef struct 65 60 { 66 int nX, nY; ///< Number of terms in x and y 67 float **coeff; ///< Coefficients 68 float **coeffErr; ///< Error in coefficients 69 char **mask; ///< Coefficients mask 61 int nX, 62 nY; // /< Number of terms in x and y 63 float **coeff; // /< Coefficients 64 float **coeffErr; // /< Error in coefficients 65 char **mask; // /< Coefficients mask 70 66 } 71 67 psPolynomial2D; … … 74 70 typedef struct 75 71 { 76 int nX, nY, nZ; ///< Number of terms in x, y and z 77 float ***coeff; ///< Coefficients 78 float ***coeffErr; ///< Error in coefficients 79 char ***mask; ///< Coefficients mask 72 int nX, 73 nY, 74 nZ; // /< Number of terms in x, y and z 75 float ***coeff; // /< Coefficients 76 float ***coeffErr; // /< Error in coefficients 77 char ***mask; // /< Coefficients mask 80 78 } 81 79 psPolynomial3D; … … 84 82 typedef struct 85 83 { 86 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 87 float ****coeff; ///< Coefficients 88 float ****coeffErr; ///< Error in coefficients 89 char ****mask; ///< Coefficients mask 84 int nW, 85 nX, 86 nY, 87 nZ; // /< Number of terms in w, x, y and z 88 float ****coeff; // /< Coefficients 89 float ****coeffErr; // /< Error in coefficients 90 char ****mask; // /< Coefficients mask 90 91 } 91 92 psPolynomial4D; 92 93 93 94 94 /** Functions **************************************************************/ 95 95 96 96 /** Constructor */ 97 psPolynomial1D *psPolynomial1DAlloc( int n ///< Number of terms 98 ); 99 /** Constructor */ 100 psPolynomial2D *psPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 101 ); 102 /** Constructor */ 103 psPolynomial3D *psPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 104 ); 105 /** Constructor */ 106 psPolynomial4D *psPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 97 psPolynomial1D *psPolynomial1DAlloc(int n // /< Number of terms 98 ); 99 100 /** Constructor */ 101 psPolynomial2D *psPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 102 ); 103 104 /** Constructor */ 105 psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 106 ); 107 108 /** Constructor */ 109 psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 110 // z 107 111 ); 108 112 109 113 /** Evaluate 1D polynomial */ 110 float 111 psPolynomial1DEval( float x, ///< Value at which to evaluate 112 const psPolynomial1D *myPoly ///< Coefficients for the polynomial 113 ); 114 float psPolynomial1DEval(float x, // /< Value at which to evaluate 115 const psPolynomial1D * myPoly // /< Coefficients for the polynomial 116 ); 114 117 115 118 /** Evaluate 2D polynomial */ 116 float 117 psPolynomial2DEval( float x, ///< Value x at which to evaluate 118 float y, ///< Value y at which to evaluate 119 const psPolynomial2D *myPoly ///< Coefficients for the polynomial 120 ); 119 float psPolynomial2DEval(float x, // /< Value x at which to evaluate 120 float y, // /< Value y at which to evaluate 121 const psPolynomial2D * myPoly // /< Coefficients for the polynomial 122 ); 121 123 122 124 /** Evaluate 3D polynomial */ 123 float 124 psPolynomial3DEval( float x, ///< Value x at which to evaluate 125 float y, ///< Value y at which to evaluate 126 float z, ///< Value z at which to evaluate 127 const psPolynomial3D *myPoly ///< Coefficients for the polynomial 128 ); 125 float psPolynomial3DEval(float x, // /< Value x at which to evaluate 126 float y, // /< Value y at which to evaluate 127 float z, // /< Value z at which to evaluate 128 const psPolynomial3D * myPoly // /< Coefficients for the polynomial 129 ); 129 130 130 131 /** Evaluate 4D polynomial */ 131 float 132 psPolynomial4DEval( float w, ///< Value w at which to evaluate 133 float x, ///< Value x at which to evaluate 134 float y, ///< Value y at which to evaluate 135 float z, ///< Value z at which to evaluate 136 const psPolynomial4D *myPoly ///< Coefficients for the polynomial 137 ); 132 float psPolynomial4DEval(float w, // /< Value w at which to evaluate 133 float x, // /< Value x at which to evaluate 134 float y, // /< Value y at which to evaluate 135 float z, // /< Value z at which to evaluate 136 const psPolynomial4D * myPoly // /< Coefficients for the polynomial 137 ); 138 138 139 139 /*****************************************************************************/ … … 144 144 typedef struct 145 145 { 146 int n; ///< Number of terms147 double *coeff; ///< Coefficients148 double *coeffErr; ///< Error in coefficients149 char *mask; ///< Coefficient mask146 int n; // /< Number of terms 147 double *coeff; // /< Coefficients 148 double *coeffErr; // /< Error in coefficients 149 char *mask; // /< Coefficient mask 150 150 } 151 151 psDPolynomial1D; … … 154 154 typedef struct 155 155 { 156 int nX, nY; ///< Number of terms in x and y 157 double **coeff; ///< Coefficients 158 double **coeffErr; ///< Error in coefficients 159 char **mask; ///< Coefficients mask 156 int nX, 157 nY; // /< Number of terms in x and y 158 double **coeff; // /< Coefficients 159 double **coeffErr; // /< Error in coefficients 160 char **mask; // /< Coefficients mask 160 161 } 161 162 psDPolynomial2D; … … 164 165 typedef struct 165 166 { 166 int nX, nY, nZ; ///< Number of terms in x, y and z 167 double ***coeff; ///< Coefficients 168 double ***coeffErr; ///< Error in coefficients 169 char ***mask; ///< Coefficient mask 167 int nX, 168 nY, 169 nZ; // /< Number of terms in x, y and z 170 double ***coeff; // /< Coefficients 171 double ***coeffErr; // /< Error in coefficients 172 char ***mask; // /< Coefficient mask 170 173 } 171 174 psDPolynomial3D; … … 174 177 typedef struct 175 178 { 176 int nW, nX, nY, nZ; ///< Number of terms in w, x, y and z 177 double ****coeff; ///< Coefficients 178 double ****coeffErr; ///< Error in coefficients 179 char ****mask; ///< Coefficients mask 179 int nW, 180 nX, 181 nY, 182 nZ; // /< Number of terms in w, x, y and z 183 double ****coeff; // /< Coefficients 184 double ****coeffErr; // /< Error in coefficients 185 char ****mask; // /< Coefficients mask 180 186 } 181 187 psDPolynomial4D; 182 188 183 189 /** Constructor */ 184 psDPolynomial1D *psDPolynomial1DAlloc( int n ///< Number of terms 185 ); 186 /** Constructor */ 187 psDPolynomial2D *psDPolynomial2DAlloc( int nX, int nY ///< Number of terms in x and y 188 ); 189 /** Constructor */ 190 psDPolynomial3D *psDPolynomial3DAlloc( int nX, int nY, int nZ ///< Number of terms in x, y and z 191 ); 192 /** Constructor */ 193 psDPolynomial4D *psDPolynomial4DAlloc( int nW, int nX, int nY, int nZ ///< Number of terms in w, x, y and z 190 psDPolynomial1D *psDPolynomial1DAlloc(int n // /< Number of terms 191 ); 192 193 /** Constructor */ 194 psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY // /< Number of terms in x and y 195 ); 196 197 /** Constructor */ 198 psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ // /< Number of terms in x, y and z 199 ); 200 201 /** Constructor */ 202 psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ // /< Number of terms in w, x, y and 203 // z 194 204 ); 195 205 196 206 /** Evaluate 1D polynomial (double precision) */ 197 double 198 psDPolynomial1DEval( double x, ///< Value at which to evaluate 199 const psDPolynomial1D *myPoly ///< Coefficients for the polynomial 200 ); 207 double psDPolynomial1DEval(double x, // /< Value at which to evaluate 208 const psDPolynomial1D * myPoly // /< Coefficients for the polynomial 209 ); 201 210 202 211 /** Evaluate 2D polynomial (double precision) */ 203 double 204 psDPolynomial2DEval( double x, ///< Value x at which to evaluate 205 double y, ///< Value y at which to evaluate 206 const psDPolynomial2D *myPoly ///< Coefficients for the polynomial 207 ); 212 double psDPolynomial2DEval(double x, // /< Value x at which to evaluate 213 double y, // /< Value y at which to evaluate 214 const psDPolynomial2D * myPoly // /< Coefficients for the polynomial 215 ); 208 216 209 217 /** Evaluate 3D polynomial (double precision) */ 210 double 211 psDPolynomial3DEval( double x, ///< Value x at which to evaluate 212 double y, ///< Value y at which to evaluate 213 double z, ///< Value z at which to evaluate 214 const psDPolynomial3D *myPoly ///< Coefficients for the polynomial 215 ); 218 double psDPolynomial3DEval(double x, // /< Value x at which to evaluate 219 double y, // /< Value y at which to evaluate 220 double z, // /< Value z at which to evaluate 221 const psDPolynomial3D * myPoly // /< Coefficients for the polynomial 222 ); 216 223 217 224 /** Evaluate 4D polynomial (double precision) */ 218 double 219 psDPolynomial4DEval( double w, ///< Value w at which to evaluate 220 double x, ///< Value x at which to evaluate 221 double y, ///< Value y at which to evaluate 222 double z, ///< Value z at which to evaluate 223 const psDPolynomial4D *myPoly ///< Coefficients for the polynomial 224 ); 225 226 /* \} */ // End of MathGroup Functions 225 double psDPolynomial4DEval(double w, // /< Value w at which to evaluate 226 double x, // /< Value x at which to evaluate 227 double y, // /< Value y at which to evaluate 228 double z, // /< Value z at which to evaluate 229 const psDPolynomial4D * myPoly // /< Coefficients for the polynomial 230 ); 231 232 /* \} */// End of MathGroup Functions 227 233 228 234 #endif -
trunk/psLib/src/math/psStats.c
r1406 r1407 1 1 2 /** @file psStats.c 2 3 * \brief basic statistical operations … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.5 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.52 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 21 22 #include <float.h> 22 23 #include <math.h> 24 23 25 /*****************************************************************************/ 26 24 27 /* INCLUDE FILES */ 28 25 29 /*****************************************************************************/ 26 30 #include "psMemory.h" … … 35 39 36 40 /*****************************************************************************/ 41 37 42 /* DEFINE STATEMENTS */ 43 38 44 /*****************************************************************************/ 39 45 // will use robust statistical methods. 40 #define GAUSS_WIDTH 20 // The width of the Gaussian or boxcar smoothing.46 #define GAUSS_WIDTH 20 // The width of the Gaussian or boxcar smoothing. 41 47 #define CLIPPED_NUM_ITER_LB 1 42 48 #define CLIPPED_NUM_ITER_UB 10 … … 48 54 #define MAX_ITERATIONS 10 49 55 50 void p_psVectorRobustStats( const psVector *restrict myVector, 51 const psVector *restrict maskVector, 52 unsigned int maskVal, 53 psStats *stats ); 56 void p_psVectorRobustStats(const psVector * restrict myVector, 57 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats); 54 58 55 59 /** Preprocessor macro to generate error on an incorrect type */ … … 83 87 printf("\n"); \ 84 88 89 85 90 /*****************************************************************************/ 91 86 92 /* TYPE DEFINITIONS */ 93 87 94 /*****************************************************************************/ 88 95 89 96 /*****************************************************************************/ 97 90 98 /* GLOBAL VARIABLES */ 99 91 100 /*****************************************************************************/ 92 101 … … 94 103 95 104 /*****************************************************************************/ 105 96 106 /* FILE STATIC VARIABLES */ 107 97 108 /*****************************************************************************/ 98 109 … … 100 111 101 112 /*****************************************************************************/ 113 102 114 /* FUNCTION IMPLEMENTATION - LOCAL */ 115 103 116 /*****************************************************************************/ 104 117 105 bool p_psGetStatValue( const psStats* stats, double* value ) 106 { 107 108 switch ( stats->options & 109 ~ ( PS_STAT_USE_RANGE | PS_STAT_USE_BINSIZE | PS_STAT_ROBUST_FOR_SAMPLE ) ) { 118 bool p_psGetStatValue(const psStats * stats, double *value) 119 { 120 121 switch (stats->options & ~(PS_STAT_USE_RANGE | PS_STAT_USE_BINSIZE | PS_STAT_ROBUST_FOR_SAMPLE)) { 110 122 case PS_STAT_SAMPLE_MEAN: 111 123 *value = stats->sampleMean; … … 163 175 *****************************************************************************/ 164 176 165 void p_psVectorPrint( psVector *myVector, 166 psVector *maskVector, 167 unsigned int maskVal, 168 psStats *stats ) 169 { 170 int i = 0; // Loop index variable. 171 172 for ( i = 0;i < myVector->n;i++ ) { 173 if ( maskVector != NULL ) 174 printf( "Element %d is %f (mask is %d)\n", i, myVector->data.F32[ i ], maskVector->data.U8[ i ] ); 177 void p_psVectorPrint(psVector * myVector, psVector * maskVector, unsigned int maskVal, psStats * stats) 178 { 179 int i = 0; // Loop index variable. 180 181 for (i = 0; i < myVector->n; i++) { 182 if (maskVector != NULL) 183 printf("Element %d is %f (mask is %d)\n", i, myVector->data.F32[i], maskVector->data.U8[i]); 175 184 else 176 printf( "Element %d is %f\n", i, myVector->data.F32[ i ]);185 printf("Element %d is %f\n", i, myVector->data.F32[i]); 177 186 } 178 187 } … … 195 204 *****************************************************************************/ 196 205 197 198 206 /****************************************************************************** 199 207 p_psVectorSampleMean(myVector, maskVector, maskVal, stats): calculates the … … 210 218 *****************************************************************************/ 211 219 212 void p_psVectorSampleMean( const psVector *restrict myVector, 213 const psVector *restrict maskVector, 214 unsigned int maskVal, 215 psStats *stats ) 216 { 217 int i = 0; // Loop index variable 218 float mean = 0.0; // The mean 219 int count = 0; // # of points in this mean? 220 float rangeMin = 0.0; // Exclude data below this 221 float rangeMax = 0.0; // Exclude date above this 220 void p_psVectorSampleMean(const psVector * restrict myVector, 221 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 222 { 223 int i = 0; // Loop index variable 224 float mean = 0.0; // The mean 225 int count = 0; // # of points in this mean? 226 float rangeMin = 0.0; // Exclude data below this 227 float rangeMax = 0.0; // Exclude date above this 222 228 223 229 // If PS_STAT_USE_RANGE is requested, then we enter a slightly different 224 230 // loop. 225 if ( stats->options & PS_STAT_USE_RANGE) {231 if (stats->options & PS_STAT_USE_RANGE) { 226 232 rangeMin = stats->min; 227 233 rangeMax = stats->max; 228 if ( maskVector != NULL) {229 for ( i = 0;i < myVector->n;i++) {234 if (maskVector != NULL) { 235 for (i = 0; i < myVector->n; i++) { 230 236 // Check if the data is with the specified range 231 if ( !( maskVal & maskVector->data.U8[ i ] ) && 232 ( rangeMin <= myVector->data.F32[ i ] ) && 233 ( myVector->data.F32[ i ] <= rangeMax ) ) { 234 mean += myVector->data.F32[ i ]; 237 if (!(maskVal & maskVector->data.U8[i]) && 238 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 239 mean += myVector->data.F32[i]; 235 240 count++; 236 241 } 237 242 } 238 mean /= ( float )count;243 mean /= (float)count; 239 244 } else { 240 for ( i = 0;i < myVector->n;i++ ) { 241 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 242 ( myVector->data.F32[ i ] <= rangeMax ) ) { 243 mean += myVector->data.F32[ i ]; 245 for (i = 0; i < myVector->n; i++) { 246 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 247 mean += myVector->data.F32[i]; 244 248 count++; 245 249 } 246 250 } 247 mean /= ( float )count;251 mean /= (float)count; 248 252 } 249 253 } else { 250 if ( maskVector != NULL) {251 for ( i = 0;i < myVector->n;i++) {252 if ( !( maskVal & maskVector->data.U8[ i ] )) {253 mean += myVector->data.F32[ i];254 if (maskVector != NULL) { 255 for (i = 0; i < myVector->n; i++) { 256 if (!(maskVal & maskVector->data.U8[i])) { 257 mean += myVector->data.F32[i]; 254 258 count++; 255 259 } 256 260 } 257 mean /= ( float )count;261 mean /= (float)count; 258 262 } else { 259 for ( i = 0;i < myVector->n;i++) {260 mean += myVector->data.F32[ i];261 } 262 mean /= ( float )myVector->n;263 for (i = 0; i < myVector->n; i++) { 264 mean += myVector->data.F32[i]; 265 } 266 mean /= (float)myVector->n; 263 267 } 264 268 } … … 278 282 NULL 279 283 *****************************************************************************/ 280 void p_psVectorMax( const psVector *restrict myVector, 281 const psVector *restrict maskVector, 282 unsigned int maskVal, 283 psStats *stats ) 284 { 285 int i = 0; // Loop index variable 286 float max = -MY_MAX_FLOAT; // The calculated maximum 287 float rangeMin = 0.0; // Exclude data below this 288 float rangeMax = 0.0; // Exclude date above this 284 void p_psVectorMax(const psVector * restrict myVector, 285 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 286 { 287 int i = 0; // Loop index variable 288 float max = -MY_MAX_FLOAT; // The calculated maximum 289 float rangeMin = 0.0; // Exclude data below this 290 float rangeMax = 0.0; // Exclude date above this 289 291 290 292 // If PS_STAT_USE_RANGE is requested, then we enter a different loop. 291 if ( stats->options & PS_STAT_USE_RANGE) {293 if (stats->options & PS_STAT_USE_RANGE) { 292 294 rangeMin = stats->min; 293 295 rangeMax = stats->max; 294 if ( maskVector != NULL ) { 295 for ( i = 0;i < myVector->n;i++ ) { 296 if ( !( maskVal & maskVector->data.U8[ i ] ) ) { 297 if ( ( myVector->data.F32[ i ] > max ) && 298 ( rangeMin <= myVector->data.F32[ i ] ) && 299 ( myVector->data.F32[ i ] <= rangeMax ) ) { 300 max = myVector->data.F32[ i ]; 296 if (maskVector != NULL) { 297 for (i = 0; i < myVector->n; i++) { 298 if (!(maskVal & maskVector->data.U8[i])) { 299 if ((myVector->data.F32[i] > max) && 300 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 301 max = myVector->data.F32[i]; 301 302 } 302 303 } 303 304 } 304 305 } else { 305 for ( i = 0;i < myVector->n;i++ ) { 306 if ( ( myVector->data.F32[ i ] > max ) && 307 ( rangeMin <= myVector->data.F32[ i ] ) && 308 ( myVector->data.F32[ i ] <= rangeMax ) ) { 309 max = myVector->data.F32[ i ]; 306 for (i = 0; i < myVector->n; i++) { 307 if ((myVector->data.F32[i] > max) && 308 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 309 max = myVector->data.F32[i]; 310 310 } 311 311 } 312 312 } 313 313 } else { 314 if ( maskVector != NULL) {315 for ( i = 0;i < myVector->n;i++) {316 if ( !( maskVal & maskVector->data.U8[ i ] )) {317 if ( myVector->data.F32[ i ] > max) {318 max = myVector->data.F32[ i];314 if (maskVector != NULL) { 315 for (i = 0; i < myVector->n; i++) { 316 if (!(maskVal & maskVector->data.U8[i])) { 317 if (myVector->data.F32[i] > max) { 318 max = myVector->data.F32[i]; 319 319 } 320 320 } 321 321 } 322 322 } else { 323 for ( i = 0;i < myVector->n;i++) {324 if ( myVector->data.F32[ i ] > max) {325 max = myVector->data.F32[ i];323 for (i = 0; i < myVector->n; i++) { 324 if (myVector->data.F32[i] > max) { 325 max = myVector->data.F32[i]; 326 326 } 327 327 } … … 343 343 NULL 344 344 *****************************************************************************/ 345 void p_psVectorMin( const psVector *restrict myVector, 346 const psVector *restrict maskVector, 347 unsigned int maskVal, 348 psStats *stats ) 349 { 350 int i = 0; // Loop index variable 351 float min = MY_MAX_FLOAT; // The calculated maximum 352 float rangeMin = 0.0; // Exclude data below this 353 float rangeMax = 0.0; // Exclude date above this 354 355 if ( stats->options & PS_STAT_USE_RANGE ) { 345 void p_psVectorMin(const psVector * restrict myVector, 346 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 347 { 348 int i = 0; // Loop index variable 349 float min = MY_MAX_FLOAT; // The calculated maximum 350 float rangeMin = 0.0; // Exclude data below this 351 float rangeMax = 0.0; // Exclude date above this 352 353 if (stats->options & PS_STAT_USE_RANGE) { 356 354 rangeMin = stats->min; 357 355 rangeMax = stats->max; 358 if ( maskVector != NULL ) { 359 for ( i = 0;i < myVector->n;i++ ) { 360 if ( !( maskVal & maskVector->data.U8[ i ] ) ) { 361 if ( ( myVector->data.F32[ i ] < min ) && 362 ( rangeMin <= myVector->data.F32[ i ] ) && 363 ( myVector->data.F32[ i ] <= rangeMax ) ) { 364 min = myVector->data.F32[ i ]; 356 if (maskVector != NULL) { 357 for (i = 0; i < myVector->n; i++) { 358 if (!(maskVal & maskVector->data.U8[i])) { 359 if ((myVector->data.F32[i] < min) && 360 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 361 min = myVector->data.F32[i]; 365 362 } 366 363 } 367 364 } 368 365 } else { 369 for ( i = 0;i < myVector->n;i++ ) { 370 if ( ( myVector->data.F32[ i ] < min ) && 371 ( rangeMin <= myVector->data.F32[ i ] ) && 372 ( myVector->data.F32[ i ] <= rangeMax ) ) { 373 min = myVector->data.F32[ i ]; 366 for (i = 0; i < myVector->n; i++) { 367 if ((myVector->data.F32[i] < min) && 368 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 369 min = myVector->data.F32[i]; 374 370 } 375 371 } 376 372 } 377 373 } else { 378 if ( maskVector != NULL) {379 for ( i = 0;i < myVector->n;i++) {380 if ( !( maskVal & maskVector->data.U8[ i ] )) {381 if ( myVector->data.F32[ i ] < min) {382 min = myVector->data.F32[ i];374 if (maskVector != NULL) { 375 for (i = 0; i < myVector->n; i++) { 376 if (!(maskVal & maskVector->data.U8[i])) { 377 if (myVector->data.F32[i] < min) { 378 min = myVector->data.F32[i]; 383 379 } 384 380 } 385 381 } 386 382 } else { 387 for ( i = 0;i < myVector->n;i++) {388 if ( myVector->data.F32[ i ] < min) {389 min = myVector->data.F32[ i];383 for (i = 0; i < myVector->n; i++) { 384 if (myVector->data.F32[i] < min) { 385 min = myVector->data.F32[i]; 390 386 } 391 387 } … … 408 404 NULL 409 405 *****************************************************************************/ 410 int p_psVectorNValues( const psVector *restrict myVector, 411 const psVector *restrict maskVector, 412 unsigned int maskVal, 413 psStats *stats ) 414 { 415 int i = 0; // Loop index variable 416 int numData = 0; // The number of data points 417 float rangeMin = 0.0; // Exclude data below this 418 float rangeMax = 0.0; // Exclude date above this 419 420 if ( stats->options & PS_STAT_USE_RANGE ) { 406 int p_psVectorNValues(const psVector * restrict myVector, 407 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 408 { 409 int i = 0; // Loop index variable 410 int numData = 0; // The number of data points 411 float rangeMin = 0.0; // Exclude data below this 412 float rangeMax = 0.0; // Exclude date above this 413 414 if (stats->options & PS_STAT_USE_RANGE) { 421 415 rangeMin = stats->min; 422 416 rangeMax = stats->max; 423 if ( maskVector != NULL ) { 424 for ( i = 0;i < myVector->n;i++ ) { 425 if ( !( maskVal & maskVector->data.U8[ i ] ) && 426 ( rangeMin <= myVector->data.F32[ i ] ) && 427 ( myVector->data.F32[ i ] <= rangeMax ) ) { 417 if (maskVector != NULL) { 418 for (i = 0; i < myVector->n; i++) { 419 if (!(maskVal & maskVector->data.U8[i]) && 420 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 428 421 numData++; 429 422 } 430 423 } 431 424 } else { 432 for ( i = 0;i < myVector->n;i++ ) { 433 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 434 ( myVector->data.F32[ i ] <= rangeMax ) ) { 425 for (i = 0; i < myVector->n; i++) { 426 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 435 427 numData++; 436 428 } … … 440 432 rangeMin = stats->min; 441 433 rangeMax = stats->max; 442 if ( maskVector != NULL) {443 for ( i = 0;i < myVector->n;i++) {444 if ( !( maskVal & maskVector->data.U8[ i ] )) {434 if (maskVector != NULL) { 435 for (i = 0; i < myVector->n; i++) { 436 if (!(maskVal & maskVector->data.U8[i])) { 445 437 numData++; 446 438 } … … 450 442 } 451 443 } 452 return ( numData ); 453 } 454 455 444 return (numData); 445 } 456 446 457 447 /****************************************************************************** … … 466 456 NULL 467 457 *****************************************************************************/ 468 void p_psVectorSampleMedian( const psVector *restrict myVector, 469 const psVector *restrict maskVector, 470 unsigned int maskVal, 471 psStats *stats ) 472 { 473 psVector * unsortedVector = NULL; // Temporary vector 474 psVector *sortedVector = NULL; // Temporary vector 475 int i = 0; // Loop index variable 476 int count = 0; // # of points in this mean? 477 int nValues = 0; // # of points in vector 478 float rangeMin = 0.0; // Exclude data below this 479 float rangeMax = 0.0; // Exclude date above this 480 458 void p_psVectorSampleMedian(const psVector * restrict myVector, 459 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 460 { 461 psVector *unsortedVector = NULL; // Temporary vector 462 psVector *sortedVector = NULL; // Temporary vector 463 int i = 0; // Loop index variable 464 int count = 0; // # of points in this mean? 465 int nValues = 0; // # of points in vector 466 float rangeMin = 0.0; // Exclude data below this 467 float rangeMax = 0.0; // Exclude date above this 481 468 482 469 // Determine if the number of data points exceed a threshold which will … … 485 472 // regardless of the vector size. 486 473 /* 487 if (myVector->n > stats->sampleLimit) { 488 psAbort(__func__, "Robust Statistic Algorithms have not yet been defined or implemented."); 489 490 // Calculate the robust quartiles. 491 stats2 = psStatsAlloc(PS_STAT_ROBUST_MEDIAN); 492 p_psVectorRobustStats(myVector, maskVector, maskVal, stats2); 493 494 // Store the robust quartiles into the sample quartile members. 495 stats->sampleMedian = stats2->robustMedian; 496 497 // Free temporary data buffers. 498 psFree(stats2); 499 500 // Set the PS_STAT_ROBUST_FOR_SAMPLE bit in the stats structure. 501 stats->options = stats->options | PS_STAT_ROBUST_FOR_SAMPLE; 502 503 return; 504 } 505 */ 474 * if (myVector->n > stats->sampleLimit) { psAbort(__func__, "Robust Statistic Algorithms have not yet 475 * been defined or implemented."); 476 * 477 * // Calculate the robust quartiles. stats2 = psStatsAlloc(PS_STAT_ROBUST_MEDIAN); 478 * p_psVectorRobustStats(myVector, maskVector, maskVal, stats2); 479 * 480 * // Store the robust quartiles into the sample quartile members. stats->sampleMedian = 481 * stats2->robustMedian; 482 * 483 * // Free temporary data buffers. psFree(stats2); 484 * 485 * // Set the PS_STAT_ROBUST_FOR_SAMPLE bit in the stats structure. stats->options = stats->options | 486 * PS_STAT_ROBUST_FOR_SAMPLE; 487 * 488 * return; } */ 506 489 507 490 // Determine how many data points fit inside this min/max range 508 491 // and are not masked, IF the maskVector is not NULL> 509 nValues = p_psVectorNValues( myVector, maskVector, maskVal, stats);492 nValues = p_psVectorNValues(myVector, maskVector, maskVal, stats); 510 493 511 494 // Allocate temporary vectors for the data. 512 unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32);495 unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 513 496 unsortedVector->n = unsortedVector->nalloc; 514 497 515 sortedVector = psVectorAlloc( nValues, PS_TYPE_F32);498 sortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 516 499 sortedVector->n = sortedVector->nalloc; 517 500 518 501 // Determine if we must only use data points within a min/max range. 519 if ( stats->options & PS_STAT_USE_RANGE) {502 if (stats->options & PS_STAT_USE_RANGE) { 520 503 rangeMin = stats->min; 521 504 rangeMax = stats->max; … … 524 507 // into the temporary vectors. 525 508 count = 0; 526 if ( maskVector != NULL ) { 527 for ( i = 0;i < myVector->n;i++ ) { 528 if ( !( maskVal & maskVector->data.U8[ i ] ) && 529 ( rangeMin <= myVector->data.F32[ i ] ) && 530 ( myVector->data.F32[ i ] <= rangeMax ) ) { 531 unsortedVector->data.F32[ count++ ] = maskVector->data.F32[ i ]; 509 if (maskVector != NULL) { 510 for (i = 0; i < myVector->n; i++) { 511 if (!(maskVal & maskVector->data.U8[i]) && 512 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 513 unsortedVector->data.F32[count++] = maskVector->data.F32[i]; 532 514 } 533 515 } 534 516 } else { 535 for ( i = 0;i < myVector->n;i++ ) { 536 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 537 ( myVector->data.F32[ i ] <= rangeMax ) ) { 538 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 517 for (i = 0; i < myVector->n; i++) { 518 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 519 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 539 520 } 540 521 } … … 543 524 // Store all non-masked data points into the temporary vectors. 544 525 count = 0; 545 if ( maskVector != NULL) {546 for ( i = 0;i < myVector->n;i++) {547 if ( !( maskVal & maskVector->data.U8[ i ] )) {548 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i];526 if (maskVector != NULL) { 527 for (i = 0; i < myVector->n; i++) { 528 if (!(maskVal & maskVector->data.U8[i])) { 529 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 549 530 } 550 531 } 551 532 } else { 552 for ( i = 0;i < myVector->n;i++) {553 unsortedVector->data.F32[ i ] = myVector->data.F32[ i];533 for (i = 0; i < myVector->n; i++) { 534 unsortedVector->data.F32[i] = myVector->data.F32[i]; 554 535 } 555 536 } 556 537 } 557 538 // Sort the temporary vectors. 558 psVectorSort( sortedVector, unsortedVector);539 psVectorSort(sortedVector, unsortedVector); 559 540 560 541 // Calculate the median exactly. 561 542 // XXX: Is this the correct action? 562 if ( 0 == ( nValues % 2 )) {563 stats->sampleMedian = 0.5 * ( sortedVector->data.F32[ ( nValues / 2 ) - 1] +564 sortedVector->data.F32[ nValues / 2 ]);543 if (0 == (nValues % 2)) { 544 stats->sampleMedian = 0.5 * (sortedVector->data.F32[(nValues / 2) - 1] + 545 sortedVector->data.F32[nValues / 2]); 565 546 } else { 566 stats->sampleMedian = sortedVector->data.F32[ nValues / 2];547 stats->sampleMedian = sortedVector->data.F32[nValues / 2]; 567 548 } 568 549 569 550 // Free the temporary data structures. 570 psFree( unsortedVector);571 psFree( sortedVector);551 psFree(unsortedVector); 552 psFree(sortedVector); 572 553 } 573 554 … … 584 565 XXX: use a static variable for gaussianCoefs[] and compute them once. 585 566 *****************************************************************************/ 586 psVector *p_psVectorsmoothHistGaussian( psHistogram *robustHistogram, 587 float sigma ) 588 { 589 int i = 0; // Loop index variable 590 int j = 0; // Loop index variable 591 float denom = 0.0; // Temporary variable 592 float expo = 0.0; // Temporary variable 593 float gaussianCoefs[ 1 + ( 2 * GAUSS_WIDTH ) ]; // The Gaussian Coefficients 594 psVector *smooth = psVectorAlloc( robustHistogram->nums->n, PS_TYPE_F32 ); 595 596 for ( i = 0;i < ( 1 + ( 2 * GAUSS_WIDTH ) );i++ ) { 597 if ( fabs( sigma ) >= FLT_EPSILON ) { 567 psVector *p_psVectorsmoothHistGaussian(psHistogram * robustHistogram, float sigma) 568 { 569 int i = 0; // Loop index variable 570 int j = 0; // Loop index variable 571 float denom = 0.0; // Temporary variable 572 float expo = 0.0; // Temporary variable 573 float gaussianCoefs[1 + (2 * GAUSS_WIDTH)]; // The Gaussian Coefficients 574 psVector *smooth = psVectorAlloc(robustHistogram->nums->n, PS_TYPE_F32); 575 576 for (i = 0; i < (1 + (2 * GAUSS_WIDTH)); i++) { 577 if (fabs(sigma) >= FLT_EPSILON) { 598 578 // If sigma does not equal zero, then we use Gaussian smoothing. 599 579 #ifdef DARWIN 600 denom = ( float ) sqrt( 2.0 * M_PI * sigma * sigma);580 denom = (float)sqrt(2.0 * M_PI * sigma * sigma); 601 581 #else 602 582 603 denom = sqrtf( 2.0 * M_PI * sigma * sigma);583 denom = sqrtf(2.0 * M_PI * sigma * sigma); 604 584 #endif 605 585 606 expo = - ( float ) ( ( i - GAUSS_WIDTH ) * ( i - GAUSS_WIDTH ));607 expo /= ( 2.0 * sigma * sigma);608 gaussianCoefs[ i ] = exp( expo / denom);586 expo = -(float)((i - GAUSS_WIDTH) * (i - GAUSS_WIDTH)); 587 expo /= (2.0 * sigma * sigma); 588 gaussianCoefs[i] = exp(expo / denom); 609 589 610 590 // NOTE: Gaussian smoothing just isn't working with low sigma … … 612 592 // all zero, except for the middle coefficient, which is exactly 613 593 // one. Therefore, I'm using boxcar smoothing. 614 gaussianCoefs[ i ] = 1.0 / ( 1.0 + ( 2.0 * ( float ) GAUSS_WIDTH ));615 // printf("gaussianCoefs[%d] is %f\n", i, gaussianCoefs[i]);594 gaussianCoefs[i] = 1.0 / (1.0 + (2.0 * (float)GAUSS_WIDTH)); 595 // printf("gaussianCoefs[%d] is %f\n", i, gaussianCoefs[i]); 616 596 } else { 617 /* If sigma equals zero (all pixels have the same value) 618 * the above code will divide by zero. Therefore, we don't need 619 * to smooth the data. 620 */ 621 for ( i = 0;i < robustHistogram->nums->n;i++ ) { 622 smooth->data.F32[ i ] = ( float ) robustHistogram->nums->data.S32[ i ]; 623 } 624 return ( smooth ); 597 /* If sigma equals zero (all pixels have the same value) the above code will divide by zero. 598 * Therefore, we don't need to smooth the data. */ 599 for (i = 0; i < robustHistogram->nums->n; i++) { 600 smooth->data.F32[i] = (float)robustHistogram->nums->data.S32[i]; 601 } 602 return (smooth); 625 603 } 626 604 } 627 605 628 606 // Perform the actual smoothing. 629 for ( i = 0;i < robustHistogram->nums->n;i++) {630 smooth->data.F32[ i] = 0.0;631 for ( j = -GAUSS_WIDTH;j <= + GAUSS_WIDTH;j++) {632 if ( ( ( j + i ) >= 0 ) && ( ( j + i ) < smooth->n )) {633 smooth->data.F32[ i ] += ( gaussianCoefs[ j + GAUSS_WIDTH] *634 ( float ) robustHistogram->nums->data.S32[ j + i ]);635 } 636 } 637 } 638 return ( smooth);607 for (i = 0; i < robustHistogram->nums->n; i++) { 608 smooth->data.F32[i] = 0.0; 609 for (j = -GAUSS_WIDTH; j <= +GAUSS_WIDTH; j++) { 610 if (((j + i) >= 0) && ((j + i) < smooth->n)) { 611 smooth->data.F32[i] += (gaussianCoefs[j + GAUSS_WIDTH] * 612 (float)robustHistogram->nums->data.S32[j + i]); 613 } 614 } 615 } 616 return (smooth); 639 617 } 640 618 … … 650 628 NULL 651 629 *****************************************************************************/ 652 void p_psVectorSampleQuartiles( const psVector *restrict myVector, 653 const psVector *restrict maskVector, 654 unsigned int maskVal, 655 psStats *stats ) 656 { 657 psVector * unsortedVector = NULL; // Temporary vector 658 psVector *sortedVector = NULL; // Temporary vector 659 int i = 0; // Loop index variable 660 int count = 0; // # of points in this mean? 661 int nValues = 0; // # data points 662 float rangeMin = 0.0; // Exclude data below this 663 float rangeMax = 0.0; // Exclude date above this 630 void p_psVectorSampleQuartiles(const psVector * restrict myVector, 631 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 632 { 633 psVector *unsortedVector = NULL; // Temporary vector 634 psVector *sortedVector = NULL; // Temporary vector 635 int i = 0; // Loop index variable 636 int count = 0; // # of points in this mean? 637 int nValues = 0; // # data points 638 float rangeMin = 0.0; // Exclude data below this 639 float rangeMax = 0.0; // Exclude date above this 664 640 665 641 // Determine how many data points fit inside this min/max range 666 642 // and are not maxed, IF the maskVector is not NULL> 667 nValues = p_psVectorNValues( myVector, maskVector, maskVal, stats);643 nValues = p_psVectorNValues(myVector, maskVector, maskVal, stats); 668 644 669 645 // Allocate temporary vectors for the data. 670 unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32);646 unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 671 647 unsortedVector->n = unsortedVector->nalloc; 672 sortedVector = psVectorAlloc( nValues, PS_TYPE_F32);648 sortedVector = psVectorAlloc(nValues, PS_TYPE_F32); 673 649 sortedVector->n = sortedVector->nalloc; 674 650 675 651 // Determine if we must only use data points within a min/max range. 676 if ( stats->options & PS_STAT_USE_RANGE) {652 if (stats->options & PS_STAT_USE_RANGE) { 677 653 rangeMin = stats->min; 678 654 rangeMax = stats->max; … … 680 656 // into the temporary vectors. 681 657 count = 0; 682 if ( maskVector != NULL ) { 683 for ( i = 0;i < myVector->n;i++ ) { 684 if ( !( maskVal & maskVector->data.U8[ i ] ) && 685 ( rangeMin <= myVector->data.F32[ i ] ) && 686 ( myVector->data.F32[ i ] <= rangeMax ) ) { 687 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 658 if (maskVector != NULL) { 659 for (i = 0; i < myVector->n; i++) { 660 if (!(maskVal & maskVector->data.U8[i]) && 661 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 662 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 688 663 } 689 664 } 690 665 } else { 691 for ( i = 0;i < myVector->n;i++ ) { 692 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 693 ( myVector->data.F32[ i ] <= rangeMax ) ) { 694 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i ]; 666 for (i = 0; i < myVector->n; i++) { 667 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 668 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 695 669 } 696 670 } … … 699 673 // Store all non-masked data points into the temporary vectors. 700 674 count = 0; 701 if ( maskVector != NULL) {702 for ( i = 0;i < myVector->n;i++) {703 if ( !( maskVal & maskVector->data.U8[ i ] )) {704 unsortedVector->data.F32[ count++ ] = myVector->data.F32[ i];675 if (maskVector != NULL) { 676 for (i = 0; i < myVector->n; i++) { 677 if (!(maskVal & maskVector->data.U8[i])) { 678 unsortedVector->data.F32[count++] = myVector->data.F32[i]; 705 679 } 706 680 } 707 681 } else { 708 for ( i = 0;i < myVector->n;i++) {709 unsortedVector->data.F32[ i ] = myVector->data.F32[ i];682 for (i = 0; i < myVector->n; i++) { 683 unsortedVector->data.F32[i] = myVector->data.F32[i]; 710 684 } 711 685 } … … 713 687 714 688 // Sort the temporary vectors. 715 psVectorSort( sortedVector, unsortedVector);689 psVectorSort(sortedVector, unsortedVector); 716 690 717 691 // Calculate the quartile points exactly. 718 stats->sampleUQ = sortedVector->data.F32[ 3 * ( nValues / 4 )];719 stats->sampleLQ = sortedVector->data.F32[ nValues / 4];692 stats->sampleUQ = sortedVector->data.F32[3 * (nValues / 4)]; 693 stats->sampleLQ = sortedVector->data.F32[nValues / 4]; 720 694 721 695 // Free the temporary data structures. 722 psFree( unsortedVector ); 723 psFree( sortedVector ); 724 } 725 696 psFree(unsortedVector); 697 psFree(sortedVector); 698 } 726 699 727 700 /****************************************************************************** … … 737 710 738 711 *****************************************************************************/ 739 void p_psVectorSampleStdev( const psVector *restrict myVector, 740 const psVector *restrict maskVector, 741 unsigned int maskVal, 742 psStats *stats ) 743 { 744 int i = 0; // Loop index variable 745 int countInt = 0; // # of data points being used 746 float countFloat = 0.0; // # of data points being used 747 float mean = 0.0; // The mean 748 float diff = 0.0; // Used in calculating stdev 749 float sumSquares = 0.0; // temporary variable 750 float sumDiffs = 0.0; // temporary variable 751 float rangeMin = 0.0; // Exclude data below this 752 float rangeMax = 0.0; // Exclude date above this 712 void p_psVectorSampleStdev(const psVector * restrict myVector, 713 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 714 { 715 int i = 0; // Loop index variable 716 int countInt = 0; // # of data points being used 717 float countFloat = 0.0; // # of data points being used 718 float mean = 0.0; // The mean 719 float diff = 0.0; // Used in calculating stdev 720 float sumSquares = 0.0; // temporary variable 721 float sumDiffs = 0.0; // temporary variable 722 float rangeMin = 0.0; // Exclude data below this 723 float rangeMax = 0.0; // Exclude date above this 753 724 754 725 // This procedure requires the mean. If it has not been already 755 726 // calculated, then call p_psVectorSampleMean() 756 if ( 0 != isnan( stats->sampleMean )) {757 p_psVectorSampleMean( myVector, maskVector, maskVal, stats);727 if (0 != isnan(stats->sampleMean)) { 728 p_psVectorSampleMean(myVector, maskVector, maskVal, stats); 758 729 } 759 730 mean = stats->sampleMean; 760 731 761 if ( stats->options & PS_STAT_USE_RANGE ) { 762 if ( maskVector != NULL ) { 763 for ( i = 0;i < myVector->n;i++ ) { 764 if ( !( maskVal & maskVector->data.U8[ i ] ) && 765 ( rangeMin <= myVector->data.F32[ i ] ) && 766 ( myVector->data.F32[ i ] <= rangeMax ) ) { 767 diff = myVector->data.F32[ i ] - mean; 768 sumSquares += ( diff * diff ); 732 if (stats->options & PS_STAT_USE_RANGE) { 733 if (maskVector != NULL) { 734 for (i = 0; i < myVector->n; i++) { 735 if (!(maskVal & maskVector->data.U8[i]) && 736 (rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 737 diff = myVector->data.F32[i] - mean; 738 sumSquares += (diff * diff); 769 739 sumDiffs += diff; 770 740 countInt++; … … 772 742 } 773 743 } else { 774 for ( i = 0;i < myVector->n;i++ ) { 775 if ( ( rangeMin <= myVector->data.F32[ i ] ) && 776 ( myVector->data.F32[ i ] <= rangeMax ) ) { 777 diff = myVector->data.F32[ i ] - mean; 778 sumSquares += ( diff * diff ); 744 for (i = 0; i < myVector->n; i++) { 745 if ((rangeMin <= myVector->data.F32[i]) && (myVector->data.F32[i] <= rangeMax)) { 746 diff = myVector->data.F32[i] - mean; 747 sumSquares += (diff * diff); 779 748 sumDiffs += diff; 780 749 countInt++; … … 784 753 } 785 754 } else { 786 if ( maskVector != NULL) {787 for ( i = 0;i < myVector->n;i++) {788 if ( !( maskVal & maskVector->data.U8[ i ] )) {789 diff = myVector->data.F32[ i] - mean;790 sumSquares += ( diff * diff);755 if (maskVector != NULL) { 756 for (i = 0; i < myVector->n; i++) { 757 if (!(maskVal & maskVector->data.U8[i])) { 758 diff = myVector->data.F32[i] - mean; 759 sumSquares += (diff * diff); 791 760 sumDiffs += diff; 792 761 countInt++; … … 794 763 } 795 764 } else { 796 for ( i = 0;i < myVector->n;i++) {797 diff = myVector->data.F32[ i] - mean;798 sumSquares += ( diff * diff);765 for (i = 0; i < myVector->n; i++) { 766 diff = myVector->data.F32[i] - mean; 767 sumSquares += (diff * diff); 799 768 sumDiffs += diff; 800 769 countInt++; … … 803 772 } 804 773 } 805 countFloat = ( float )countInt;774 countFloat = (float)countInt; 806 775 807 776 #ifdef DARWIN 808 777 809 stats->sampleStdev = ( float ) sqrt( ( sumSquares - ( sumDiffs * 810 sumDiffs / countFloat ) ) / ( countFloat - 1 ) ); 778 stats->sampleStdev = (float)sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 811 779 #else 812 780 813 stats->sampleStdev = sqrtf( ( sumSquares - ( sumDiffs * 814 sumDiffs / countFloat ) ) / ( countFloat - 1 ) ); 781 stats->sampleStdev = sqrtf((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 815 782 #endif 816 783 } … … 828 795 NULL 829 796 *****************************************************************************/ 830 void p_psVectorClippedStats( const psVector *restrict myVector, 831 const psVector *restrict maskVector, 832 unsigned int maskVal, 833 psStats *stats ) 834 { 835 int i = 0; // Loop index variable 836 int j = 0; // Loop index variable 837 float clippedMean = 0.0; // self-explanatory 838 float clippedStdev = 0.0; // self-explanatory 839 float oldStanMean = 0.0; // Temporary variable 840 float oldStanStdev = 0.0; // Temporary variable 841 psVector *tmpMask = NULL; // Temporary vector 797 void p_psVectorClippedStats(const psVector * restrict myVector, 798 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 799 { 800 int i = 0; // Loop index variable 801 int j = 0; // Loop index variable 802 float clippedMean = 0.0; // self-explanatory 803 float clippedStdev = 0.0; // self-explanatory 804 float oldStanMean = 0.0; // Temporary variable 805 float oldStanStdev = 0.0; // Temporary variable 806 psVector *tmpMask = NULL; // Temporary vector 842 807 843 808 // Endure that stats->clipIter is within the proper range. 844 if ( !( ( CLIPPED_NUM_ITER_LB <= stats->clipIter ) && 845 ( stats->clipIter <= CLIPPED_NUM_ITER_UB ) ) ) { 846 psAbort( __func__, "Unallowed value for clipIter (%d).\n", 847 stats->clipIter ); 848 } 849 809 if (!((CLIPPED_NUM_ITER_LB <= stats->clipIter) && (stats->clipIter <= CLIPPED_NUM_ITER_UB))) { 810 psAbort(__func__, "Unallowed value for clipIter (%d).\n", stats->clipIter); 811 } 850 812 // Endure that stats->clipSigma is within the proper range. 851 if ( !( ( CLIPPED_SIGMA_LB <= stats->clipSigma ) && 852 ( stats->clipSigma <= CLIPPED_SIGMA_UB ) ) ) { 853 psAbort( __func__, "Unallowed value for clipSigma (%f).\n", 854 stats->clipSigma ); 855 } 856 813 if (!((CLIPPED_SIGMA_LB <= stats->clipSigma) && (stats->clipSigma <= CLIPPED_SIGMA_UB))) { 814 psAbort(__func__, "Unallowed value for clipSigma (%f).\n", stats->clipSigma); 815 } 857 816 // We allocate a temporary mask vector since during the iterative 858 817 // steps that follow, we will be masking off additional data points. 859 818 // However, we do no want to modify the original mask vector. 860 tmpMask = psVectorAlloc( myVector->n, PS_TYPE_U8);819 tmpMask = psVectorAlloc(myVector->n, PS_TYPE_U8); 861 820 tmpMask->n = myVector->n; 862 821 863 822 // If we were called with a mask vector, then initialize the temporary 864 823 // mask vector with those values. 865 if ( maskVector != NULL ) { 866 for ( i = 0;i < tmpMask->n;i++ ) { 867 tmpMask->data.U8[ i ] = maskVector->data.U8[ i ]; 868 } 869 } 870 824 if (maskVector != NULL) { 825 for (i = 0; i < tmpMask->n; i++) { 826 tmpMask->data.U8[i] = maskVector->data.U8[i]; 827 } 828 } 871 829 // 1. Compute the sample median. 872 830 // NOTE: This seems odd. Verify with IfA that we want to calculate the 873 831 // median here, not the mean. 874 p_psVectorSampleMedian( myVector, maskVector, maskVal, stats);832 p_psVectorSampleMedian(myVector, maskVector, maskVal, stats); 875 833 876 834 // 2. Compute the sample standard deviation. 877 p_psVectorSampleStdev( myVector, maskVector, maskVal, stats);835 p_psVectorSampleStdev(myVector, maskVector, maskVal, stats); 878 836 879 837 // 3. Use the sample median as the first estimator of the mean X. … … 889 847 890 848 // 5. Repeat N times: 891 for ( i = 0;i < stats->clipIter;i++) {892 for ( j = 0;j < myVector->n;j++) {849 for (i = 0; i < stats->clipIter; i++) { 850 for (j = 0; j < myVector->n; j++) { 893 851 // a) Exclude all values x_i for which |x_i - x| > K * stdev 894 if ( fabs( myVector->data.F32[ j ] - clippedMean ) > 895 ( stats->clipSigma * clippedStdev ) ) { 896 tmpMask->data.U8[ i ] = 0xff; 852 if (fabs(myVector->data.F32[j] - clippedMean) > (stats->clipSigma * clippedStdev)) { 853 tmpMask->data.U8[i] = 0xff; 897 854 } 898 855 // b) compute new mean and stdev 899 p_psVectorSampleMedian( myVector, tmpMask, maskVal, stats);900 p_psVectorSampleStdev( myVector, tmpMask, maskVal, stats);856 p_psVectorSampleMedian(myVector, tmpMask, maskVal, stats); 857 p_psVectorSampleStdev(myVector, tmpMask, maskVal, stats); 901 858 902 859 // c) Use the new mean for x … … 912 869 913 870 // 7. The last calcuated value of x is the cliped mean. 914 if ( stats->options & PS_STAT_CLIPPED_MEAN) {871 if (stats->options & PS_STAT_CLIPPED_MEAN) { 915 872 stats->clippedMean = clippedMean; 916 873 } 917 918 874 // 8. The last calcuated value of stdev is the cliped stdev. 919 if ( stats->options & PS_STAT_CLIPPED_STDEV) {875 if (stats->options & PS_STAT_CLIPPED_STDEV) { 920 876 stats->clippedStdev = clippedStdev; 921 877 } 922 878 923 psFree( tmpMask);879 psFree(tmpMask); 924 880 } 925 881 … … 928 884 elements of a vector to a range between 0.0 and 1.0. 929 885 *****************************************************************************/ 930 void p_psNormalizeVector( psVector *myData)931 { 932 float min = ( float )HUGE;933 float max = ( float ) -HUGE;886 void p_psNormalizeVector(psVector * myData) 887 { 888 float min = (float)HUGE; 889 float max = (float)-HUGE; 934 890 float range = 0.0; 935 891 int i = 0; 936 892 937 for ( i = 0;i < myData->n;i++) {938 if ( myData->data.F32[ i ] < min) {939 min = myData->data.F32[ i];940 } 941 if ( myData->data.F32[ i ] > max) {942 max = myData->data.F32[ i];893 for (i = 0; i < myData->n; i++) { 894 if (myData->data.F32[i] < min) { 895 min = myData->data.F32[i]; 896 } 897 if (myData->data.F32[i] > max) { 898 max = myData->data.F32[i]; 943 899 } 944 900 } 945 901 946 902 range = max - min; 947 for ( i = 0;i < myData->n;i++ ) { 948 myData->data.F32[ i ] = ( myData->data.F32[ i ] - min ) / range; 949 } 950 } 951 903 for (i = 0; i < myData->n; i++) { 904 myData->data.F32[i] = (myData->data.F32[i] - min) / range; 905 } 906 } 952 907 953 908 /***************************************************************************** … … 956 911 specified data point. 957 912 *****************************************************************************/ 958 float p_psGaussian( const psVector *restrict myData,959 const psVector *restrict myParams ) 960 { 961 float x = myData->data.F32[ 0];962 float mean = myParams->data.F32[ 0];963 float stdev = myParams->data.F32[ 1 ];964 float tmp = exp( -( ( x - mean ) * ( x - mean ) ) / ( 2.0 * stdev * stdev ) ); 965 tmp /= ( ( float ) sqrt( 2.0 * M_PI * ( stdev * stdev ) ));966 967 // printf("p_psGaussian((%.2f), %.2f, %.2f) is %.2f\n", x, mean, stdev, tmp);968 return ( tmp);913 float p_psGaussian(const psVector * restrict myData, const psVector * restrict myParams) 914 { 915 float x = myData->data.F32[0]; 916 float mean = myParams->data.F32[0]; 917 float stdev = myParams->data.F32[1]; 918 float tmp = exp(-((x - mean) * (x - mean)) / (2.0 * stdev * stdev)); 919 920 tmp /= ((float)sqrt(2.0 * M_PI * (stdev * stdev))); 921 922 // printf("p_psGaussian((%.2f), %.2f, %.2f) is %.2f\n", x, mean, stdev, tmp); 923 return (tmp); 969 924 } 970 925 … … 973 928 calculates the specified partial derivative of the above Gaussian function. 974 929 *****************************************************************************/ 975 float p_psGaussianDeriv( const psVector *restrict myData, 976 const psVector *restrict myParams, 977 int whichParam ) 978 { 979 float x = myData->data.F32[ 0 ]; 980 float mean = myParams->data.F32[ 0 ]; 981 float stdev = myParams->data.F32[ 1 ]; 930 float p_psGaussianDeriv(const psVector * restrict myData, const psVector * restrict myParams, int whichParam) 931 { 932 float x = myData->data.F32[0]; 933 float mean = myParams->data.F32[0]; 934 float stdev = myParams->data.F32[1]; 982 935 float tmp = 0.0; 983 936 984 if ( whichParam == 0) {937 if (whichParam == 0) { 985 938 // Return the derivative w.r.t. the mean. 986 tmp = ( x - mean ) * p_psGaussian( myData, myParams ); 987 tmp /= ( stdev * stdev ); 988 } else 989 if ( whichParam == 1 ) { 990 // Return the derivative w.r.t. the stdev. 991 tmp = ( x - mean ) * ( x - mean ) * p_psGaussian( myData, myParams ); 992 tmp /= ( stdev * stdev * stdev ); 993 } 994 printf( "p_psGaussianDeriv((%.2f), %.2f, %.2f, (%d)) is %.2f\n", x, mean, stdev, whichParam, tmp ); 995 996 return ( tmp ); 997 } 998 939 tmp = (x - mean) * p_psGaussian(myData, myParams); 940 tmp /= (stdev * stdev); 941 } else if (whichParam == 1) { 942 // Return the derivative w.r.t. the stdev. 943 tmp = (x - mean) * (x - mean) * p_psGaussian(myData, myParams); 944 tmp /= (stdev * stdev * stdev); 945 } 946 printf("p_psGaussianDeriv((%.2f), %.2f, %.2f, (%d)) is %.2f\n", x, mean, stdev, whichParam, tmp); 947 948 return (tmp); 949 } 999 950 1000 951 /***************************************************************************** … … 1003 954 specified data point. 1004 955 *****************************************************************************/ 1005 float p_psQuadratic( const psVector *restrict myParams, 1006 const psVector *restrict myCoords ) 1007 { 1008 float x = myCoords->data.F32[ 0 ]; 1009 float A = myParams->data.F32[ 0 ]; 1010 float B = myParams->data.F32[ 1 ]; 1011 float C = myParams->data.F32[ 2 ]; 956 float p_psQuadratic(const psVector * restrict myParams, const psVector * restrict myCoords) 957 { 958 float x = myCoords->data.F32[0]; 959 float A = myParams->data.F32[0]; 960 float B = myParams->data.F32[1]; 961 float C = myParams->data.F32[2]; 1012 962 float tmp = 0.0; 1013 963 1014 tmp = ( A * x * x ) + ( B * x) + C;1015 return ( tmp);964 tmp = (A * x * x) + (B * x) + C; 965 return (tmp); 1016 966 } 1017 967 … … 1020 970 calculates the specified partial derivative of the above quadratic function. 1021 971 *****************************************************************************/ 1022 float p_psQuadraticDeriv( const psVector *restrict myParams, 1023 const psVector *restrict myCoords, 1024 int whichParamDeriv ) 1025 { 1026 float x = myCoords->data.F32[ 0 ]; 972 float p_psQuadraticDeriv(const psVector * restrict myParams, 973 const psVector * restrict myCoords, int whichParamDeriv) 974 { 975 float x = myCoords->data.F32[0]; 1027 976 float tmp = 0.0; 1028 977 1029 if ( whichParamDeriv == 0) {978 if (whichParamDeriv == 0) { 1030 979 tmp = x * x; 1031 } else 1032 if ( whichParamDeriv == 1 ) { 1033 tmp = x; 1034 } else 1035 if ( whichParamDeriv == 2 ) { 1036 tmp = 1.0; 1037 } 1038 1039 return ( tmp ); 980 } else if (whichParamDeriv == 1) { 981 tmp = x; 982 } else if (whichParamDeriv == 2) { 983 tmp = 1.0; 984 } 985 986 return (tmp); 1040 987 } 1041 988 … … 1049 996 decreasing within that range. 1050 997 *****************************************************************************/ 1051 float p_ps1DPolyMedian( psPolynomial1D *myPoly, 1052 float rangeLow, 1053 float rangeHigh, 1054 float getThisValue ) 998 float p_ps1DPolyMedian(psPolynomial1D * myPoly, float rangeLow, float rangeHigh, float getThisValue) 1055 999 { 1056 1000 int numIterations = 0; … … 1059 1003 float f = 0.0; 1060 1004 1061 // printf("p_ps1DPolyMedian(%f, %f, %f) \n", rangeLow, rangeHigh, getThisValue);1062 1063 while ( numIterations < MAX_ITERATIONS) {1064 midpoint = ( rangeHigh + rangeLow) / 2.0;1065 if ( fabs( midpoint - oldMidpoint ) <= FLT_EPSILON) {1066 return ( midpoint);1005 // printf("p_ps1DPolyMedian(%f, %f, %f) \n", rangeLow, rangeHigh, getThisValue); 1006 1007 while (numIterations < MAX_ITERATIONS) { 1008 midpoint = (rangeHigh + rangeLow) / 2.0; 1009 if (fabs(midpoint - oldMidpoint) <= FLT_EPSILON) { 1010 return (midpoint); 1067 1011 } 1068 1012 oldMidpoint = midpoint; 1069 1013 1070 f = psPolynomial1DEval( midpoint, myPoly);1071 // printf("p_ps1DPolyMedian() iteration %d. f(%f) is %f\n", numIterations, midpoint, f);1072 if ( fabs( f - getThisValue ) <= FLT_EPSILON) {1073 return ( midpoint);1074 } 1075 1076 if ( f > getThisValue) {1014 f = psPolynomial1DEval(midpoint, myPoly); 1015 // printf("p_ps1DPolyMedian() iteration %d. f(%f) is %f\n", numIterations, midpoint, f); 1016 if (fabs(f - getThisValue) <= FLT_EPSILON) { 1017 return (midpoint); 1018 } 1019 1020 if (f > getThisValue) { 1077 1021 rangeHigh = midpoint; 1078 1022 } else { … … 1081 1025 numIterations++; 1082 1026 } 1083 return ( midpoint);1027 return (midpoint); 1084 1028 } 1085 1029 … … 1092 1036 XXX: This function is currently not being used. 1093 1037 *****************************************************************************/ 1094 float p_psFitQuadratic( psHistogram *histogram, 1095 psVector *cumulativeSums, 1096 int binNum, 1097 float fitFloat ) 1098 { 1099 psVector * x = psVectorAlloc( 3, PS_TYPE_F64 ); 1100 psVector *y = psVectorAlloc( 3, PS_TYPE_F64 ); 1101 psVector *yErr = psVectorAlloc( 3, PS_TYPE_F64 ); 1102 psPolynomial1D *myPoly = psPolynomial1DAlloc( 2 ); 1103 1104 if ( ( binNum > 0 ) && 1105 ( binNum < ( histogram->nums->n + 1 ) ) ) { 1106 x->data.F64[ 0 ] = ( double ) 0.5 * 1107 ( histogram->bounds->data.F32[ binNum - 1 ] + 1108 histogram->bounds->data.F32[ binNum ] ); 1109 x->data.F64[ 1 ] = ( double ) 0.5 * 1110 ( histogram->bounds->data.F32[ binNum ] + 1111 histogram->bounds->data.F32[ binNum + 1 ] ); 1112 x->data.F64[ 2 ] = ( double ) 0.5 * 1113 ( histogram->bounds->data.F32[ binNum + 1 ] + 1114 histogram->bounds->data.F32[ binNum + 2 ] ); 1115 1116 y->data.F64[ 0 ] = cumulativeSums->data.F32[ binNum - 1 ]; 1117 y->data.F64[ 1 ] = cumulativeSums->data.F32[ binNum ]; 1118 y->data.F64[ 2 ] = cumulativeSums->data.F32[ binNum + 1 ]; 1119 1120 if ( !( ( y->data.F64[ 0 ] <= fitFloat ) && 1121 ( fitFloat <= y->data.F64[ 2 ] ) ) ) { 1122 psAbort( __func__, "p_psVectorRobustStats(0): midpoint not within y-range\n" ); 1123 } 1124 1125 yErr->data.F64[ 0 ] = 1.0; 1126 yErr->data.F64[ 1 ] = 1.0; 1127 yErr->data.F64[ 2 ] = 1.0; 1128 1129 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1130 return ( p_ps1DPolyMedian( myPoly, x->data.F64[ 0 ], x->data.F64[ 2 ], 1131 fitFloat ) ); 1038 float p_psFitQuadratic(psHistogram * histogram, psVector * cumulativeSums, int binNum, float fitFloat) 1039 { 1040 psVector *x = psVectorAlloc(3, PS_TYPE_F64); 1041 psVector *y = psVectorAlloc(3, PS_TYPE_F64); 1042 psVector *yErr = psVectorAlloc(3, PS_TYPE_F64); 1043 psPolynomial1D *myPoly = psPolynomial1DAlloc(2); 1044 1045 if ((binNum > 0) && (binNum < (histogram->nums->n + 1))) { 1046 x->data.F64[0] = (double)0.5 * 1047 (histogram->bounds->data.F32[binNum - 1] + histogram->bounds->data.F32[binNum]); 1048 x->data.F64[1] = (double)0.5 * 1049 (histogram->bounds->data.F32[binNum] + histogram->bounds->data.F32[binNum + 1]); 1050 x->data.F64[2] = (double)0.5 * 1051 (histogram->bounds->data.F32[binNum + 1] + histogram->bounds->data.F32[binNum + 2]); 1052 1053 y->data.F64[0] = cumulativeSums->data.F32[binNum - 1]; 1054 y->data.F64[1] = cumulativeSums->data.F32[binNum]; 1055 y->data.F64[2] = cumulativeSums->data.F32[binNum + 1]; 1056 1057 if (!((y->data.F64[0] <= fitFloat) && (fitFloat <= y->data.F64[2]))) { 1058 psAbort(__func__, "p_psVectorRobustStats(0): midpoint not within y-range\n"); 1059 } 1060 1061 yErr->data.F64[0] = 1.0; 1062 yErr->data.F64[1] = 1.0; 1063 yErr->data.F64[2] = 1.0; 1064 1065 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1066 return (p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], fitFloat)); 1132 1067 } else { 1133 return ( 0.5 * ( histogram->bounds->data.F32[ binNum + 1 ] + 1134 histogram->bounds->data.F32[ binNum ] ) ); 1135 } 1136 1137 psFree( x ); 1138 psFree( y ); 1139 psFree( yErr ); 1140 psFree( myPoly ); 1141 return ( 0.0 ); 1068 return (0.5 * (histogram->bounds->data.F32[binNum + 1] + histogram->bounds->data.F32[binNum])); 1069 } 1070 1071 psFree(x); 1072 psFree(y); 1073 psFree(yErr); 1074 psFree(myPoly); 1075 return (0.0); 1142 1076 } 1143 1077 … … 1166 1100 NULL 1167 1101 *****************************************************************************/ 1168 void p_psVectorRobustStats( const psVector *restrict myVector, 1169 const psVector *restrict maskVector, 1170 unsigned int maskVal, 1171 psStats *stats ) 1172 { 1173 psHistogram * robustHistogram = NULL; 1102 void p_psVectorRobustStats(const psVector * restrict myVector, 1103 const psVector * restrict maskVector, unsigned int maskVal, psStats * stats) 1104 { 1105 psHistogram *robustHistogram = NULL; 1174 1106 psVector *robustHistogramVector = NULL; 1175 float binSize = 0.0; // Size of the histogram bins1176 int LQBinNum = -1; // Bin num for lower quartile1177 int UQBinNum = -1; // Bin num for upper quartile1178 int i = 0; // Loop index variable1107 float binSize = 0.0; // Size of the histogram bins 1108 int LQBinNum = -1; // Bin num for lower quartile 1109 int UQBinNum = -1; // Bin num for upper quartile 1110 int i = 0; // Loop index variable 1179 1111 int maxBinNum = 0; 1180 1112 float maxBinCount = 0.0; 1181 1113 float dL = 0.0; 1182 1114 int numBins = 0; 1183 psStats *tmpStats = psStatsAlloc( PS_STAT_CLIPPED_STDEV | PS_STAT_CLIPPED_MEAN ); 1184 // psImage *domain; 1185 // psVector *errors; 1186 // psVector *data; 1187 // psVector *initialGuess; 1188 // psVector *theParams; 1189 // float chiSq=0.0; 1190 // float max = -HUGE; 1191 // float max_pos; 1115 psStats *tmpStats = psStatsAlloc(PS_STAT_CLIPPED_STDEV | PS_STAT_CLIPPED_MEAN); 1116 1117 // psImage *domain; 1118 // psVector *errors; 1119 // psVector *data; 1120 // psVector *initialGuess; 1121 // psVector *theParams; 1122 // float chiSq=0.0; 1123 // float max = -HUGE; 1124 // float max_pos; 1192 1125 float myMean = 0.0; 1193 1126 float myStdev = 0.0; … … 1196 1129 float sumSquares = 0.0; 1197 1130 float sumDiffs = 0.0; 1198 psVector *x = psVectorAlloc( 3, PS_TYPE_F64);1199 psVector *y = psVectorAlloc( 3, PS_TYPE_F64);1200 psVector *yErr = psVectorAlloc( 3, PS_TYPE_F64);1201 psPolynomial1D *myPoly = psPolynomial1DAlloc( 2);1131 psVector *x = psVectorAlloc(3, PS_TYPE_F64); 1132 psVector *y = psVectorAlloc(3, PS_TYPE_F64); 1133 psVector *yErr = psVectorAlloc(3, PS_TYPE_F64); 1134 psPolynomial1D *myPoly = psPolynomial1DAlloc(2); 1202 1135 psVector *cumulativeRobustSumsFullRange = NULL; 1203 1136 psVector *cumulativeRobustSumsDlRange = NULL; … … 1210 1143 // by computing the clipped standard deviation of the vector, and dividing 1211 1144 // that by 10.0; 1212 p_psVectorClippedStats( myVector, maskVector, maskVal, tmpStats);1145 p_psVectorClippedStats(myVector, maskVector, maskVal, tmpStats); 1213 1146 binSize = tmpStats->clippedStdev / 10.0f; 1214 1147 1215 1148 // If stats->clippedStdev == 0.0, then all data elements have the same 1216 1149 // value. Therefore, we can set the appropiate results and return. 1217 if ( fabs( binSize ) <= FLT_EPSILON) {1218 if ( stats->options & PS_STAT_ROBUST_MEAN) {1150 if (fabs(binSize) <= FLT_EPSILON) { 1151 if (stats->options & PS_STAT_ROBUST_MEAN) { 1219 1152 stats->robustMean = stats->clippedMean; 1220 1153 } 1221 if ( stats->options & PS_STAT_ROBUST_MEDIAN) {1154 if (stats->options & PS_STAT_ROBUST_MEDIAN) { 1222 1155 stats->robustMedian = stats->clippedMean; 1223 1156 } 1224 if ( stats->options & PS_STAT_ROBUST_MODE) {1157 if (stats->options & PS_STAT_ROBUST_MODE) { 1225 1158 stats->robustMode = stats->clippedMean; 1226 1159 } 1227 if ( stats->options & PS_STAT_ROBUST_STDEV) {1160 if (stats->options & PS_STAT_ROBUST_STDEV) { 1228 1161 stats->robustStdev = 0.0; 1229 1162 } 1230 if ( stats->options & PS_STAT_ROBUST_QUARTILE) {1163 if (stats->options & PS_STAT_ROBUST_QUARTILE) { 1231 1164 stats->robustUQ = stats->clippedMean; 1232 1165 stats->robustLQ = stats->clippedMean; … … 1235 1168 stats->robustNfit = 0.0; 1236 1169 stats->robustN50 = 0.0; 1237 psFree( tmpStats ); 1238 return ; 1239 } 1240 1170 psFree(tmpStats); 1171 return; 1172 } 1241 1173 // Determine minimum and maximum values in the data vector. 1242 if ( isnan( stats->min ) ) { 1243 p_psVectorMin( myVector, maskVector, maskVal, stats ); 1244 } 1245 if ( isnan( stats->max ) ) { 1246 p_psVectorMax( myVector, maskVector, maskVal, stats ); 1247 } 1248 1174 if (isnan(stats->min)) { 1175 p_psVectorMin(myVector, maskVector, maskVal, stats); 1176 } 1177 if (isnan(stats->max)) { 1178 p_psVectorMax(myVector, maskVector, maskVal, stats); 1179 } 1249 1180 // Create the histogram structure. NOTE: we can not specify the bin size 1250 1181 // precisely since the argument to psHistogramAlloc() is the number of 1251 1182 // bins, not the binSize. Also, if we get here, we know that 1252 1183 // binSize != 0.0. 1253 numBins = ( int ) ( ( stats->max - stats->min ) / binSize ); 1254 robustHistogram = psHistogramAlloc( stats->min, 1255 stats->max, 1256 numBins ); 1184 numBins = (int)((stats->max - stats->min) / binSize); 1185 robustHistogram = psHistogramAlloc(stats->min, stats->max, numBins); 1257 1186 1258 1187 // Populate the histogram array. 1259 psVectorHistogram( robustHistogram, myVector, maskVector, maskVal);1188 psVectorHistogram(robustHistogram, myVector, maskVector, maskVal); 1260 1189 1261 1190 // Smooth the histogram. 1262 1191 // XXX: is that the right stdev? 1263 robustHistogramVector = p_psVectorsmoothHistGaussian( robustHistogram, 1264 tmpStats->clippedStdev / 4.0f ); 1192 robustHistogramVector = p_psVectorsmoothHistGaussian(robustHistogram, tmpStats->clippedStdev / 4.0f); 1265 1193 1266 1194 // The following was necessary to fit a gaussian to the data, since … … 1274 1202 // index position i is equal to the sum of bins 0:i. This will be used 1275 1203 // now and later in determining the lower/upper quartiles. 1276 cumulativeRobustSumsFullRange = psVectorAlloc( robustHistogramVector->n, PS_TYPE_F32 ); 1277 cumulativeRobustSumsFullRange->data.F32[ 0 ] = robustHistogramVector->data.F32[ 0 ]; 1278 for ( i = 1;i < robustHistogramVector->n;i++ ) { 1279 cumulativeRobustSumsFullRange->data.F32[ i ] = 1280 cumulativeRobustSumsFullRange->data.F32[ i - 1 ] + 1281 robustHistogramVector->data.F32[ i ]; 1282 } 1283 sumRobust = cumulativeRobustSumsFullRange->data.F32[ robustHistogramVector->n - 1 ]; 1204 cumulativeRobustSumsFullRange = psVectorAlloc(robustHistogramVector->n, PS_TYPE_F32); 1205 cumulativeRobustSumsFullRange->data.F32[0] = robustHistogramVector->data.F32[0]; 1206 for (i = 1; i < robustHistogramVector->n; i++) { 1207 cumulativeRobustSumsFullRange->data.F32[i] = 1208 cumulativeRobustSumsFullRange->data.F32[i - 1] + robustHistogramVector->data.F32[i]; 1209 } 1210 sumRobust = cumulativeRobustSumsFullRange->data.F32[robustHistogramVector->n - 1]; 1284 1211 1285 1212 // Determine the bin number containing the lower quartile point. 1286 1213 LQBinNum = -1; 1287 for ( i = 0;i < cumulativeRobustSumsFullRange->n;i++) {1288 if ( cumulativeRobustSumsFullRange->data.F32[ i ] >= ( sumRobust / 4.0 )) {1214 for (i = 0; i < cumulativeRobustSumsFullRange->n; i++) { 1215 if (cumulativeRobustSumsFullRange->data.F32[i] >= (sumRobust / 4.0)) { 1289 1216 LQBinNum = i; 1290 1217 break; … … 1294 1221 // Determine the bin number containing the upper quartile point. 1295 1222 UQBinNum = -1; 1296 for ( i = cumulativeRobustSumsFullRange->n - 1;i >= 0;i--) {1297 if ( cumulativeRobustSumsFullRange->data.F32[ i ] <= ( 3.0 * sumRobust / 4.0 )) {1223 for (i = cumulativeRobustSumsFullRange->n - 1; i >= 0; i--) { 1224 if (cumulativeRobustSumsFullRange->data.F32[i] <= (3.0 * sumRobust / 4.0)) { 1298 1225 UQBinNum = i; 1299 1226 break; … … 1301 1228 } 1302 1229 1303 if ( ( LQBinNum == -1 ) ||1304 ( UQBinNum == -1 ) ) {1305 psAbort( __func__, "Could not determine the robust lower/upper quartiles." );1306 } 1230 if ((LQBinNum == -1) || (UQBinNum == -1)) { 1231 psAbort(__func__, "Could not determine the robust lower/upper quartiles."); 1232 } 1233 1307 1234 /************************************************************************** 1308 1235 Determine the mode in the range LQ:UQ. … … 1310 1237 // Determine the bin with the peak value in the range LQ to UQ. 1311 1238 maxBinNum = LQBinNum; 1312 maxBinCount = robustHistogramVector->data.F32[ LQBinNum];1313 sumN50 = ( float ) robustHistogram->nums->data.S32[ LQBinNum];1314 for ( i = LQBinNum + 1;i <= UQBinNum;i++) {1315 if ( robustHistogramVector->data.F32[ i ] > maxBinCount) {1239 maxBinCount = robustHistogramVector->data.F32[LQBinNum]; 1240 sumN50 = (float)robustHistogram->nums->data.S32[LQBinNum]; 1241 for (i = LQBinNum + 1; i <= UQBinNum; i++) { 1242 if (robustHistogramVector->data.F32[i] > maxBinCount) { 1316 1243 maxBinNum = i; 1317 maxBinCount = robustHistogramVector->data.F32[ i];1318 } 1319 sumN50 += ( float ) robustHistogram->nums->data.S32[ i];1244 maxBinCount = robustHistogramVector->data.F32[i]; 1245 } 1246 sumN50 += (float)robustHistogram->nums->data.S32[i]; 1320 1247 } 1321 1248 1322 1249 // XXX: is dL defined as the value at the LQ/UQ, or the bin number? 1323 dL = ( UQBinNum - LQBinNum) / 4;1324 1325 printf( "(LQBinNum, UQBinNum, maxBinNum) is (%d, %d, %d)\n", LQBinNum, UQBinNum, maxBinNum);1250 dL = (UQBinNum - LQBinNum) / 4; 1251 1252 printf("(LQBinNum, UQBinNum, maxBinNum) is (%d, %d, %d)\n", LQBinNum, UQBinNum, maxBinNum); 1326 1253 1327 1254 /************************************************************************** 1328 1255 Determine the mean/stdev for the bins in the range mode-dL to mode+dL 1329 1256 **************************************************************************/ 1330 cumulativeRobustSumsDlRange = psVectorAlloc( robustHistogramVector->n, PS_TYPE_F32);1331 for ( i = 0;i < robustHistogramVector->n;i++) {1332 cumulativeRobustSumsDlRange->data.F32[ i] = 0.0;1257 cumulativeRobustSumsDlRange = psVectorAlloc(robustHistogramVector->n, PS_TYPE_F32); 1258 for (i = 0; i < robustHistogramVector->n; i++) { 1259 cumulativeRobustSumsDlRange->data.F32[i] = 0.0; 1333 1260 } 1334 1261 sumNfit = 0.0; 1335 1262 cumulativeMedian = 0.0; 1336 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++ ) { 1337 if ( ( 0 <= i ) && ( i < robustHistogramVector->n ) ) { 1338 cumulativeRobustSumsDlRange->data.F32[ i ] = 1339 cumulativeRobustSumsDlRange->data.F32[ i - 1 ] + 1340 robustHistogramVector->data.F32[ i ]; 1341 cumulativeMedian += robustHistogramVector->data.F32[ i ]; 1342 sumNfit += ( float ) robustHistogram->nums->data.S32[ i ]; 1263 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1264 if ((0 <= i) && (i < robustHistogramVector->n)) { 1265 cumulativeRobustSumsDlRange->data.F32[i] = 1266 cumulativeRobustSumsDlRange->data.F32[i - 1] + robustHistogramVector->data.F32[i]; 1267 cumulativeMedian += robustHistogramVector->data.F32[i]; 1268 sumNfit += (float)robustHistogram->nums->data.S32[i]; 1343 1269 } 1344 1270 } … … 1348 1274 // that bin (this is a non-exact approximation). 1349 1275 myMean = 0.0; 1350 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++ ) { 1351 if ( ( 0 <= i ) && ( i < robustHistogramVector->n ) ) { 1352 myMean += ( robustHistogramVector->data.F32[ i ] ) * 0.5 * 1353 ( robustHistogram->bounds->data.F32[ i + 1 ] + 1354 robustHistogram->bounds->data.F32[ i ] ); 1355 countFloat += robustHistogramVector->data.F32[ i ]; 1276 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1277 if ((0 <= i) && (i < robustHistogramVector->n)) { 1278 myMean += (robustHistogramVector->data.F32[i]) * 0.5 * 1279 (robustHistogram->bounds->data.F32[i + 1] + robustHistogram->bounds->data.F32[i]); 1280 countFloat += robustHistogramVector->data.F32[i]; 1356 1281 } 1357 1282 } … … 1361 1286 // mode-dL to mode+dL. We use the midpoint of each bin as the mean for 1362 1287 // that bin. 1363 for ( i = maxBinNum - dL;i <= maxBinNum + dL;i++) {1364 if ( ( 0 <= i ) && ( i < robustHistogramVector->n )) {1365 diff = ( 0.5 * ( robustHistogram->bounds->data.F32[ i + 1] +1366 robustHistogram->bounds->data.F32[ i ] )) - myMean;1367 sumSquares += diff * diff * robustHistogramVector->data.F32[ i];1368 sumDiffs += diff * robustHistogramVector->data.F32[ i];1369 } 1370 } 1371 myStdev = sqrt( ( sumSquares - ( sumDiffs * sumDiffs / countFloat ) ) / ( countFloat - 1 ));1288 for (i = maxBinNum - dL; i <= maxBinNum + dL; i++) { 1289 if ((0 <= i) && (i < robustHistogramVector->n)) { 1290 diff = (0.5 * (robustHistogram->bounds->data.F32[i + 1] + 1291 robustHistogram->bounds->data.F32[i])) - myMean; 1292 sumSquares += diff * diff * robustHistogramVector->data.F32[i]; 1293 sumDiffs += diff * robustHistogramVector->data.F32[i]; 1294 } 1295 } 1296 myStdev = sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1)); 1372 1297 1373 1298 /************************************************************************** 1374 1299 Set the appropriate members in the output stats struct. 1375 1300 **************************************************************************/ 1376 if ( stats->options & PS_STAT_ROBUST_MEAN) {1301 if (stats->options & PS_STAT_ROBUST_MEAN) { 1377 1302 stats->robustMean = myMean; 1378 1303 } 1379 1304 1380 if ( stats->options & PS_STAT_ROBUST_MODE) {1305 if (stats->options & PS_STAT_ROBUST_MODE) { 1381 1306 stats->robustMode = 0.5 * 1382 ( robustHistogram->bounds->data.F32[ maxBinNum ] + 1383 robustHistogram->bounds->data.F32[ maxBinNum + 1 ] ); 1384 } 1385 1386 if ( stats->options & PS_STAT_ROBUST_STDEV ) { 1307 (robustHistogram->bounds->data.F32[maxBinNum] + robustHistogram->bounds->data.F32[maxBinNum + 1]); 1308 } 1309 1310 if (stats->options & PS_STAT_ROBUST_STDEV) { 1387 1311 stats->robustStdev = myStdev; 1388 1312 } 1389 1390 1313 // To determine the median (and later, the lower/upper quartile), we fit 1391 1314 // a quadratic to the three bins surrounding the bin containing the median. … … 1394 1317 // this bin. We then solve the quadratic for 1395 1318 1396 if ( stats->options & PS_STAT_ROBUST_MEDIAN) {1397 if ( ( maxBinNum > 0 ) && ( maxBinNum < ( robustHistogram->nums->n - 1 ) )) {1398 x->data.F64[ 0 ] = ( double )0.5 *1399 ( robustHistogram->bounds->data.F32[ maxBinNum - 1] +1400 robustHistogram->bounds->data.F32[ maxBinNum ]);1401 x->data.F64[ 1 ] = ( double )0.5 *1402 ( robustHistogram->bounds->data.F32[ maxBinNum] +1403 robustHistogram->bounds->data.F32[ maxBinNum + 1 ]);1404 x->data.F64[ 2 ] = ( double )0.5 *1405 ( robustHistogram->bounds->data.F32[ maxBinNum + 1] +1406 robustHistogram->bounds->data.F32[ maxBinNum + 2 ]);1407 1408 y->data.F64[ 0 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum - 1];1409 y->data.F64[ 1 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum];1410 y->data.F64[ 2 ] = cumulativeRobustSumsDlRange->data.F32[ maxBinNum + 1];1319 if (stats->options & PS_STAT_ROBUST_MEDIAN) { 1320 if ((maxBinNum > 0) && (maxBinNum < (robustHistogram->nums->n - 1))) { 1321 x->data.F64[0] = (double)0.5 * 1322 (robustHistogram->bounds->data.F32[maxBinNum - 1] + 1323 robustHistogram->bounds->data.F32[maxBinNum]); 1324 x->data.F64[1] = (double)0.5 * 1325 (robustHistogram->bounds->data.F32[maxBinNum] + 1326 robustHistogram->bounds->data.F32[maxBinNum + 1]); 1327 x->data.F64[2] = (double)0.5 * 1328 (robustHistogram->bounds->data.F32[maxBinNum + 1] + 1329 robustHistogram->bounds->data.F32[maxBinNum + 2]); 1330 1331 y->data.F64[0] = cumulativeRobustSumsDlRange->data.F32[maxBinNum - 1]; 1332 y->data.F64[1] = cumulativeRobustSumsDlRange->data.F32[maxBinNum]; 1333 y->data.F64[2] = cumulativeRobustSumsDlRange->data.F32[maxBinNum + 1]; 1411 1334 1412 1335 // Ensure that cumulativeMedian/2 is actually within the range of the bins 1413 1336 // we are using. 1414 1337 cumulativeMedian *= 0.5; 1415 if ( !( ( y->data.F64[ 0 ] <= cumulativeMedian ) && 1416 ( cumulativeMedian <= y->data.F64[ 2 ] ) ) ) { 1417 printf( "((%f), %f, %f)\n", cumulativeMedian, y->data.F64[ 0 ], y->data.F64[ 2 ] ); 1418 psAbort( __func__, "p_psVectorRobustStats(1): midpoint not within y-range\n" ); 1338 if (!((y->data.F64[0] <= cumulativeMedian) && (cumulativeMedian <= y->data.F64[2]))) { 1339 printf("((%f), %f, %f)\n", cumulativeMedian, y->data.F64[0], y->data.F64[2]); 1340 psAbort(__func__, "p_psVectorRobustStats(1): midpoint not within y-range\n"); 1419 1341 } 1420 1342 // XXX: yErr is not currently used by psVectorFitPolynomial1D(). We 1421 1343 // may have to set this meaningfully later. 1422 yErr->data.F64[ 0] = 1.0;1423 yErr->data.F64[ 1] = 1.0;1424 yErr->data.F64[ 2] = 1.0;1344 yErr->data.F64[0] = 1.0; 1345 yErr->data.F64[1] = 1.0; 1346 yErr->data.F64[2] = 1.0; 1425 1347 1426 1348 // Determine the coefficients of the polynomial. 1427 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr);1349 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1428 1350 // Call p_ps1DPolyMedian(), which does a binary search on the 1429 1351 // polynomial, looking for the value x such that 1430 1352 // f(x) = cumulativeMedian. 1431 stats->robustMedian = p_ps1DPolyMedian( myPoly, x->data.F64[ 0 ], 1432 x->data.F64[ 2 ], cumulativeMedian ); 1353 stats->robustMedian = p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], cumulativeMedian); 1433 1354 } else { 1434 1355 // If the mode is the first/last histogram bin, then simply use 1435 1356 // the midpoint of that bin. 1436 stats->robustMedian = 0.5 * ( robustHistogram->bounds->data.F32[ maxBinNum + 1 ] + 1437 robustHistogram->bounds->data.F32[ maxBinNum ] ); 1438 } 1439 } 1440 1357 stats->robustMedian = 0.5 * (robustHistogram->bounds->data.F32[maxBinNum + 1] + 1358 robustHistogram->bounds->data.F32[maxBinNum]); 1359 } 1360 } 1441 1361 // The lower/upper quartile calculations are very similar to the median 1442 1362 // calculations. We fit a quadratic to the array containing the … … 1444 1364 // f(x) equals the lower/upper quartile exactly. 1445 1365 // 1446 if ( stats->options & PS_STAT_ROBUST_QUARTILE ) { 1447 countFloat = cumulativeRobustSumsFullRange->data.F32[ robustHistogramVector->n - 1 ]; 1448 1449 if ( ( LQBinNum > 0 ) && ( LQBinNum < ( robustHistogram->nums->n - 1 ) ) ) { 1450 x->data.F64[ 0 ] = ( double ) 0.5 * 1451 ( robustHistogram->bounds->data.F32[ LQBinNum - 1 ] + 1452 robustHistogram->bounds->data.F32[ LQBinNum ] ); 1453 x->data.F64[ 1 ] = ( double ) 0.5 * 1454 ( robustHistogram->bounds->data.F32[ LQBinNum ] + 1455 robustHistogram->bounds->data.F32[ LQBinNum + 1 ] ); 1456 x->data.F64[ 2 ] = ( double ) 0.5 * 1457 ( robustHistogram->bounds->data.F32[ LQBinNum + 1 ] + 1458 robustHistogram->bounds->data.F32[ LQBinNum + 2 ] ); 1459 1460 y->data.F64[ 0 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum - 1 ]; 1461 y->data.F64[ 1 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum ]; 1462 y->data.F64[ 2 ] = cumulativeRobustSumsFullRange->data.F32[ LQBinNum + 1 ]; 1463 1464 if ( !( ( y->data.F64[ 0 ] <= ( countFloat / 4.0 ) ) && 1465 ( ( countFloat / 4.0 ) <= y->data.F64[ 2 ] ) ) ) { 1466 psAbort( __func__, "p_psVectorRobustStats(2): midpoint not within y-range\n" ); 1467 } 1468 1469 yErr->data.F64[ 0 ] = 1.0; 1470 yErr->data.F64[ 1 ] = 1.0; 1471 yErr->data.F64[ 2 ] = 1.0; 1472 1473 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1474 stats->robustLQ = p_ps1DPolyMedian( myPoly, 1475 x->data.F64[ 0 ], 1476 x->data.F64[ 2 ], 1477 countFloat / 4.0 ); 1366 if (stats->options & PS_STAT_ROBUST_QUARTILE) { 1367 countFloat = cumulativeRobustSumsFullRange->data.F32[robustHistogramVector->n - 1]; 1368 1369 if ((LQBinNum > 0) && (LQBinNum < (robustHistogram->nums->n - 1))) { 1370 x->data.F64[0] = (double)0.5 * 1371 (robustHistogram->bounds->data.F32[LQBinNum - 1] + 1372 robustHistogram->bounds->data.F32[LQBinNum]); 1373 x->data.F64[1] = (double)0.5 * 1374 (robustHistogram->bounds->data.F32[LQBinNum] + 1375 robustHistogram->bounds->data.F32[LQBinNum + 1]); 1376 x->data.F64[2] = (double)0.5 * 1377 (robustHistogram->bounds->data.F32[LQBinNum + 1] + 1378 robustHistogram->bounds->data.F32[LQBinNum + 2]); 1379 1380 y->data.F64[0] = cumulativeRobustSumsFullRange->data.F32[LQBinNum - 1]; 1381 y->data.F64[1] = cumulativeRobustSumsFullRange->data.F32[LQBinNum]; 1382 y->data.F64[2] = cumulativeRobustSumsFullRange->data.F32[LQBinNum + 1]; 1383 1384 if (!((y->data.F64[0] <= (countFloat / 4.0)) && ((countFloat / 4.0) <= y->data.F64[2]))) { 1385 psAbort(__func__, "p_psVectorRobustStats(2): midpoint not within y-range\n"); 1386 } 1387 1388 yErr->data.F64[0] = 1.0; 1389 yErr->data.F64[1] = 1.0; 1390 yErr->data.F64[2] = 1.0; 1391 1392 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1393 stats->robustLQ = p_ps1DPolyMedian(myPoly, x->data.F64[0], x->data.F64[2], countFloat / 4.0); 1478 1394 1479 1395 } else { 1480 1396 // If the LQ is the first/last histogram bin, then simply use 1481 1397 // the midpoint of that bin. 1482 stats->robustLQ = 0.5 * ( robustHistogram->bounds->data.F32[ LQBinNum + 1 ] + 1483 robustHistogram->bounds->data.F32[ LQBinNum ] ); 1484 } 1485 1486 if ( ( UQBinNum > 0 ) && ( UQBinNum < ( robustHistogram->nums->n - 1 ) ) ) { 1487 x->data.F64[ 0 ] = ( double ) 0.5 * 1488 ( robustHistogram->bounds->data.F32[ UQBinNum - 1 ] + 1489 robustHistogram->bounds->data.F32[ UQBinNum ] ); 1490 x->data.F64[ 1 ] = ( double ) 0.5 * 1491 ( robustHistogram->bounds->data.F32[ UQBinNum ] + 1492 robustHistogram->bounds->data.F32[ UQBinNum + 1 ] ); 1493 x->data.F64[ 2 ] = ( double ) 0.5 * 1494 ( robustHistogram->bounds->data.F32[ UQBinNum + 1 ] + 1495 robustHistogram->bounds->data.F32[ UQBinNum + 2 ] ); 1496 1497 y->data.F64[ 0 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum - 1 ]; 1498 y->data.F64[ 1 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum ]; 1499 y->data.F64[ 2 ] = cumulativeRobustSumsFullRange->data.F32[ UQBinNum + 1 ]; 1500 1501 if ( !( ( y->data.F64[ 0 ] <= ( 3.0 * countFloat / 4.0 ) ) && 1502 ( ( 3.0 * countFloat / 4.0 ) <= y->data.F64[ 2 ] ) ) ) { 1503 psAbort( __func__, "p_psVectorRobustStats(3): midpoint not within y-range\n" ); 1504 } 1505 1506 yErr->data.F64[ 0 ] = 1.0; 1507 yErr->data.F64[ 1 ] = 1.0; 1508 yErr->data.F64[ 2 ] = 1.0; 1509 1510 myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr ); 1511 stats->robustUQ = p_ps1DPolyMedian( myPoly, 1512 x->data.F64[ 0 ], 1513 x->data.F64[ 2 ], 1514 3.0 * countFloat / 4.0 ); 1398 stats->robustLQ = 0.5 * (robustHistogram->bounds->data.F32[LQBinNum + 1] + 1399 robustHistogram->bounds->data.F32[LQBinNum]); 1400 } 1401 1402 if ((UQBinNum > 0) && (UQBinNum < (robustHistogram->nums->n - 1))) { 1403 x->data.F64[0] = (double)0.5 * 1404 (robustHistogram->bounds->data.F32[UQBinNum - 1] + 1405 robustHistogram->bounds->data.F32[UQBinNum]); 1406 x->data.F64[1] = (double)0.5 * 1407 (robustHistogram->bounds->data.F32[UQBinNum] + 1408 robustHistogram->bounds->data.F32[UQBinNum + 1]); 1409 x->data.F64[2] = (double)0.5 * 1410 (robustHistogram->bounds->data.F32[UQBinNum + 1] + 1411 robustHistogram->bounds->data.F32[UQBinNum + 2]); 1412 1413 y->data.F64[0] = cumulativeRobustSumsFullRange->data.F32[UQBinNum - 1]; 1414 y->data.F64[1] = cumulativeRobustSumsFullRange->data.F32[UQBinNum]; 1415 y->data.F64[2] = cumulativeRobustSumsFullRange->data.F32[UQBinNum + 1]; 1416 1417 if (!((y->data.F64[0] <= (3.0 * countFloat / 4.0)) && 1418 ((3.0 * countFloat / 4.0) <= y->data.F64[2]))) { 1419 psAbort(__func__, "p_psVectorRobustStats(3): midpoint not within y-range\n"); 1420 } 1421 1422 yErr->data.F64[0] = 1.0; 1423 yErr->data.F64[1] = 1.0; 1424 yErr->data.F64[2] = 1.0; 1425 1426 myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr); 1427 stats->robustUQ = p_ps1DPolyMedian(myPoly, 1428 x->data.F64[0], x->data.F64[2], 3.0 * countFloat / 4.0); 1515 1429 } else { 1516 1430 // If the UQ is the first/last histogram bin, then simply use 1517 1431 // the midpoint of that bin. 1518 stats->robustUQ = 0.5 * ( robustHistogram->bounds->data.F32[ UQBinNum + 1] +1519 robustHistogram->bounds->data.F32[ UQBinNum ]);1432 stats->robustUQ = 0.5 * (robustHistogram->bounds->data.F32[UQBinNum + 1] + 1433 robustHistogram->bounds->data.F32[UQBinNum]); 1520 1434 } 1521 1435 } … … 1523 1437 stats->robustN50 = sumN50; 1524 1438 1525 psFree( x ); 1526 psFree( y ); 1527 psFree( yErr ); 1528 psFree( tmpStats ); 1529 psFree( robustHistogram ); 1530 psFree( myPoly ); 1531 psFree( cumulativeRobustSumsFullRange ); 1532 psFree( cumulativeRobustSumsDlRange ); 1533 } 1534 1535 1439 psFree(x); 1440 psFree(y); 1441 psFree(yErr); 1442 psFree(tmpStats); 1443 psFree(robustHistogram); 1444 psFree(myPoly); 1445 psFree(cumulativeRobustSumsFullRange); 1446 psFree(cumulativeRobustSumsDlRange); 1447 } 1536 1448 1537 1449 /* … … 1582 1494 */ 1583 1495 1584 1585 1496 /*****************************************************************************/ 1497 1586 1498 /* FUNCTION IMPLEMENTATION - PUBLIC */ 1499 1587 1500 /*****************************************************************************/ 1588 1501 1589 static void histogramFree( psHistogram *myHist);1502 static void histogramFree(psHistogram * myHist); 1590 1503 1591 1504 /****************************************************************************** 1592 1505 psStatsAlloc(): This routine must create a new psStats data structure. 1593 1506 *****************************************************************************/ 1594 psStats *psStatsAlloc( psStatsOptions options)1595 { 1596 psStats * newStruct = NULL;1597 1598 newStruct = ( psStats * ) psAlloc( sizeof( psStats ));1507 psStats *psStatsAlloc(psStatsOptions options) 1508 { 1509 psStats *newStruct = NULL; 1510 1511 newStruct = (psStats *) psAlloc(sizeof(psStats)); 1599 1512 newStruct->sampleMean = NAN; 1600 1513 newStruct->sampleMedian = NAN; … … 1620 1533 newStruct->options = options; 1621 1534 1622 return ( newStruct);1535 return (newStruct); 1623 1536 } 1624 1537 … … 1635 1548 The histogram structure 1636 1549 *****************************************************************************/ 1637 psHistogram *psHistogramAlloc( float lower, 1638 float upper, 1639 int n ) 1640 { 1641 int i = 0; // Loop index variable 1550 psHistogram *psHistogramAlloc(float lower, float upper, int n) 1551 { 1552 int i = 0; // Loop index variable 1642 1553 psHistogram *newHist = NULL; // The new histogram structure 1643 float binSize = 0.0; // The histogram bin size1554 float binSize = 0.0; // The histogram bin size 1644 1555 1645 1556 // NOTE: Verify that this is the correct action. 1646 if ( n == 0 ) { 1647 return ( NULL ); 1648 } 1649 if ( n < 0 ) { 1650 psAbort( __func__, "psHistogramAlloc() called with bin size %d.\n", n ); 1651 } 1652 1557 if (n == 0) { 1558 return (NULL); 1559 } 1560 if (n < 0) { 1561 psAbort(__func__, "psHistogramAlloc() called with bin size %d.\n", n); 1562 } 1653 1563 // NOTE: Verify that this is the correct action. 1654 if ( lower > upper ) { 1655 return ( NULL ); 1656 } 1657 1564 if (lower > upper) { 1565 return (NULL); 1566 } 1658 1567 // Allocate memory for the new histogram structure. If there are N 1659 1568 // bins, then there are N+1 bounds to those bins. 1660 newHist = ( psHistogram * ) psAlloc( sizeof( psHistogram ));1661 p_psMemSetDeallocator( newHist, ( psFreeFcn ) histogramFree);1662 newHist->bounds = psVectorAlloc( n + 1, PS_TYPE_F32);1569 newHist = (psHistogram *) psAlloc(sizeof(psHistogram)); 1570 p_psMemSetDeallocator(newHist, (psFreeFcn) histogramFree); 1571 newHist->bounds = psVectorAlloc(n + 1, PS_TYPE_F32); 1663 1572 newHist->bounds->n = newHist->bounds->nalloc; 1664 1573 1665 1574 // Calculate the bounds for each bin. 1666 binSize = ( upper - lower ) / ( float )n;1667 // NOTE: Is the following necessary? It prevents the max data point1575 binSize = (upper - lower) / (float)n; 1576 // NOTE: Is the following necessary? It prevents the max data point 1668 1577 // from being in a non-existant bin. 1669 1578 binSize += FLT_EPSILON; 1670 for ( i = 0;i < n + 1;i++) {1671 newHist->bounds->data.F32[ i ] = lower + ( binSize * ( float ) i);1579 for (i = 0; i < n + 1; i++) { 1580 newHist->bounds->data.F32[i] = lower + (binSize * (float)i); 1672 1581 } 1673 1582 1674 1583 // Allocate the bins, and initialize them to zero. 1675 newHist->nums = psVectorAlloc( n, PS_TYPE_U32);1584 newHist->nums = psVectorAlloc(n, PS_TYPE_U32); 1676 1585 newHist->nums->n = newHist->nums->nalloc; 1677 for ( i = 0;i < newHist->nums->n;i++) {1678 newHist->nums->data.U32[ i] = 0;1586 for (i = 0; i < newHist->nums->n; i++) { 1587 newHist->nums->data.U32[i] = 0; 1679 1588 } 1680 1589 … … 1684 1593 newHist->uniform = true; 1685 1594 1686 return ( newHist);1595 return (newHist); 1687 1596 } 1688 1597 … … 1696 1605 The histogram structure 1697 1606 *****************************************************************************/ 1698 psHistogram *psHistogramAllocGeneric( const psVector *restrict bounds)1699 { 1700 psHistogram * newHist = NULL; // The new histogram structure1701 int i; // Loop index variable1607 psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds) 1608 { 1609 psHistogram *newHist = NULL; // The new histogram structure 1610 int i; // Loop index variable 1702 1611 1703 1612 // NOTE: Verify that this is the correct action. 1704 if ( bounds == NULL) {1613 if (bounds == NULL) { 1705 1614 // psAbort(__func__, "psHistogram requested with NULL bounds"); 1706 return ( NULL ); 1707 } 1708 1615 return (NULL); 1616 } 1709 1617 // NOTE: Verify that this is the correct action. 1710 if ( bounds->n <= 1) {1618 if (bounds->n <= 1) { 1711 1619 // psAbort(__func__, "psHistogram requested with NULL bounds"); 1712 return ( NULL);1713 } 1714 1715 if ( bounds->type.type != PS_TYPE_F32) {1620 return (NULL); 1621 } 1622 1623 if (bounds->type.type != PS_TYPE_F32) { 1716 1624 // psAbort(__func__, "psHistogram request a bound which is not type F32"); 1717 return ( NULL ); 1718 } 1719 1625 return (NULL); 1626 } 1720 1627 // Allocate memory for the new histogram structure. 1721 newHist = ( psHistogram * ) psAlloc( sizeof( psHistogram ));1722 p_psMemSetDeallocator( newHist, ( psFreeFcn ) histogramFree);1723 newHist->bounds = psVectorAlloc( bounds->n, PS_TYPE_F32);1628 newHist = (psHistogram *) psAlloc(sizeof(psHistogram)); 1629 p_psMemSetDeallocator(newHist, (psFreeFcn) histogramFree); 1630 newHist->bounds = psVectorAlloc(bounds->n, PS_TYPE_F32); 1724 1631 newHist->bounds->n = newHist->bounds->nalloc; 1725 for ( i = 0;i < bounds->n;i++) {1726 newHist->bounds->data.F32[ i ] = bounds->data.F32[ i];1632 for (i = 0; i < bounds->n; i++) { 1633 newHist->bounds->data.F32[i] = bounds->data.F32[i]; 1727 1634 } 1728 1635 1729 1636 // Allocate the bins, and initialize them to zero. If there are N bounds, 1730 1637 // then there are N-1 bins. 1731 newHist->nums = psVectorAlloc( ( bounds->n ) - 1, PS_TYPE_U32);1638 newHist->nums = psVectorAlloc((bounds->n) - 1, PS_TYPE_U32); 1732 1639 newHist->nums->n = newHist->nums->nalloc; 1733 for ( i = 0;i < newHist->nums->n;i++) {1734 newHist->nums->data.U32[ i] = 0;1640 for (i = 0; i < newHist->nums->n; i++) { 1641 newHist->nums->data.U32[i] = 0; 1735 1642 } 1736 1643 … … 1740 1647 newHist->uniform = false; 1741 1648 1742 return ( newHist ); 1743 } 1744 1745 static void histogramFree( psHistogram *myHist ) 1746 { 1747 psFree( myHist->bounds ); 1748 psFree( myHist->nums ); 1749 } 1750 1649 return (newHist); 1650 } 1651 1652 static void histogramFree(psHistogram * myHist) 1653 { 1654 psFree(myHist->bounds); 1655 psFree(myHist->nums); 1656 } 1751 1657 1752 1658 /***************************************************************************** … … 1764 1670 The histogram structure "out". 1765 1671 *****************************************************************************/ 1766 psHistogram *psVectorHistogram( psHistogram *out, 1767 const psVector *restrict in, 1768 const psVector *restrict mask, 1769 unsigned int maskVal ) 1770 { 1771 int i = 0; // Loop index variable 1772 int j = 0; // Loop index variable 1773 float binSize = 0.0; // Histogram bin size 1774 int binNum = 0; // A temporary bin number 1775 int numBins = 0; // The total number of bins 1672 psHistogram *psVectorHistogram(psHistogram * out, 1673 const psVector * restrict in, 1674 const psVector * restrict mask, unsigned int maskVal) 1675 { 1676 int i = 0; // Loop index variable 1677 int j = 0; // Loop index variable 1678 float binSize = 0.0; // Histogram bin size 1679 int binNum = 0; // A temporary bin number 1680 int numBins = 0; // The total number of bins 1776 1681 1777 1682 // NOTE: Verify that this is the correct action. 1778 if ( out == NULL ) { 1779 return ( NULL ); 1780 } 1781 1683 if (out == NULL) { 1684 return (NULL); 1685 } 1782 1686 // Check the specified output histogram for type psF32 1783 if ( out->bounds->type.type != PS_TYPE_F32 ) { 1784 psAbort( __func__, 1785 "Only data type PS_TYPE_F32 for the output.bounds member." ); 1786 } 1787 1788 if ( out->nums->type.type != PS_TYPE_U32 ) { 1789 psAbort( __func__, 1790 "Only data type PS_TYPE_U32 for output.nums member." ); 1791 } 1792 1687 if (out->bounds->type.type != PS_TYPE_F32) { 1688 psAbort(__func__, "Only data type PS_TYPE_F32 for the output.bounds member."); 1689 } 1690 1691 if (out->nums->type.type != PS_TYPE_U32) { 1692 psAbort(__func__, "Only data type PS_TYPE_U32 for output.nums member."); 1693 } 1793 1694 // NOTE: Verify that this is the correct action. 1794 if ( in == NULL ) { 1795 return ( out ); 1796 } 1797 1798 if ( in->type.type != PS_TYPE_F32 ) { 1799 psAbort( __func__, 1800 "Only data type PS_TYPE_F32 is currently supported (0x%x).", 1801 in->type.type ); 1802 } 1803 1804 if ( mask != NULL ) { 1805 if ( in->n != mask->n ) { 1806 psAbort( __func__, 1807 "Vector data and vector mask are of different sizes." ); 1808 } 1809 if ( mask->type.type != PS_TYPE_U8 ) { 1810 psAbort( __func__, "Vector mask must be type PS_TYPE_U8" ); 1695 if (in == NULL) { 1696 return (out); 1697 } 1698 1699 if (in->type.type != PS_TYPE_F32) { 1700 psAbort(__func__, "Only data type PS_TYPE_F32 is currently supported (0x%x).", in->type.type); 1701 } 1702 1703 if (mask != NULL) { 1704 if (in->n != mask->n) { 1705 psAbort(__func__, "Vector data and vector mask are of different sizes."); 1706 } 1707 if (mask->type.type != PS_TYPE_U8) { 1708 psAbort(__func__, "Vector mask must be type PS_TYPE_U8"); 1811 1709 } 1812 1710 } … … 1815 1713 1816 1714 numBins = out->nums->n; 1817 for ( i = 0;i < in->n;i++) {1715 for (i = 0; i < in->n; i++) { 1818 1716 // Check if this pixel is masked, and if so, skip it. 1819 if ( ( mask == NULL ) || 1820 ( ( mask != NULL ) && ( !( mask->data.U8[ i ] & maskVal ) ) ) ) { 1717 if ((mask == NULL) || ((mask != NULL) && (!(mask->data.U8[i] & maskVal)))) { 1821 1718 // Check if this pixel is below the minimum value, and if so 1822 1719 // count it, then skip it. 1823 if ( in->data.F32[ i ] < out->bounds->data.F32[ 0 ]) {1720 if (in->data.F32[i] < out->bounds->data.F32[0]) { 1824 1721 out->minNum++; 1825 1722 // Check if this pixel is above the maximum value, and if so 1826 1723 // count it, then skip it. 1827 } else 1828 if ( in->data.F32[ i ] > out->bounds->data.F32[ numBins ] ) { 1829 out->maxNum++; 1724 } else if (in->data.F32[i] > out->bounds->data.F32[numBins]) { 1725 out->maxNum++; 1726 } else { 1727 // If this is a uniform histogram, determining the correct 1728 // number is trivial. 1729 if (out->uniform == true) { 1730 binSize = out->bounds->data.F32[1] - out->bounds->data.F32[0]; 1731 binNum = (int)((in->data.F32[i] - out->bounds->data.F32[0]) / binSize); 1732 1733 // NOTE: This next if-statement really shouldn't be necessary. 1734 // However, do to numerical lack of precision, we occasionally 1735 // produce a binNum outside the range of bins. 1736 if (binNum >= out->nums->n) { 1737 binNum = out->nums->n - 1; 1738 } 1739 1740 (out->nums->data.S32[binNum])++; 1741 1742 // If this is a non-uniform histogram, determining the correct 1743 // bin number requires a bit more work. 1830 1744 } else { 1831 // If this is a uniform histogram, determining the correct 1832 // number is trivial. 1833 if ( out->uniform == true ) { 1834 binSize = out->bounds->data.F32[ 1 ] - out->bounds->data.F32[ 0 ]; 1835 binNum = ( int ) ( ( in->data.F32[ i ] - out->bounds->data.F32[ 0 ] ) / 1836 binSize ); 1837 1838 // NOTE: This next if-statement really shouldn't be necessary. 1839 // However, do to numerical lack of precision, we occasionally 1840 // produce a binNum outside the range of bins. 1841 if ( binNum >= out->nums->n ) { 1842 binNum = out->nums->n - 1; 1843 } 1844 1845 ( out->nums->data.S32[ binNum ] ) ++; 1846 1847 // If this is a non-uniform histogram, determining the correct 1848 // bin number requires a bit more work. 1849 } else { 1850 // NOTE: This is slow. Put a smarter algorithm here to 1851 // find the correct bin number (bin search, probably) 1852 for ( j = 0;j < ( out->bounds->n ) - 1;j++ ) { 1853 if ( ( out->bounds->data.S32[ j ] <= in->data.F32[ i ] ) && 1854 ( in->data.F32[ i ] <= out->bounds->data.S32[ j + 1 ] ) ) { 1855 ( out->nums->data.S32[ j ] ) ++; 1856 } 1745 // NOTE: This is slow. Put a smarter algorithm here to 1746 // find the correct bin number (bin search, probably) 1747 for (j = 0; j < (out->bounds->n) - 1; j++) { 1748 if ((out->bounds->data.S32[j] <= in->data.F32[i]) && 1749 (in->data.F32[i] <= out->bounds->data.S32[j + 1])) { 1750 (out->nums->data.S32[j])++; 1857 1751 } 1858 1752 } 1859 1753 } 1860 } 1861 } 1862 return ( out ); 1754 } 1755 } 1756 } 1757 return (out); 1863 1758 } 1864 1759 … … 1872 1767 the various stat functions. 1873 1768 *****************************************************************************/ 1874 psVector *p_psConvertToF32( psStats *stats, 1875 psVector *in, 1876 psVector *mask, 1877 unsigned int maskVal ) 1769 psVector *p_psConvertToF32(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal) 1878 1770 { 1879 1771 int i = 0; 1880 1772 psVector *tmp = NULL; 1881 1773 1882 if ( in->type.type == PS_TYPE_S32 ) { 1883 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1884 for ( i = 0;i < in->n;i++ ) { 1885 tmp->data.F32[ i ] = ( float ) in->data.S32[ i ]; 1886 } 1887 } else 1888 if ( in->type.type == PS_TYPE_U32 ) { 1889 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1890 for ( i = 0;i < in->n;i++ ) { 1891 tmp->data.F32[ i ] = ( float ) in->data.U32[ i ]; 1892 } 1893 } else 1894 if ( in->type.type == PS_TYPE_F64 ) { 1895 tmp = psVectorAlloc( in->n, PS_TYPE_F32 ); 1896 for ( i = 0;i < in->n;i++ ) { 1897 tmp->data.F32[ i ] = ( float ) in->data.F64[ i ]; 1898 } 1899 } else 1900 if ( in->type.type == PS_TYPE_F32 ) { 1901 // do nothing 1902 } else { 1903 psAbort( __func__, "unsupported vector type 0x%x\n", in->type.type ); 1904 } 1905 return ( tmp ); 1906 } 1907 1774 if (in->type.type == PS_TYPE_S32) { 1775 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1776 for (i = 0; i < in->n; i++) { 1777 tmp->data.F32[i] = (float)in->data.S32[i]; 1778 } 1779 } else if (in->type.type == PS_TYPE_U32) { 1780 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1781 for (i = 0; i < in->n; i++) { 1782 tmp->data.F32[i] = (float)in->data.U32[i]; 1783 } 1784 } else if (in->type.type == PS_TYPE_F64) { 1785 tmp = psVectorAlloc(in->n, PS_TYPE_F32); 1786 for (i = 0; i < in->n; i++) { 1787 tmp->data.F32[i] = (float)in->data.F64[i]; 1788 } 1789 } else if (in->type.type == PS_TYPE_F32) { 1790 // do nothing 1791 } else { 1792 psAbort(__func__, "unsupported vector type 0x%x\n", in->type.type); 1793 } 1794 return (tmp); 1795 } 1908 1796 1909 1797 /****************************************************************************** … … 1924 1812 macro-ize everything and add PS_TYPE_U16 and PS_TYPE_F64. 1925 1813 *****************************************************************************/ 1926 psStats *psVectorStats( psStats *stats, 1927 psVector *in, 1928 psVector *mask, 1929 unsigned int maskVal ) 1930 { 1931 psVector * inF32; 1814 psStats *psVectorStats(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal) 1815 { 1816 psVector *inF32; 1932 1817 int mustFreeTmp = 1; 1933 1818 1934 1819 // NOTE: Verify that this is the correct action. 1935 if ( in == NULL) {1936 return ( stats);1937 } 1938 if ( stats == NULL) {1939 return ( NULL);1940 } 1941 1942 inF32 = p_psConvertToF32( stats, in, mask, maskVal);1943 if ( inF32 == NULL) {1820 if (in == NULL) { 1821 return (stats); 1822 } 1823 if (stats == NULL) { 1824 return (NULL); 1825 } 1826 1827 inF32 = p_psConvertToF32(stats, in, mask, maskVal); 1828 if (inF32 == NULL) { 1944 1829 inF32 = in; 1945 1830 mustFreeTmp = 0; 1946 1831 } 1947 1948 1832 // XXX: Should we abort if (stats->min == stats->max)? 1949 if ( ( stats->options & PS_STAT_USE_RANGE ) && 1950 ( stats->min >= stats->max ) ) { 1951 psAbort( __func__, "psVectorStats() called with range: %f to %f\n", 1952 stats->min, stats->max ); 1953 } 1954 1955 // PS_CHECK_VECTOR_TYPE(in, PS_TYPE_F32); 1956 if ( mask != NULL ) { 1957 PS_CHECK_NULL_VECTOR( mask ); 1958 PS_CHECK_EMPTY_VECTOR( mask ); 1959 PS_CHECK_VECTOR_SIZE_EQUAL( mask, in ); 1960 PS_CHECK_VECTOR_TYPE( mask, PS_TYPE_U8 ); 1961 } 1962 1833 if ((stats->options & PS_STAT_USE_RANGE) && (stats->min >= stats->max)) { 1834 psAbort(__func__, "psVectorStats() called with range: %f to %f\n", stats->min, stats->max); 1835 } 1836 // PS_CHECK_VECTOR_TYPE(in, PS_TYPE_F32); 1837 if (mask != NULL) { 1838 PS_CHECK_NULL_VECTOR(mask); 1839 PS_CHECK_EMPTY_VECTOR(mask); 1840 PS_CHECK_VECTOR_SIZE_EQUAL(mask, in); 1841 PS_CHECK_VECTOR_TYPE(mask, PS_TYPE_U8); 1842 } 1963 1843 // ************************************************************************ 1964 if ( stats->options & PS_STAT_SAMPLE_MEAN ) { 1965 p_psVectorSampleMean( in, mask, maskVal, stats ); 1966 } 1967 1844 if (stats->options & PS_STAT_SAMPLE_MEAN) { 1845 p_psVectorSampleMean(in, mask, maskVal, stats); 1846 } 1968 1847 // ************************************************************************ 1969 if ( stats->options & PS_STAT_SAMPLE_MEDIAN ) { 1970 p_psVectorSampleMedian( in, mask, maskVal, stats ); 1971 } 1972 1848 if (stats->options & PS_STAT_SAMPLE_MEDIAN) { 1849 p_psVectorSampleMedian(in, mask, maskVal, stats); 1850 } 1973 1851 // ************************************************************************ 1974 1852 // NOTE: The Stdev calculation requires the mean. Should we assume the 1975 // mean has already been calculated? Or should we always calculate it? 1976 if ( stats->options & PS_STAT_SAMPLE_STDEV ) { 1977 p_psVectorSampleMean( in, mask, maskVal, stats ); 1978 p_psVectorSampleStdev( in, mask, maskVal, stats ); 1979 } 1980 1853 // mean has already been calculated? Or should we always calculate it? 1854 if (stats->options & PS_STAT_SAMPLE_STDEV) { 1855 p_psVectorSampleMean(in, mask, maskVal, stats); 1856 p_psVectorSampleStdev(in, mask, maskVal, stats); 1857 } 1981 1858 // ************************************************************************ 1982 if ( stats->options & PS_STAT_SAMPLE_QUARTILE ) { 1983 p_psVectorSampleQuartiles( in, mask, maskVal, stats ); 1984 } 1985 1859 if (stats->options & PS_STAT_SAMPLE_QUARTILE) { 1860 p_psVectorSampleQuartiles(in, mask, maskVal, stats); 1861 } 1986 1862 // Since the various robust stats quantities share much computation, they 1987 1863 // are grouped together in a single private function: 1988 1864 // p_psVectorRobustStats() 1989 if ( ( stats->options & PS_STAT_ROBUST_MEAN ) || 1990 ( stats->options & PS_STAT_ROBUST_MEDIAN ) || 1991 ( stats->options & PS_STAT_ROBUST_MODE ) || 1992 ( stats->options & PS_STAT_ROBUST_STDEV ) || 1993 ( stats->options & PS_STAT_ROBUST_QUARTILE ) ) { 1994 p_psVectorRobustStats( in, mask, maskVal, stats ); 1995 } 1996 1997 if ( ( stats->options & PS_STAT_CLIPPED_MEAN ) || 1998 ( stats->options & PS_STAT_CLIPPED_STDEV ) ) { 1999 p_psVectorClippedStats( in, mask, maskVal, stats ); 2000 } 2001 1865 if ((stats->options & PS_STAT_ROBUST_MEAN) || 1866 (stats->options & PS_STAT_ROBUST_MEDIAN) || 1867 (stats->options & PS_STAT_ROBUST_MODE) || 1868 (stats->options & PS_STAT_ROBUST_STDEV) || (stats->options & PS_STAT_ROBUST_QUARTILE)) { 1869 p_psVectorRobustStats(in, mask, maskVal, stats); 1870 } 1871 1872 if ((stats->options & PS_STAT_CLIPPED_MEAN) || (stats->options & PS_STAT_CLIPPED_STDEV)) { 1873 p_psVectorClippedStats(in, mask, maskVal, stats); 1874 } 2002 1875 // ************************************************************************ 2003 if ( stats->options & PS_STAT_MAX ) { 2004 p_psVectorMax( in, mask, maskVal, stats ); 2005 } 2006 1876 if (stats->options & PS_STAT_MAX) { 1877 p_psVectorMax(in, mask, maskVal, stats); 1878 } 2007 1879 // ************************************************************************ 2008 if ( stats->options & PS_STAT_MIN) {2009 p_psVectorMin( in, mask, maskVal, stats);2010 } 2011 2012 if ( mustFreeTmp == 1) {2013 psFree( inF32);2014 } 2015 return ( stats);2016 } 1880 if (stats->options & PS_STAT_MIN) { 1881 p_psVectorMin(in, mask, maskVal, stats); 1882 } 1883 1884 if (mustFreeTmp == 1) { 1885 psFree(inF32); 1886 } 1887 return (stats); 1888 } -
trunk/psLib/src/math/psStats.h
r1406 r1407 1 1 2 /** @file psStats.h 2 3 * \brief basic statistical operations … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_STATS_H) 17 # define PS_STATS_H18 # define PS_STATS_H 18 19 19 # include "psVector.h"20 # include "psVector.h" 20 21 21 22 /// @addtogroup Stats … … 26 27 *****************************************************************************/ 27 28 typedef enum { 28 PS_STAT_SAMPLE_MEAN = 0x000001,29 PS_STAT_SAMPLE_MEDIAN = 0x000002,30 PS_STAT_SAMPLE_STDEV = 0x000004,31 PS_STAT_SAMPLE_QUARTILE = 0x000008,32 PS_STAT_ROBUST_MEAN = 0x000010,33 PS_STAT_ROBUST_MEDIAN = 0x000020,34 PS_STAT_ROBUST_MODE = 0x000040,35 PS_STAT_ROBUST_STDEV = 0x000080,36 PS_STAT_ROBUST_QUARTILE = 0x000100,37 PS_STAT_CLIPPED_MEAN = 0x000200,38 PS_STAT_CLIPPED_STDEV = 0x000400,39 PS_STAT_MAX = 0x000800,40 PS_STAT_MIN = 0x001000,41 PS_STAT_USE_RANGE = 0x002000,42 PS_STAT_USE_BINSIZE = 0x004000,43 PS_STAT_ROBUST_FOR_SAMPLE = 0x00800029 PS_STAT_SAMPLE_MEAN = 0x000001, 30 PS_STAT_SAMPLE_MEDIAN = 0x000002, 31 PS_STAT_SAMPLE_STDEV = 0x000004, 32 PS_STAT_SAMPLE_QUARTILE = 0x000008, 33 PS_STAT_ROBUST_MEAN = 0x000010, 34 PS_STAT_ROBUST_MEDIAN = 0x000020, 35 PS_STAT_ROBUST_MODE = 0x000040, 36 PS_STAT_ROBUST_STDEV = 0x000080, 37 PS_STAT_ROBUST_QUARTILE = 0x000100, 38 PS_STAT_CLIPPED_MEAN = 0x000200, 39 PS_STAT_CLIPPED_STDEV = 0x000400, 40 PS_STAT_MAX = 0x000800, 41 PS_STAT_MIN = 0x001000, 42 PS_STAT_USE_RANGE = 0x002000, 43 PS_STAT_USE_BINSIZE = 0x004000, 44 PS_STAT_ROBUST_FOR_SAMPLE = 0x008000 44 45 } psStatsOptions; 45 46 46 47 47 /** This is the generic statistics structure. It contails the data members … … 50 50 typedef struct 51 51 { 52 double sampleMean; // /< formal mean of sample53 double sampleMedian; // /< formal median of sample54 double sampleStdev; // /< standard deviation of sample55 double sampleUQ; // /< upper quartile of sample56 double sampleLQ; // /< lower quartile of sample57 double sampleLimit; // /<58 double robustMean; // /< robust mean of array59 double robustMedian; // /< robust median of array60 double robustMode; // /< Robust mode of array61 double robustStdev; // /< robust standard deviation of array62 double robustUQ; // /< robust upper quartile63 double robustLQ; // /< robust lower quartile52 double sampleMean; // /< formal mean of sample 53 double sampleMedian; // /< formal median of sample 54 double sampleStdev; // /< standard deviation of sample 55 double sampleUQ; // /< upper quartile of sample 56 double sampleLQ; // /< lower quartile of sample 57 double sampleLimit; // /< 58 double robustMean; // /< robust mean of array 59 double robustMedian; // /< robust median of array 60 double robustMode; // /< Robust mode of array 61 double robustStdev; // /< robust standard deviation of array 62 double robustUQ; // /< robust upper quartile 63 double robustLQ; // /< robust lower quartile 64 64 double XXX; 65 double robustN50; // /<66 double robustNfit; // /<67 double clippedMean; // /< Nsigma clipped mean68 double clippedStdev; // /< standard deviation after clipping69 double clipSigma; // /< Nsigma used for clipping; user input70 int clipIter; ///< Number of clipping iterations; user input71 double min; // /< minimum data value in array72 double max; // /< maximum data value in array73 double binsize; // /<74 psStatsOptions options; // /< bitmask of calculated values65 double robustN50; // /< 66 double robustNfit; // /< 67 double clippedMean; // /< Nsigma clipped mean 68 double clippedStdev; // /< standard deviation after clipping 69 double clipSigma; // /< Nsigma used for clipping; user input 70 int clipIter; // /< Number of clipping iterations; user input 71 double min; // /< minimum data value in array 72 double max; // /< maximum data value in array 73 double binsize; // /< 74 psStatsOptions options; // /< bitmask of calculated values 75 75 } 76 76 psStats; 77 77 78 79 78 /** Do Statistics on an array. Returns a status value. \ingroup MathGroup */ 80 psStats * 81 psVectorStats(psStats *stats, ///< stats structure defines stats to be calculated and how 82 psVector *in, ///< Vector to be analysed: must be F32 83 psVector *mask, ///< Ignore elements where (maskVector & maskVal) != 0: must be INT or NULL 84 unsigned int maskVal ///< Only mask elements with one of these bits set in maskVector 85 ); 79 psStats *psVectorStats(psStats * stats, // /< stats structure defines stats to be calculated and how 80 psVector * in, // /< Vector to be analysed: must be F32 81 psVector * mask, // /< Ignore elements where (maskVector & maskVal) != 0: must be INT 82 // or NULL 83 unsigned int maskVal // /< Only mask elements with one of these bits set in 84 // maskVector 85 ); 86 86 87 87 /** A constructor for the stats structure.*/ 88 psStats *psStatsAlloc(psStatsOptions options); ///< Statistics to measure88 psStats *psStatsAlloc(psStatsOptions options); // /< Statistics to measure 89 89 90 90 /****************************************************************************** 91 91 Histogram functions and data structures. 92 92 *****************************************************************************/ 93 93 94 /** The basic histogram structure which contains bounds and bins. */ 94 95 typedef struct 95 96 { 96 psVector *bounds; ///< Bounds for the bins (type F32)97 psVector *nums; ///< Number in each of the bins (INT)98 int minNum; ///< Number below the minimum99 int maxNum; ///< Number above the maximum100 bool uniform; ///< Is it a uniform distribution?97 psVector *bounds; // /< Bounds for the bins (type F32) 98 psVector *nums; // /< Number in each of the bins (INT) 99 int minNum; // /< Number below the minimum 100 int maxNum; // /< Number above the maximum 101 bool uniform; // /< Is it a uniform distribution? 101 102 } 102 103 psHistogram; 103 104 104 105 105 /** Constructor \ingroup MathGroup */ 106 psHistogram * 107 psHistogramAlloc(float lower, ///< Lower limit for the bins 108 float upper, ///< Upper limit for the bins 109 int n); ///< Number of bins 110 106 psHistogram *psHistogramAlloc(float lower, // /< Lower limit for the bins 107 float upper, // /< Upper limit for the bins 108 int n); // /< Number of bins 111 109 112 110 /** Generic constructor \ingroup MathGroup */ 113 psHistogram * psHistogramAllocGeneric(const psVector *restrict bounds); ///< Bounds for the bins111 psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds); // /< Bounds for the bins 114 112 115 113 /** Calculate a histogram \ingroup MathGroup **/ 116 psHistogram *psVectorHistogram (psHistogram *out, ///< Histogram data117 const psVector *restrict in, ///< Vector to analyse118 const psVector *restrict mask, ///< Mask dat for input vector119 unsigned int maskVal); ///< Mask value114 psHistogram *psVectorHistogram(psHistogram * out, // /< Histogram data 115 const psVector * restrict in, // /< Vector to analyse 116 const psVector * restrict mask, // /< Mask dat for input vector 117 unsigned int maskVal); // /< Mask value 120 118 121 bool p_psGetStatValue( 122 const psStats* stats, 123 double* value 124 ); 119 bool p_psGetStatValue(const psStats * stats, double *value); 125 120 126 121 /// @} 127 122 128 123 #endif 129 -
trunk/psLib/src/mathtypes/psImage.c
r1406 r1407 1 1 2 /** @file psImage.c 2 3 * … … 9 10 * @author Ross Harman, MHPCC 10 11 * 11 * @version $Revision: 1.3 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.38 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 … … 29 32 #include "psImage.h" 30 33 31 static void imageFree(psImage * image);34 static void imageFree(psImage * image); 32 35 33 36 /*****************************************************************************/ 37 34 38 /* FUNCTION IMPLEMENTATION - PUBLIC */ 39 35 40 /*****************************************************************************/ 36 41 37 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, 38 const psElemType type) 42 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, const psElemType type) 39 43 { 40 44 int area = 0; 41 int elementSize = PSELEMTYPE_SIZEOF(type); // element size in bytes 42 int rowSize = numCols*elementSize; // row size in bytes. 43 44 area = numCols*numRows; 45 int elementSize = PSELEMTYPE_SIZEOF(type); // element 46 47 // size in 48 // bytes 49 int rowSize = numCols * elementSize; // row 50 51 // size 52 53 // in bytes. 54 55 area = numCols * numRows; 45 56 46 57 if (area < 1) { 47 psError(__func__, "Invalid value for number of rows or columns "48 " (numRows=%d, numCols=%d).", numRows, numCols);58 psError(__func__, 59 "Invalid value for number of rows or columns " "(numRows=%d, numCols=%d).", numRows, numCols); 49 60 return NULL; 50 61 } 51 62 52 psImage *image = (psImage *) psAlloc(sizeof(psImage));53 if(image == NULL) { 54 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__);55 }56 57 p_psMemSetDeallocator(image,(psFreeFcn)imageFree); 58 59 image->data.V = psAlloc(sizeof(void*)*numRows); 60 i f(image->data.V == NULL) {61 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__);62 }63 64 65 image->data.V[0] = psAlloc(area *elementSize);66 if (image->data.V[0] == NULL) {67 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);68 } 69 70 for (int i = 1; i < numRows; i++) {71 image->data.V[i] = (void *)((int8_t*)image->data.V[i-1]+rowSize);72 } 73 74 *(int *)&image->col0 = 0;75 *(int *)&image->row0 = 0;76 *(unsigned int *)&image->numCols = numCols;77 *(unsigned int *)&image->numRows = numRows;78 *(psDimen *)&image->type.dimen = PS_DIMEN_IMAGE;79 *(psElemType *)&image->type.type = type;63 psImage *image = (psImage *) psAlloc(sizeof(psImage)); 64 65 if (image == NULL) { 66 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 67 } 68 69 p_psMemSetDeallocator(image, (psFreeFcn) imageFree); 70 71 image->data.V = psAlloc(sizeof(void *) * numRows); 72 if (image->data.V == NULL) { 73 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 74 } 75 76 image->data.V[0] = psAlloc(area * elementSize); 77 if (image->data.V[0] == NULL) { 78 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 79 } 80 81 for (int i = 1; i < numRows; i++) { 82 image->data.V[i] = (void *)((int8_t *) image->data.V[i - 1] + rowSize); 83 } 84 85 *(int *)&image->col0 = 0; 86 *(int *)&image->row0 = 0; 87 *(unsigned int *)&image->numCols = numCols; 88 *(unsigned int *)&image->numRows = numRows; 89 *(psDimen *) & image->type.dimen = PS_DIMEN_IMAGE; 90 *(psElemType *) & image->type.type = type; 80 91 image->parent = NULL; 81 92 image->nChildren = 0; … … 85 96 } 86 97 87 static void imageFree(psImage * image)98 static void imageFree(psImage * image) 88 99 { 89 100 if (image == NULL) { … … 92 103 93 104 if (image->type.type == PS_TYPE_PTR) { 94 // 2-D array of pointers -- must dereference 105 // 2-D array of pointers -- must 106 // dereference 95 107 unsigned int oldNumRows = image->numRows; 96 108 unsigned int oldNumCols = image->numCols; 97 psPTR *rowPtr;98 99 for (unsigned int row=0;row<oldNumRows;row++) {109 psPTR *rowPtr; 110 111 for (unsigned int row = 0; row < oldNumRows; row++) { 100 112 rowPtr = image->data.PTR[row]; 101 for (unsigned int col =0;col<oldNumCols;col++) {113 for (unsigned int col = 0; col < oldNumCols; col++) { 102 114 psMemDecrRefCounter(rowPtr[col]); 103 115 } … … 112 124 } 113 125 114 psImage* psImageRecycle(psImage* old, 115 unsigned int numCols, 116 unsigned int numRows, 117 const psElemType type) 126 psImage *psImageRecycle(psImage * old, unsigned int numCols, unsigned int numRows, const psElemType type) 118 127 { 119 int elementSize = PSELEMTYPE_SIZEOF(type); // element size in bytes 120 int rowSize = numCols*elementSize; // row size in bytes. 128 int elementSize = PSELEMTYPE_SIZEOF(type); // element 129 130 // size in 131 // bytes 132 int rowSize = numCols * elementSize; // row 133 134 // size 135 136 // in bytes. 121 137 122 138 if (old == NULL) { 123 old = psImageAlloc(numCols, numRows,type);139 old = psImageAlloc(numCols, numRows, type); 124 140 return old; 125 141 } 126 142 127 143 if (old->type.dimen != PS_DIMEN_IMAGE) { 128 psError(__func__, "Can not realloc image because input is not an image.");144 psError(__func__, "Can not realloc image because input is not an image."); 129 145 return NULL; 130 146 } 131 147 132 148 if (old->type.type == PS_TYPE_PTR) { 133 // 2-D array of pointers -- must dereference 149 // 2-D array of pointers -- must 150 // dereference 134 151 unsigned int oldNumRows = old->numRows; 135 152 unsigned int oldNumCols = old->numCols; 136 psPTR *rowPtr;137 138 for (unsigned int row=0;row<oldNumRows;row++) {153 psPTR *rowPtr; 154 155 for (unsigned int row = 0; row < oldNumRows; row++) { 139 156 rowPtr = old->data.PTR[row]; 140 for (unsigned int col =0;col<oldNumCols;col++) {157 for (unsigned int col = 0; col < oldNumCols; col++) { 141 158 psMemDecrRefCounter(rowPtr[col]); 142 159 rowPtr[col] = NULL; … … 146 163 147 164 /* image already the right size/type? */ 148 if (numCols == old->numCols && numRows == old->numRows && 149 type == old->type.type) { 165 if (numCols == old->numCols && numRows == old->numRows && type == old->type.type) { 150 166 return old; 151 167 } 152 153 168 // Resize the image buffer 154 old->data.V[0] = psRealloc(old->data.V[0], numCols * numRows * elementSize);155 old->data.V = (void **) psRealloc(old->data.V,numRows * sizeof(void*));169 old->data.V[0] = psRealloc(old->data.V[0], numCols * numRows * elementSize); 170 old->data.V = (void **)psRealloc(old->data.V, numRows * sizeof(void *)); 156 171 157 172 // recreate the row pointers 158 for (int i = 1; i < numRows; i++) {159 old->data.V[i] = (void *)((int8_t*)old->data.V[i-1]+rowSize);160 } 161 162 *(unsigned int *)&old->numCols = numCols;163 *(unsigned int *)&old->numRows = numRows;164 *(psElemType *)&old->type.type = type;173 for (int i = 1; i < numRows; i++) { 174 old->data.V[i] = (void *)((int8_t *) old->data.V[i - 1] + rowSize); 175 } 176 177 *(unsigned int *)&old->numCols = numCols; 178 *(unsigned int *)&old->numRows = numRows; 179 *(psElemType *) & old->type.type = type; 165 180 166 181 return old; 167 182 } 168 183 169 int psImageFreeChildren(psImage * image)184 int psImageFreeChildren(psImage * image) 170 185 { 171 186 int i = 0; … … 181 196 children = image->children; 182 197 183 for (i=0; i<nChildren; i++) {198 for (i = 0; i < nChildren; i++) { 184 199 if (children[i] != NULL) { 185 200 numFreed++; … … 191 206 image->nChildren = 0; 192 207 image->children = NULL; 193 194 208 195 209 return numFreed; … … 202 216 linear interpolation is performed on the image. 203 217 *****************************************************************************/ 204 psF32 psImagePixelInterpolate( 205 const psImage *input, 206 float x, 207 float y, 208 psF32 unexposedValue, 209 psImageInterpolateMode mode) 218 psF32 psImagePixelInterpolate(const psImage * input, 219 float x, float y, psF32 unexposedValue, psImageInterpolateMode mode) 210 220 { 211 221 212 222 if (input == NULL) { 213 psError(__func__, "Image can not be NULL.");223 psError(__func__, "Image can not be NULL."); 214 224 return unexposedValue; 215 225 } 216 217 226 #define PSIMAGE_PIXEL_INTERPOLATE_CASE(TYPE) \ 218 227 case PS_TYPE_##TYPE: \ … … 243 252 PSIMAGE_PIXEL_INTERPOLATE_CASE(C64); 244 253 default: 245 psError(__func__, "Unsupported image datatype (%d)",input->type.type);254 psError(__func__, "Unsupported image datatype (%d)", input->type.type); 246 255 } 247 256 … … 303 312 PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C32) 304 313 PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C64) 305 306 314 #define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR(TYPE) \ 307 315 inline psF64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \ … … 359 367 return(pixel); \ 360 368 } 361 362 369 #define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(TYPE) \ 363 370 inline psC64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \ … … 428 435 PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C32) 429 436 PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C64) 430 431 -
trunk/psLib/src/mathtypes/psImage.h
r1406 r1407 1 1 2 /** @file psImage.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.2 7$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.28 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 17 18 */ 18 # ifndef PS_IMAGE_H19 # define PS_IMAGE_H19 #ifndef PS_IMAGE_H 20 # define PS_IMAGE_H 20 21 21 # include <complex.h>22 # include <complex.h> 22 23 23 # include "psType.h"24 # include "psType.h" 24 25 25 26 /// @addtogroup Image … … 39 40 typedef struct psImage 40 41 { 41 const psType type; ///< Image data type and dimension.42 const unsigned int numCols; ///< Number of columns in image43 const unsigned int numRows; ///< Number of rows in image.44 const int col0; ///< Column position relative to parent.45 const int row0; ///< Row position relative to parent.42 const psType type; // /< Image data type and dimension. 43 const unsigned int numCols; // /< Number of columns in image 44 const unsigned int numRows; // /< Number of rows in image. 45 const int col0; // /< Column position relative to parent. 46 const int row0; // /< Row position relative to parent. 46 47 47 48 union { 48 psU8 **U8; ///< Unsigned 8-bit integer data.49 psU16 **U16; ///< Unsigned 16-bit integer data.50 psU32 **U32; ///< Unsigned 32-bit integer data.51 psU64 **U64; ///< Unsigned 64-bit integer data.52 psS8 **S8; ///< Signed 8-bit integer data.53 psS16 **S16; ///< Signed 16-bit integer data.54 psS32 **S32; ///< Signed 32-bit integer data.55 psS64 **S64; ///< Signed 64-bit integer data.56 psF32 **F32; ///< Single-precision float data.57 psF64 **F64; ///< Double-precision float data.58 psC32 **C32; ///< Single-precision complex data.59 psC64 **C64; ///< Double-precision complex data.60 psPTR **PTR; ///< Void pointers.61 psPTR *V; ///< Pointer to data.62 } data; ///< Union for data types.63 const struct psImage *parent; // /< Parent, if a subimage.64 int nChildren; ///< Number of subimages.65 struct psImage ** children; ///< Children of this region.49 psU8 **U8; // /< Unsigned 8-bit integer data. 50 psU16 **U16; // /< Unsigned 16-bit integer data. 51 psU32 **U32; // /< Unsigned 32-bit integer data. 52 psU64 **U64; // /< Unsigned 64-bit integer data. 53 psS8 **S8; // /< Signed 8-bit integer data. 54 psS16 **S16; // /< Signed 16-bit integer data. 55 psS32 **S32; // /< Signed 32-bit integer data. 56 psS64 **S64; // /< Signed 64-bit integer data. 57 psF32 **F32; // /< Single-precision float data. 58 psF64 **F64; // /< Double-precision float data. 59 psC32 **C32; // /< Single-precision complex data. 60 psC64 **C64; // /< Double-precision complex data. 61 psPTR **PTR; // /< Void pointers. 62 psPTR *V; // /< Pointer to data. 63 } data; // /< Union for data types. 64 const struct psImage *parent; // /< Parent, if a subimage. 65 int nChildren; // /< Number of subimages. 66 struct psImage **children; // /< Children of this region. 66 67 } 67 68 psImage; 68 69 69 70 /*****************************************************************************/ 71 70 72 /* FUNCTION PROTOTYPES */ 73 71 74 /*****************************************************************************/ 72 73 75 74 76 /** Create an image of the specified size and type. … … 80 82 * 81 83 */ 82 psImage *psImageAlloc( 83 unsigned int numCols, ///< Number of rows in image. 84 unsigned int numRows, ///< Number of columns in image. 85 const psElemType type ///< Type of data for image. 86 ); 84 psImage *psImageAlloc(unsigned int numCols, // /< Number of rows in image. 85 unsigned int numRows, // /< Number of columns in image. 86 const psElemType type // /< Type of data for image. 87 ); 87 88 88 89 /** Resize a given image to the given size/type. … … 91 92 * 92 93 */ 93 psImage* psImageRecycle( 94 psImage* old, ///< the psImage to recycle by resizing image buffer 95 unsigned int numCols, ///< the desired number of columns in image 96 unsigned int numRows, ///< the desired number of rows in image 97 const psElemType type ///< the desired datatype of the image 98 ); 99 94 psImage *psImageRecycle(psImage * old, // /< the psImage to recycle by resizing image buffer 95 unsigned int numCols, // /< the desired number of columns in image 96 unsigned int numRows, // /< the desired number of rows in image 97 const psElemType type // /< the desired datatype of the image 98 ); 100 99 101 100 /** Frees all children of a psImage. … … 104 103 * 105 104 */ 106 int psImageFreeChildren( 107 psImage* image 108 /**< psImage in which all children shall be deallocated */ 109 ); 105 int psImageFreeChildren(psImage * image 110 106 111 psF32 psImagePixelInterpolate( 112 const psImage *input, 113 float x, 114 float y, 115 psF32 unexposedValue, 116 psImageInterpolateMode mode 117 ); 107 /**< psImage in which all children shall be deallocated */ 108 ); 118 109 119 #define p_psImagePixelInterpolateFcns(TYPE) \ 110 psF32 psImagePixelInterpolate(const psImage * input, 111 float x, float y, psF32 unexposedValue, psImageInterpolateMode mode); 112 113 # define p_psImagePixelInterpolateFcns(TYPE) \ 120 114 inline psF64 p_psImagePixelInterpolateFLAT_##TYPE( \ 121 115 const psImage *input, \ … … 131 125 ); 132 126 133 # define p_psImagePixelInterpolateComplexFcns(TYPE) \127 # define p_psImagePixelInterpolateComplexFcns(TYPE) \ 134 128 inline psC64 p_psImagePixelInterpolateFLAT_##TYPE( \ 135 129 const psImage *input, \ … … 157 151 p_psImagePixelInterpolateComplexFcns(C32) 158 152 p_psImagePixelInterpolateComplexFcns(C64) 159 160 153 /// @} 161 162 154 #endif -
trunk/psLib/src/mathtypes/psScalar.c
r1406 r1407 1 1 2 /** @file psScalar.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 22 #include "psMemory.h" … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 psScalar *psScalarAlloc(psC64 value, psElemType dataType) … … 61 76 62 77 // Create scalar 63 scalar = (psScalar *) psAlloc(sizeof(psScalar));64 if (scalar == NULL) {65 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);78 scalar = (psScalar *) psAlloc(sizeof(psScalar)); 79 if (scalar == NULL) { 80 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 66 81 } 67 82 … … 71 86 switch (dataType) { 72 87 case PS_TYPE_S8: 73 scalar->data.S8 = (psS8) value;88 scalar->data.S8 = (psS8) value; 74 89 break; 75 90 case PS_TYPE_U8: 76 scalar->data.U8 = (psU8) value;91 scalar->data.U8 = (psU8) value; 77 92 break; 78 93 case PS_TYPE_S16: 79 scalar->data.S16 = (psS16) value;94 scalar->data.S16 = (psS16) value; 80 95 break; 81 96 case PS_TYPE_U16: 82 scalar->data.U16 = (psU16) value;97 scalar->data.U16 = (psU16) value; 83 98 break; 84 99 case PS_TYPE_S32: 85 scalar->data.S32 = (psS32) value;100 scalar->data.S32 = (psS32) value; 86 101 break; 87 102 case PS_TYPE_U32: 88 scalar->data.U32 = (psU32) value;103 scalar->data.U32 = (psU32) value; 89 104 break; 90 105 case PS_TYPE_S64: 91 scalar->data.S64 = (psS64) value;106 scalar->data.S64 = (psS64) value; 92 107 break; 93 108 case PS_TYPE_U64: 94 scalar->data.U64 = (psU64) value;109 scalar->data.U64 = (psU64) value; 95 110 break; 96 111 case PS_TYPE_F32: 97 scalar->data.F32 = (psF32) value;112 scalar->data.F32 = (psF32) value; 98 113 break; 99 114 case PS_TYPE_F64: 100 scalar->data.F64 = (psF64) value;115 scalar->data.F64 = (psF64) value; 101 116 break; 102 117 case PS_TYPE_C32: 103 scalar->data.C32 = (psC32) value;118 scalar->data.C32 = (psC32) value; 104 119 break; 105 120 case PS_TYPE_C64: 106 scalar->data.C64 = (psC64) value;121 scalar->data.C64 = (psC64) value; 107 122 break; 108 123 default: … … 110 125 } 111 126 112 113 127 return scalar; 114 128 } 115 129 116 void psScalarFree(psScalar * restrict scalar)130 void psScalarFree(psScalar * restrict scalar) 117 131 { 118 132 if (scalar == NULL) { … … 122 136 psFree(scalar); 123 137 } 124 125 -
trunk/psLib/src/mathtypes/psScalar.h
r1406 r1407 1 1 2 /** @file psScalar.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1. 3$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.4 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_SCALAR_H 19 # define PS_SCALAR_H20 # define PS_SCALAR_H 20 21 21 # include "psType.h"22 # include "psType.h" 22 23 23 24 /// @addtogroup Scalar … … 31 32 typedef struct 32 33 { 33 psType type; ///< Type of data.34 psType type; // /< Type of data. 34 35 35 36 union { 36 psU8 U8; ///< Unsigned 8-bit integer data.37 psU16 U16; ///< Unsigned 16-bit integer data.38 psU32 U32; ///< Unsigned 32-bit integer data.39 psU64 U64; ///< Unsigned 64-bit integer data.40 psS8 S8; ///< Signed 8-bit integer data.41 psS16 S16; ///< Signed 16-bit integer data.42 psS32 S32; ///< Signed 32-bit integer data.43 psS64 S64; ///< Signed 64-bit integer data.44 psF32 F32; ///< Single-precision float data.45 psF64 F64; ///< Double-precision float data.46 psC32 C32; ///< Single-precision complex data.47 psC64 C64; ///< Double-precision complex data.48 } data; ///< Union for data types.37 psU8 U8; // /< Unsigned 8-bit integer data. 38 psU16 U16; // /< Unsigned 16-bit integer data. 39 psU32 U32; // /< Unsigned 32-bit integer data. 40 psU64 U64; // /< Unsigned 64-bit integer data. 41 psS8 S8; // /< Signed 8-bit integer data. 42 psS16 S16; // /< Signed 16-bit integer data. 43 psS32 S32; // /< Signed 32-bit integer data. 44 psS64 S64; // /< Signed 64-bit integer data. 45 psF32 F32; // /< Single-precision float data. 46 psF64 F64; // /< Double-precision float data. 47 psC32 C32; // /< Single-precision complex data. 48 psC64 C64; // /< Double-precision complex data. 49 } data; // /< Union for data types. 49 50 } 50 51 psScalar; 51 52 52 53 /*****************************************************************************/ 54 53 55 /* FUNCTION PROTOTYPES */ 56 54 57 /*****************************************************************************/ 55 58 … … 62 65 * 63 66 */ 64 psScalar *psScalarAlloc( 65 psC64 value, ///< Data to be put into psScalar. 66 psElemType dataType ///< Type of data to be held by psScalar. 67 ); 68 67 psScalar *psScalarAlloc(psC64 value, // /< Data to be put into psScalar. 68 psElemType dataType // /< Type of data to be held by psScalar. 69 ); 69 70 70 71 /** Deallocate a scalar. … … 75 76 * 76 77 */ 77 void psScalarFree( 78 psScalar *restrict scalar ///< Scalar to free. 79 ); 78 void psScalarFree(psScalar * restrict scalar // /< Scalar to free. 79 ); 80 80 81 81 /// @} -
trunk/psLib/src/mathtypes/psVector.c
r1406 r1407 1 1 2 /** @file psVector.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1.2 0$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.21 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 18 /******************************************************************************/ 19 #include <string.h> // for memcpy 20 21 /******************************************************************************/ 22 #include <string.h> // for memcpy 20 23 #include <stdlib.h> 21 24 #include <math.h> … … 28 31 29 32 /******************************************************************************/ 33 30 34 /* DEFINE STATEMENTS */ 35 31 36 /******************************************************************************/ 32 37 … … 34 39 35 40 /******************************************************************************/ 41 36 42 /* TYPE DEFINITIONS */ 43 37 44 /******************************************************************************/ 38 45 … … 40 47 41 48 /*****************************************************************************/ 49 42 50 /* GLOBAL VARIABLES */ 51 43 52 /*****************************************************************************/ 44 53 … … 46 55 47 56 /*****************************************************************************/ 57 48 58 /* FILE STATIC VARIABLES */ 59 49 60 /*****************************************************************************/ 50 61 … … 52 63 53 64 /*****************************************************************************/ 65 54 66 /* FUNCTION IMPLEMENTATION - LOCAL */ 55 /*****************************************************************************/ 56 static void vectorFree( psVector *restrict psVec ); 57 58 /*****************************************************************************/ 67 68 /*****************************************************************************/ 69 static void vectorFree(psVector * restrict psVec); 70 71 /*****************************************************************************/ 72 59 73 /* FUNCTION IMPLEMENTATION - PUBLIC */ 60 /*****************************************************************************/ 61 psVector* psVectorAlloc( unsigned int nalloc, psElemType elemType ) 62 { 63 psVector * psVec = NULL; 74 75 /*****************************************************************************/ 76 psVector *psVectorAlloc(unsigned int nalloc, psElemType elemType) 77 { 78 psVector *psVec = NULL; 64 79 int elementSize = 0; 65 80 66 81 // Invalid nalloc 67 if ( nalloc < 1) {68 psError( __func__, "Invalid value for nalloc. nalloc: %d\n", nalloc);82 if (nalloc < 1) { 83 psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc); 69 84 return NULL; 70 85 } 71 86 72 elementSize = PSELEMTYPE_SIZEOF( elemType);87 elementSize = PSELEMTYPE_SIZEOF(elemType); 73 88 74 89 // Create vector struct 75 psVec = ( psVector * ) psAlloc( sizeof( psVector ));76 p_psMemSetDeallocator( psVec, ( psFreeFcn ) vectorFree);90 psVec = (psVector *) psAlloc(sizeof(psVector)); 91 p_psMemSetDeallocator(psVec, (psFreeFcn) vectorFree); 77 92 78 93 psVec->type.dimen = PS_DIMEN_VECTOR; … … 82 97 83 98 // Create vector data array 84 psVec->data.V = psAlloc( nalloc * elementSize);99 psVec->data.V = psAlloc(nalloc * elementSize); 85 100 86 101 return psVec; 87 102 } 88 103 89 psVector *psVectorRealloc( unsigned int nalloc, psVector *restrict in)104 psVector *psVectorRealloc(unsigned int nalloc, psVector * restrict in) 90 105 { 91 106 int elementSize = 0; … … 93 108 94 109 // Invalid nalloc 95 if ( nalloc < 1) {96 psError( __func__, "Invalid value for realloc (%d)\n", nalloc);110 if (nalloc < 1) { 111 psError(__func__, "Invalid value for realloc (%d)\n", nalloc); 97 112 return NULL; 98 113 } 99 114 100 if ( in == NULL) {101 psError( __func__, "Null input vector\n");115 if (in == NULL) { 116 psError(__func__, "Null input vector\n"); 102 117 return NULL; 103 } else 104 if ( in->nalloc != nalloc ) { // No need to realloc to same size 105 elemType = in->type.type; 106 elementSize = PSELEMTYPE_SIZEOF( elemType ); 107 if ( nalloc < in->n ) { 108 in->n = nalloc; 109 } 110 111 // Realloc after decrementation to avoid accessing freed array elements 112 in->data.V = psRealloc( in->data.V, nalloc * elementSize ); 113 in->nalloc = nalloc; 118 } else if (in->nalloc != nalloc) { // No need to realloc to same size 119 elemType = in->type.type; 120 elementSize = PSELEMTYPE_SIZEOF(elemType); 121 if (nalloc < in->n) { 122 in->n = nalloc; 114 123 } 124 // Realloc after decrementation to avoid accessing freed array elements 125 in->data.V = psRealloc(in->data.V, nalloc * elementSize); 126 in->nalloc = nalloc; 127 } 115 128 116 129 return in; 117 130 } 118 131 119 psVector *psVectorRecycle( psVector *restrict in, unsigned int nalloc, psElemType type)132 psVector *psVectorRecycle(psVector * restrict in, unsigned int nalloc, psElemType type) 120 133 { 121 134 psElemType elemType; 122 135 123 if ( in == NULL) {124 return psVectorAlloc( nalloc, type);136 if (in == NULL) { 137 return psVectorAlloc(nalloc, type); 125 138 } 126 139 127 140 elemType = in->type.type; 128 141 129 if ( in->nalloc == nalloc && elemType == type) {142 if (in->nalloc == nalloc && elemType == type) { 130 143 // it is proper size/type already 131 144 return in; 132 145 } 133 134 146 // Invalid nalloc 135 if ( nalloc < 1) {136 psError( __func__, "Invalid value for nalloc (%d)\n", nalloc);137 psFree( in);147 if (nalloc < 1) { 148 psError(__func__, "Invalid value for nalloc (%d)\n", nalloc); 149 psFree(in); 138 150 return NULL; 139 151 } 140 152 141 142 in->data.V = psRealloc( in->data.V, nalloc * PSELEMTYPE_SIZEOF( type ) ); 153 in->data.V = psRealloc(in->data.V, nalloc * PSELEMTYPE_SIZEOF(type)); 143 154 144 155 in->type.type = type; … … 149 160 } 150 161 151 psVector *psVectorSort( psVector *restrict outVector, const psVector *restrict inVector)162 psVector *psVectorSort(psVector * restrict outVector, const psVector * restrict inVector) 152 163 { 153 164 int inN = 0; … … 158 169 psElemType inType = 0; 159 170 160 if ( inVector == NULL) {161 psError( __func__, " : Line %d - Null input vector\n", __LINE__);171 if (inVector == NULL) { 172 psError(__func__, " : Line %d - Null input vector\n", __LINE__); 162 173 return outVector; 163 174 } … … 166 177 inN = inVector->n; 167 178 inVec = inVector->data.V; 168 elSize = PSELEMTYPE_SIZEOF( inType);169 170 if ( outVector == NULL) {171 outVector = psVectorAlloc( inN, inType);179 elSize = PSELEMTYPE_SIZEOF(inType); 180 181 if (outVector == NULL) { 182 outVector = psVectorAlloc(inN, inType); 172 183 outVector->n = inVector->n; 173 184 } … … 176 187 outVec = outVector->data.V; 177 188 178 if ( inN != outN ) { 179 psError( __func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", __LINE__, 180 inN, outN ); 181 return outVector; 182 } 183 184 if ( inType != outVector->type.type ) { 185 psError( __func__, " : Line %d - Input and output vectors are not same type: in=%d out=%d\n", __LINE__, 186 inType, outVector->type.type ); 187 return outVector; 188 } 189 190 if ( inN == 0 ) { 191 psError( __func__, " : Line %d - No elements in use for input vector\n", __LINE__ ); 192 return outVector; 193 } 194 195 if ( outN == 0 ) { 196 psError( __func__, " : Line %d - No elements in use for output vector\n", __LINE__ ); 197 return outVector; 198 } 199 189 if (inN != outN) { 190 psError(__func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", 191 __LINE__, inN, outN); 192 return outVector; 193 } 194 195 if (inType != outVector->type.type) { 196 psError(__func__, " : Line %d - Input and output vectors are not same type: in=%d out=%d\n", __LINE__, 197 inType, outVector->type.type); 198 return outVector; 199 } 200 201 if (inN == 0) { 202 psError(__func__, " : Line %d - No elements in use for input vector\n", __LINE__); 203 return outVector; 204 } 205 206 if (outN == 0) { 207 psError(__func__, " : Line %d - No elements in use for output vector\n", __LINE__); 208 return outVector; 209 } 200 210 // Copy input vector values into output vector 201 memcpy( outVec, inVec, elSize * outN);211 memcpy(outVec, inVec, elSize * outN); 202 212 203 213 // Sort output vector 204 switch ( inType) {214 switch (inType) { 205 215 case PS_TYPE_U8: 206 qsort( outVec, inN, elSize, psCompareU8);216 qsort(outVec, inN, elSize, psCompareU8); 207 217 break; 208 218 case PS_TYPE_U16: 209 qsort( outVec, inN, elSize, psCompareU16);219 qsort(outVec, inN, elSize, psCompareU16); 210 220 break; 211 221 case PS_TYPE_U32: 212 qsort( outVec, inN, elSize, psCompareU32);222 qsort(outVec, inN, elSize, psCompareU32); 213 223 break; 214 224 case PS_TYPE_U64: 215 qsort( outVec, inN, elSize, psCompareU64);225 qsort(outVec, inN, elSize, psCompareU64); 216 226 break; 217 227 case PS_TYPE_S8: 218 qsort( outVec, inN, elSize, psCompareS8);228 qsort(outVec, inN, elSize, psCompareS8); 219 229 break; 220 230 case PS_TYPE_S16: 221 qsort( outVec, inN, elSize, psCompareS16);231 qsort(outVec, inN, elSize, psCompareS16); 222 232 break; 223 233 case PS_TYPE_S32: 224 qsort( outVec, inN, elSize, psCompareS32);234 qsort(outVec, inN, elSize, psCompareS32); 225 235 break; 226 236 case PS_TYPE_S64: 227 qsort( outVec, inN, elSize, psCompareS64);237 qsort(outVec, inN, elSize, psCompareS64); 228 238 break; 229 239 case PS_TYPE_F32: 230 qsort( outVec, inN, elSize, psCompareF32);240 qsort(outVec, inN, elSize, psCompareF32); 231 241 break; 232 242 case PS_TYPE_F64: 233 qsort( outVec, inN, elSize, psCompareF64);243 qsort(outVec, inN, elSize, psCompareF64); 234 244 break; 235 245 default: 236 psError( __func__, " : Line %d - Invalid psType\n", __LINE__);246 psError(__func__, " : Line %d - Invalid psType\n", __LINE__); 237 247 } 238 248 … … 251 261 } 252 262 253 psVector *psVectorSortIndex( psVector *restrict outVector, const psVector *restrict inVector)263 psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector) 254 264 { 255 265 int inN = 0; … … 263 273 psElemType inType = 0; 264 274 265 if ( inVector == NULL) {266 psError( __func__, " : Line %d - Null input vector\n", __LINE__);275 if (inVector == NULL) { 276 psError(__func__, " : Line %d - Null input vector\n", __LINE__); 267 277 return outVector; 268 278 } … … 272 282 inType = inVector->type.type; 273 283 274 if ( outVector == NULL) {275 outVector = psVectorAlloc( inN, PS_TYPE_U32);284 if (outVector == NULL) { 285 outVector = psVectorAlloc(inN, PS_TYPE_U32); 276 286 outVector->n = inN; 277 287 } … … 280 290 outVec = outVector->data.V; 281 291 282 if ( inN != outN) {283 psError( __func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n",284 __LINE__, inN, outN);285 return outVector; 286 } 287 288 if ( outVector->type.type != PS_TYPE_U32) {289 psError( __func__, " : Line %d - Output vector is not of type U32: out=%d\n",290 __LINE__, outVector->type.type);291 return outVector; 292 } 293 294 tmpVector = psVectorAlloc( inN, inType);292 if (inN != outN) { 293 psError(__func__, " : Line %d - Input and output vector sizes are not equal: in=%d out=%d\n", 294 __LINE__, inN, outN); 295 return outVector; 296 } 297 298 if (outVector->type.type != PS_TYPE_U32) { 299 psError(__func__, " : Line %d - Output vector is not of type U32: out=%d\n", 300 __LINE__, outVector->type.type); 301 return outVector; 302 } 303 304 tmpVector = psVectorAlloc(inN, inType); 295 305 tmpVector->n = inN; 296 tmpVector = psVectorSort( tmpVector, inVector);306 tmpVector = psVectorSort(tmpVector, inVector); 297 307 298 308 // Sort output vector 299 switch ( inType) {309 switch (inType) { 300 310 case PS_TYPE_U8: 301 SORT_INDICES( U8);311 SORT_INDICES(U8); 302 312 break; 303 313 case PS_TYPE_U16: 304 SORT_INDICES( U16);314 SORT_INDICES(U16); 305 315 break; 306 316 case PS_TYPE_U32: 307 SORT_INDICES( U32);317 SORT_INDICES(U32); 308 318 break; 309 319 case PS_TYPE_U64: 310 SORT_INDICES( U64);320 SORT_INDICES(U64); 311 321 break; 312 322 case PS_TYPE_S8: 313 SORT_INDICES( S8);323 SORT_INDICES(S8); 314 324 break; 315 325 case PS_TYPE_S16: 316 SORT_INDICES( S16);326 SORT_INDICES(S16); 317 327 break; 318 328 case PS_TYPE_S32: 319 SORT_INDICES( S32);329 SORT_INDICES(S32); 320 330 break; 321 331 case PS_TYPE_S64: 322 SORT_INDICES( S64);332 SORT_INDICES(S64); 323 333 break; 324 334 case PS_TYPE_F32: 325 SORT_INDICES( F32);335 SORT_INDICES(F32); 326 336 break; 327 337 case PS_TYPE_F64: 328 SORT_INDICES( F64);338 SORT_INDICES(F64); 329 339 break; 330 340 default: 331 psError( __func__, " : Line %d - Invalid psType\n", __LINE__);341 psError(__func__, " : Line %d - Invalid psType\n", __LINE__); 332 342 } 333 343 334 344 // Free temp memory 335 psFree( tmpVector);345 psFree(tmpVector); 336 346 337 347 return outVector; 338 348 } 339 349 340 static void vectorFree( psVector *restrict psVec)341 { 342 if ( psVec == NULL) {343 return ;344 } 345 346 psFree( psVec->data.V);347 } 350 static void vectorFree(psVector * restrict psVec) 351 { 352 if (psVec == NULL) { 353 return; 354 } 355 356 psFree(psVec->data.V); 357 } -
trunk/psLib/src/mathtypes/psVector.h
r1406 r1407 1 1 2 /** @file psVector.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_VECTOR_H 20 # define PS_VECTOR_H21 # define PS_VECTOR_H 21 22 22 # include "psType.h"23 # include "psType.h" 23 24 24 25 /// @addtogroup Vector … … 32 33 typedef struct 33 34 { 34 psType type; ///< Type of data.35 unsigned int nalloc; ///< Total number of elements available.36 unsigned int n; ///< Number of elements in use.35 psType type; // /< Type of data. 36 unsigned int nalloc; // /< Total number of elements available. 37 unsigned int n; // /< Number of elements in use. 37 38 38 39 union { 39 psU8 *U8; ///< Unsigned 8-bit integer data.40 psU16 *U16; ///< Unsigned 16-bit integer data.41 psU32 *U32; ///< Unsigned 32-bit integer data.42 psU64 *U64; ///< Unsigned 64-bit integer data.43 psS8 *S8; ///< Signed 8-bit integer data.44 psS16 *S16; ///< Signed 16-bit integer data.45 psS32 *S32; ///< Signed 32-bit integer data.46 psS64 *S64; ///< Signed 64-bit integer data.47 psF32 *F32; ///< Single-precision float data.48 psF64 *F64; ///< Double-precision float data.49 psC32 *C32; ///< Single-precision complex data.50 psC64 *C64; ///< Double-precision complex data.51 psPTR V; ///< Pointer to data.52 } data; ///< Union for data types.40 psU8 *U8; // /< Unsigned 8-bit integer data. 41 psU16 *U16; // /< Unsigned 16-bit integer data. 42 psU32 *U32; // /< Unsigned 32-bit integer data. 43 psU64 *U64; // /< Unsigned 64-bit integer data. 44 psS8 *S8; // /< Signed 8-bit integer data. 45 psS16 *S16; // /< Signed 16-bit integer data. 46 psS32 *S32; // /< Signed 32-bit integer data. 47 psS64 *S64; // /< Signed 64-bit integer data. 48 psF32 *F32; // /< Single-precision float data. 49 psF64 *F64; // /< Double-precision float data. 50 psC32 *C32; // /< Single-precision complex data. 51 psC64 *C64; // /< Double-precision complex data. 52 psPTR V; // /< Pointer to data. 53 } data; // /< Union for data types. 53 54 } 54 55 psVector; 55 56 56 57 /*****************************************************************************/ 58 57 59 /* FUNCTION PROTOTYPES */ 60 58 61 /*****************************************************************************/ 59 62 … … 65 68 * 66 69 */ 67 psVector *psVectorAlloc( 68 unsigned int nalloc, ///< Total number of elements to make available. 69 psElemType dataType ///< Type of data to be held by vector. 70 ); 70 psVector *psVectorAlloc(unsigned int nalloc, // /< Total number of elements to make available. 71 psElemType dataType // /< Type of data to be held by vector. 72 ); 71 73 72 74 /** Reallocate a vector. … … 78 80 * 79 81 */ 80 psVector *psVectorRealloc( 81 unsigned int nalloc, ///< Total number of elements to make available. 82 psVector *restrict psVec ///< Vector to reallocate. 83 ); 82 psVector *psVectorRealloc(unsigned int nalloc, // /< Total number of elements to make available. 83 psVector * restrict psVec // /< Vector to reallocate. 84 ); 84 85 85 86 /** Recycle a vector. … … 91 92 * 92 93 */ 93 psVector *psVectorRecycle( 94 psVector *restrict psVec, 95 ///< Vector to recycle. If NULL, a new vector is created. No effort taken to preserve the values. 96 97 unsigned int nalloc, ///< Total number of elements to make available. 98 psElemType type ///< the datatype of the returned vector 99 ); 94 psVector *psVectorRecycle(psVector * restrict psVec, 95 // /< Vector to recycle. If NULL, a new vector is created. No effort taken to 96 // preserve the values. 97 unsigned int nalloc, // /< Total number of elements to make available. 98 psElemType type // /< the datatype of the returned vector 99 ); 100 100 101 101 /** Sort an array of floats. … … 107 107 */ 108 108 109 psVector *psVectorSort( 110 psVector *restrict outVector, ///< the output vector to recycle, or NULL if newvector desired.111 const psVector *restrict inVector ///< the vector to sort.112 );109 psVector *psVectorSort(psVector * restrict outVector, // /< the output vector to recycle, or NULL if new 110 // vector desired. 111 const psVector * restrict inVector // /< the vector to sort. 112 ); 113 113 114 114 /** Creates an array of indices based on sort odred of float array. … … 120 120 */ 121 121 122 psVector *psVectorSortIndex( 123 psVector *restrict outVector, 124 const psVector *restrict inVector 125 ); 126 122 psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector); 127 123 128 124 /// @} -
trunk/psLib/src/pslib.h
r1392 r1407 1 1 2 /** @file pslib.h 2 3 * … … 8 9 * @author Eric Van Alst, MHPCC 9 10 * 10 * @version $Revision: 1.1 8$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 5 17:52:05$11 * @version $Revision: 1.19 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 #ifndef PS_LIB_H 17 # define PS_LIB_H18 # define PS_LIB_H 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 … … 35 38 */ 36 39 37 # include "fitsio.h"40 # include "fitsio.h" 38 41 39 # include "psMemory.h"42 # include "psMemory.h" 40 43 41 44 /// @defgroup LogTrace Tracing and Logging 42 45 /// @ingroup SysUtils 43 # include "psLogMsg.h"44 # include "psTrace.h"46 # include "psLogMsg.h" 47 # include "psTrace.h" 45 48 46 49 /// @defgroup ErrorHandling Error Handling 47 50 /// @ingroup SysUtils 48 # include "psAbort.h"49 # include "psError.h"51 # include "psAbort.h" 52 # include "psError.h" 50 53 51 # include "psString.h"54 # include "psString.h" 52 55 53 56 /// @} … … 57 60 /// @{ 58 61 59 # include "psType.h"62 # include "psType.h" 60 63 61 64 /// @defgroup LinkedList Linked List 62 65 /// @ingroup DataContainer 63 # include "psList.h"66 # include "psList.h" 64 67 65 68 /// @defgroup HashTable Hash Table 66 69 /// @ingroup DataContainer 67 # include "psHash.h"70 # include "psHash.h" 68 71 69 72 /// @defgroup Scalar Scalar 70 73 /// @ingroup DataContainer 71 # include "psScalar.h"74 # include "psScalar.h" 72 75 73 76 /// @defgroup Vector Vector Container 74 77 /// @ingroup DataContainer 75 # include "psVector.h"78 # include "psVector.h" 76 79 77 80 /// @defgroup Array Array Container 78 81 /// @ingroup DataContainer 79 # include "psArray.h"82 # include "psArray.h" 80 83 81 84 /// @defgroup Image Image Container 82 85 /// @ingroup DataContainer 83 86 /// @{ 84 # include "psImage.h"85 # include "psImageExtraction.h"86 # include "psImageManip.h"87 # include "psImage.h" 88 # include "psImageExtraction.h" 89 # include "psImageManip.h" 87 90 88 91 /// @defgroup ImageIO Image File I/O Functions 89 92 /// @ingroup Image 90 #include "psImageIO.h" 91 93 # include "psImageIO.h" 92 94 93 95 /// @defgroup ImageStats Image Statistical Functions 94 96 /// @ingroup Image 95 # include "psImageStats.h"97 # include "psImageStats.h" 96 98 97 99 /// @} … … 99 101 /// @defgroup BitSet Bit Set Container 100 102 /// @ingroup DataContainer 101 # include "psBitSet.h"103 # include "psBitSet.h" 102 104 103 105 /// @} … … 109 111 /// @defgroup Compare Comparison Functions 110 112 /// @ingroup DataManip 111 # include "psCompare.h"113 # include "psCompare.h" 112 114 113 115 /// @defgroup Stats Statistic Functions 114 116 /// @ingroup DataManip 115 # include "psStats.h"117 # include "psStats.h" 116 118 117 119 /// @defgroup Matrix Matrix Operations 118 120 /// @ingroup DataManip 119 # include "psMatrix.h"121 # include "psMatrix.h" 120 122 121 123 /// @defgroup MatrixVectorArithmetic Matrix Vector Arithmetic Operations 122 124 /// @ingroup DataManip 123 # include "psMatrixVectorArithmetic.h"125 # include "psMatrixVectorArithmetic.h" 124 126 125 127 /// @defgroup Transform Fourier Transform Operations 126 128 /// @ingroup DataManip 127 # include "psFFT.h"129 # include "psFFT.h" 128 130 129 # include "psFunctions.h"130 # include "psMinimize.h"131 # include "psFunctions.h" 132 # include "psMinimize.h" 131 133 132 134 /// @} … … 138 140 /// @defgroup CoordinateTransform Coordinate Functions 139 141 /// @ingroup Astronomy 140 # include "psCoord.h"142 # include "psCoord.h" 141 143 142 144 /// @defgroup Photometry Photometry 143 145 /// @ingroup Astronomy 144 # include "psPhotometry.h"146 # include "psPhotometry.h" 145 147 146 148 /// @defgroup Time Time Functions 147 149 /// @ingroup Astronomy 148 # include "psTime.h"150 # include "psTime.h" 149 151 150 152 /// @defgroup Metadata Metadata Functions 151 153 /// @ingroup Astronomy 152 # include "psMetadata.h"154 # include "psMetadata.h" 153 155 154 156 /// @} 155 157 156 158 #endif 157 -
trunk/psLib/src/sys/psAbort.c
r1406 r1407 1 1 2 /** @file psAbort.c 2 3 * … … 9 10 * @author Eric Van Alst, MHPCC 10 11 * 11 * @version $Revision: 1. 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.8 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 16 17 17 18 /******************************************************************************/ 19 18 20 /* INCLUDE FILES */ 21 19 22 /******************************************************************************/ 20 23 #include <stdarg.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 void psAbort(const char *name, const char *fmt, ...)74 void psAbort(const char *name, const char *fmt, ...) 60 75 { 61 va_list argPtr;// variable list arguement pointer76 va_list argPtr; // variable list arguement pointer 62 77 63 78 // Get the variable list parameters to pass to logging function … … 73 88 abort(); 74 89 } 75 -
trunk/psLib/src/sys/psAbort.h
r974 r1407 1 1 2 /** @file psAbort.h 2 3 * … … 11 12 * @author Eric Van Alst, MHPCC 12 13 * 13 * @version $Revision: 1. 4$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-0 6-10 01:58:06 $14 * @version $Revision: 1.5 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_ABORT_H 20 #define PS_ABORT_H 21 21 # define PS_ABORT_H 22 22 23 23 // Doxygen grouping tags 24 24 25 /** @addtogroup ErrorHandling 25 26 * @{ … … 36 37 * 37 38 */ 38 void psAbort( 39 const char* name, ///< Source of abort such as file or function detected 40 const char* fmt, ///< A printf style formatting statement defining msg 41 ... 42 ); 39 void psAbort(const char *name, // /< Source of abort such as file or function detected 40 const char *fmt, // /< A printf style formatting statement defining msg 41 ... 42 ); 43 43 44 /* @} */ // Doxygen - End of SystemGroup Functions44 /* @} */// Doxygen - End of SystemGroup Functions 45 45 46 46 #endif 47 -
trunk/psLib/src/sys/psError.c
r1406 r1407 1 1 2 /** @file psError.c 2 3 * … … 10 11 * @author Eric Van Alst, MHPCC 11 12 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 /******************************************************************************/ 20 19 21 /* INCLUDE FILES */ 22 20 23 /******************************************************************************/ 21 24 #include <stdarg.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATIONS - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATIONS - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 void psError(const char *name, const char *fmt, ...)74 void psError(const char *name, const char *fmt, ...) 60 75 { 61 va_list argPtr;// variable list arguement pointer76 va_list argPtr; // variable list arguement pointer 62 77 63 // Get the variable list parameters to pass to logging function78 // Get the variable list parameters to pass to logging function 64 79 va_start(argPtr, fmt); 65 80 … … 70 85 va_end(argPtr); 71 86 } 72 -
trunk/psLib/src/sys/psError.h
r974 r1407 1 1 2 /** @file psError.h 2 3 * … … 12 13 * @author Eric Van Alst, MHPCC 13 14 * 14 * @version $Revision: 1. 4$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-0 6-10 01:58:06 $15 * @version $Revision: 1.5 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PS_ERROR_H 21 # define PS_ERROR_H22 # define PS_ERROR_H 22 23 23 24 /** @addtogroup ErrorHandling … … 34 35 * 35 36 */ 36 void psError( 37 const char *name, ///< Source of error such as file or function detected 38 const char *fmt, ///< A printf style formatting statement defining msg 39 ... 40 ); 37 void psError(const char *name, // /< Source of error such as file or function detected 38 const char *fmt, // /< A printf style formatting statement defining msg 39 ... 40 ); 41 41 42 /* @} */ // End of SysUtils Functions42 /* @} */// End of SysUtils Functions 43 43 44 44 #endif 45 -
trunk/psLib/src/sys/psLogMsg.c
r1406 r1407 1 1 2 /** @file psLogMsg.c 2 3 * @brief Procedures for logging messages. … … 11 12 * @author George Gusciora, MHPCC 12 13 * 13 * @version $Revision: 1.2 3$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.24 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 44 45 45 46 #define MAX_LOG_LINE_LENGTH 128 46 static FILE * logDest = (FILE*)1;// flag to initialize to stderr before using.47 static int globalLogLevel = PS_LOG_INFO; // log all messages at this or above48 static bool logTime = true; // Flag to include time info49 static bool logHost = true; // Flag to include host info50 static bool logLevel = true; // Flag to include level info51 static bool logName = true; // Flag to include name info52 static bool logMsg = true; // Flag to include message info47 static FILE *logDest = (FILE *) 1; // flag to initialize to stderr before using. 48 static int globalLogLevel = PS_LOG_INFO; // log all messages at this or above 49 static bool logTime = true; // Flag to include time info 50 static bool logHost = true; // Flag to include host info 51 static bool logLevel = true; // Flag to include level info 52 static bool logName = true; // Flag to include name info 53 static bool logMsg = true; // Flag to include message info 53 54 54 55 /***************************************************************************** … … 67 68 68 69 if ((level < MIN_LOG_LEVEL) || (level > MAX_LOG_LEVEL)) { 69 psLogMsg("logmsg", PS_LOG_WARN, 70 "Attempt to set invalid logMsg level: %d", level); 70 psLogMsg("logmsg", PS_LOG_WARN, "Attempt to set invalid logMsg level: %d", level); 71 71 level = (level < MIN_LOG_LEVEL) ? MIN_LOG_LEVEL : MAX_LOG_LEVEL; 72 72 } 73 74 73 // Set new global log level 75 74 globalLogLevel = level; … … 78 77 return oldLevel; 79 78 } 80 81 79 82 80 /***************************************************************************** … … 91 89 An integer specifying the old log destination. 92 90 *****************************************************************************/ 93 int psLogSetDestination(const char *dest)91 int psLogSetDestination(const char *dest) 94 92 { 95 93 char protocol[5]; … … 97 95 98 96 // if logDest has not been initialized, do so before using it 99 if (logDest ==(FILE*)1) {97 if (logDest == (FILE *) 1) { 100 98 logDest = stderr; 101 99 } 102 100 103 if (dest == NULL || strcmp(dest, "none")==0) {101 if (dest == NULL || strcmp(dest, "none") == 0) { 104 102 if (logDest != NULL && logDest != stderr && logDest != stdout) { 105 103 fclose(logDest); … … 109 107 } 110 108 111 if (sscanf(dest, "%4s:%256s",protocol,location) < 2) {112 psError(__func__, "The specified destination, %s, is malformed.", dest);109 if (sscanf(dest, "%4s:%256s", protocol, location) < 2) { 110 psError(__func__, "The specified destination, %s, is malformed.", dest); 113 111 return 1; 114 112 } 115 113 116 if (strcmp(protocol, "dest") == 0) {117 if (strcmp(location, "stderr") == 0) {114 if (strcmp(protocol, "dest") == 0) { 115 if (strcmp(location, "stderr") == 0) { 118 116 if (logDest != NULL && logDest != stderr && logDest != stdout) { 119 117 fclose(logDest); … … 122 120 return 0; 123 121 } 124 if (strcmp(location, "stdout") == 0) {122 if (strcmp(location, "stdout") == 0) { 125 123 if (logDest != NULL && logDest != stderr && logDest != stdout) { 126 124 fclose(logDest); … … 129 127 return 0; 130 128 } 131 psError(__func__, "The location, %s, for protocol 'dest' is invalid.",location);129 psError(__func__, "The location, %s, for protocol 'dest' is invalid.", location); 132 130 return 1; 133 } else 134 if (strcmp(protocol,"file") == 0) {135 FILE* file = fopen(location,"w"); 136 if (file == NULL) {137 psError(__func__,"Could not open file '%s' for output.",location);138 return 1;139 }140 if (logDest != NULL && logDest != stderr && logDest != stdout) {141 fclose(logDest);142 }143 logDest = file;144 return 0;145 }146 147 psError(__func__, "Do not know how to handle the protocol '%s'.",protocol);131 } else if (strcmp(protocol, "file") == 0) { 132 FILE *file = fopen(location, "w"); 133 134 if (file == NULL) { 135 psError(__func__, "Could not open file '%s' for output.", location); 136 return 1; 137 } 138 if (logDest != NULL && logDest != stderr && logDest != stdout) { 139 fclose(logDest); 140 } 141 logDest = file; 142 return 0; 143 } 144 145 psError(__func__, "Do not know how to handle the protocol '%s'.", protocol); 148 146 return 1; 149 147 } … … 181 179 fmt = "THLNM"; 182 180 } 183 184 181 // Step through each character in the format string. For each letter 185 182 // in that string, set/unset the appropriate logging. … … 214 211 215 212 if (!logMsg) { 216 psTrace("utils.logMsg", 1, 217 "You must at least log error messages (You chose \"%s\")", 218 fmt); 219 } 220 } 221 222 223 224 #if !defined(HOST_NAME_MAX) // should be in limits.h 225 # define HOST_NAME_MAX 256 213 psTrace("utils.logMsg", 1, "You must at least log error messages (You chose \"%s\")", fmt); 214 } 215 } 216 217 #if !defined(HOST_NAME_MAX) // should be in limits.h 218 # define HOST_NAME_MAX 256 226 219 #endif 220 227 221 /***************************************************************************** 228 222 psVLogMsg(): This routine sends the message, which is a printf style … … 239 233 NULL. 240 234 *****************************************************************************/ 241 void psLogMsgV(const char *name, 242 int level, 243 const char *fmt, 244 va_list ap) 245 { 246 static int first = 1; // Flag for calling gethostname() 235 void psLogMsgV(const char *name, int level, const char *fmt, va_list ap) 236 { 237 static int first = 1; // Flag for calling gethostname() 247 238 static char hostname[HOST_NAME_MAX + 1]; 239 248 240 // Buffer for hostname. 249 char clevel =0;// letter-name for level250 char head[MAX_LOG_LINE_LENGTH +2];// the added two are for the ending | and \0251 char *head_ptr = head; // where we've got to in head241 char clevel = 0; // letter-name for level 242 char head[MAX_LOG_LINE_LENGTH + 2]; // the added two are for the ending | and \0 243 char *head_ptr = head; // where we've got to in head 252 244 int maxLength = MAX_LOG_LINE_LENGTH; 253 time_t clock = time(NULL); // The current time.245 time_t clock = time(NULL); // The current time. 254 246 struct tm *utc = gmtime(&clock); // The current gm time. 255 247 256 248 // if logDest has not been initialized, do so before using it 257 if (logDest ==(FILE*)1) {249 if (logDest == (FILE *) 1) { 258 250 logDest = stderr; 259 251 } 260 261 252 // If logging is off, or if the level is too high, return immediately. 262 253 if ((level > globalLogLevel) || (logDest == NULL)) { 263 254 return; 264 255 } 265 266 256 // If I have not been here yet, determine my hostname and save it. 267 257 if (first) { … … 297 287 298 288 default: 299 psTrace("utils.logMsg", 2, "Invalid logMsg level: %d (%s)\n", 300 level, fmt); 289 psTrace("utils.logMsg", 2, "Invalid logMsg level: %d (%s)\n", level, fmt); 301 290 level = (level < 0) ? 0 : 9; 302 291 break; … … 307 296 maxLength -= snprintf(head_ptr, maxLength, "%4d:%02d:%02d %02d:%02d:%02dZ", 308 297 utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday, 309 utc->tm_hour, utc->tm_min, utc->tm_sec) -1;298 utc->tm_hour, utc->tm_min, utc->tm_sec) - 1; 310 299 head_ptr += strlen(head_ptr); 311 300 } … … 336 325 if (head_ptr > head) { 337 326 *head_ptr++ = '|'; 338 } else 339 if (!logMsg) { // no output desired 340 return; 341 } 327 } else if (!logMsg) { // no output desired 328 return; 329 } 342 330 *head_ptr = '\0'; 343 331 … … 352 340 } 353 341 } 354 355 342 356 343 /***************************************************************************** … … 369 356 NULL 370 357 *****************************************************************************/ 371 void psLogMsg(const char *name, 372 int level, 373 const char *fmt, 374 ...) 358 void psLogMsg(const char *name, int level, const char *fmt, ...) 375 359 { 376 360 va_list ap; -
trunk/psLib/src/sys/psLogMsg.h
r1406 r1407 1 1 2 /** @file psLogMsg.h 2 3 * @brief Procedures for logging messages. … … 11 12 * @author George Gusciora, MHPCC 12 13 * 13 * @version $Revision: 1.1 2$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.13 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 17 18 */ 18 19 #if !defined(PS_LOG_MSG_H) 19 # define PS_LOG_MSG_H20 # include <stdarg.h>20 # define PS_LOG_MSG_H 21 # include <stdarg.h> 21 22 22 23 /** @addtogroup LogTrace … … 29 30 /// In future versions, this procedure will take a character string as an 30 31 /// argument which can specify more general log destinations. 31 int psLogSetDestination(const char * dest ///< Specifies where to send messages.32 int psLogSetDestination(const char *dest // /< Specifies where to send messages. 32 33 ); 33 34 34 35 35 /// This procedure sets the message level for future log messages. Subsequent … … 38 38 /// Ie. higher values set by this procedure will cause more log messages to 39 39 /// be displayed. 40 int psLogSetLevel(int level ///< Specifies the system log level40 int psLogSetLevel(int level // /< Specifies the system log level 41 41 ); 42 43 42 44 43 /// This procedure sets the log format for future log messages. The argument … … 47 46 /// Deleting a letter from the string will cause the associated information 48 47 /// to not be logged. 49 void psLogSetFormat(const char *fmt ///< Specifies the system log format48 void psLogSetFormat(const char *fmt // /< Specifies the system log format 50 49 ); 51 52 50 53 51 /// This procedure logs a message to the destination set by a prior … … 55 53 /// specified by a prior call to psLogSetLevel(). The message is specified 56 54 /// with a printf-stype string an arguments. 57 void psLogMsg(const char *name, ///< name of the log source58 int myLevel, ///< severity level of this log message59 const char *fmt, ... ///< printf-style format command55 void psLogMsg(const char *name, // /< name of the log source 56 int myLevel, // /< severity level of this log message 57 const char *fmt, ... // /< printf-style format command 60 58 ); 61 62 59 63 60 /// This procedure is functionally equivalent to psLogMsg(), except that 64 61 /// it takes a va_list as the message parameter, not a printf-style string. 65 void psLogMsgV(const char *name, ///< name of the log source66 int myLevel, ///< severity level of this log message67 const char *fmt, ///< printf-style format command68 va_list ap ///< varargs argument list62 void psLogMsgV(const char *name, // /< name of the log source 63 int myLevel, // /< severity level of this log message 64 const char *fmt, // /< printf-style format command 65 va_list ap // /< varargs argument list 69 66 ); 70 67 … … 74 71 PS_LOG_ERROR, 75 72 PS_LOG_WARN, 76 PS_LOG_INFO }; 73 PS_LOG_INFO 74 }; 77 75 78 76 ///< Destinations for log messages … … 80 78 PS_LOG_NONE, 81 79 PS_LOG_TO_STDERR, 82 PS_LOG_TO_STDOUT }; 80 PS_LOG_TO_STDOUT 81 }; 83 82 84 83 /// @} -
trunk/psLib/src/sys/psMemory.c
r1406 r1407 1 1 2 /** @file psMemory.c 2 3 * … … 8 9 * @author Robert Lupton, Princeton University 9 10 * 10 * @version $Revision: 1.3 2$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.33 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 14 15 */ 15 16 16 #define PS_ALLOW_MALLOC // we're allowed to call malloc()17 #define PS_ALLOW_MALLOC // we're allowed to call malloc() 17 18 18 19 #include <stdlib.h> … … 26 27 #include "psLogMsg.h" 27 28 28 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header29 30 #define P_PS_LARGE_BLOCK_SIZE 65536 // size where under, we try to recycle31 32 static int checkMemBlock( const psMemBlock *m, const char* funcName);29 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header 30 31 #define P_PS_LARGE_BLOCK_SIZE 65536 // size where under, we try to recycle 32 33 static int checkMemBlock(const psMemBlock * m, const char *funcName); 33 34 static psMemBlock *lastMemBlockAllocated = NULL; 34 35 static pthread_mutex_t memBlockListMutex = PTHREAD_MUTEX_INITIALIZER; … … 38 39 39 40 static int recycleBins = 13; 40 static int recycleBinSize[ 14 ] =41 {42 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE43 }; 41 static int recycleBinSize[14] = { 42 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE 43 }; 44 44 45 // N.B. recycleBinSize should be terminated by P_PS_LARGE_BLOCK_SIZE (simplifies search loops) 45 static psMemBlock* recycleMemBlockList[ 13 ] = 46 { 47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 48 }; 46 static psMemBlock *recycleMemBlockList[13] = { 47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 48 }; 49 49 50 50 #ifdef PS_MEM_DEBUG 51 static psMemBlock * deadBlockList;// a place to put dead memBlocks in debug mode.51 static psMemBlock *deadBlockList; // a place to put dead memBlocks in debug mode. 52 52 #endif 53 53 54 /** 54 55 * Unique ID for allocated blocks … … 59 60 * Default memExhausted callback. 60 61 */ 61 static void *memExhaustedCallbackDefault( size_t size)62 { 63 void * ptr = NULL;64 65 pthread_mutex_lock( &recycleMemBlockListMutex);62 static void *memExhaustedCallbackDefault(size_t size) 63 { 64 void *ptr = NULL; 65 66 pthread_mutex_lock(&recycleMemBlockListMutex); 66 67 int level = recycleBins - 1; 67 while ( level >= 0 && ptr == NULL ) { 68 while ( recycleMemBlockList[ level ] != NULL && ptr == NULL ) { 69 psMemBlock * old = recycleMemBlockList[ level ]; 70 recycleMemBlockList[ level ] = recycleMemBlockList[ level ] ->nextBlock; 71 free( old ); 72 ptr = malloc( size ); 68 69 while (level >= 0 && ptr == NULL) { 70 while (recycleMemBlockList[level] != NULL && ptr == NULL) { 71 psMemBlock *old = recycleMemBlockList[level]; 72 73 recycleMemBlockList[level] = recycleMemBlockList[level]->nextBlock; 74 free(old); 75 ptr = malloc(size); 73 76 } 74 77 level--; 75 78 } 76 pthread_mutex_unlock( &recycleMemBlockListMutex);79 pthread_mutex_unlock(&recycleMemBlockListMutex); 77 80 78 81 return ptr; … … 81 84 static psMemExhaustedCallback memExhaustedCallback = memExhaustedCallbackDefault; 82 85 83 psMemExhaustedCallback psMemExhaustedCallbackSet( psMemExhaustedCallback func)86 psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func) 84 87 { 85 88 psMemExhaustedCallback old = memExhaustedCallback; 86 89 87 if ( func != NULL) {90 if (func != NULL) { 88 91 memExhaustedCallback = func; 89 92 } else { … … 94 97 } 95 98 96 static void memProblemCallbackDefault( const psMemBlock *ptr, 97 const char *file, int lineno ) 98 { 99 if ( ptr->refCounter < 1 ) { 100 psError( __func__, 101 "Block %ld allocated at %s:%d freed more than once at %s:%d\n", 102 ptr->id, ptr->file, ptr->lineno, file, lineno ); 103 } 104 105 if ( lineno > 0 ) { 106 psAbort( __func__, "Detected a problem in the memory system at %s:%d", file, lineno ); 99 static void memProblemCallbackDefault(const psMemBlock * ptr, const char *file, int lineno) 100 { 101 if (ptr->refCounter < 1) { 102 psError(__func__, 103 "Block %ld allocated at %s:%d freed more than once at %s:%d\n", 104 ptr->id, ptr->file, ptr->lineno, file, lineno); 105 } 106 107 if (lineno > 0) { 108 psAbort(__func__, "Detected a problem in the memory system at %s:%d", file, lineno); 107 109 } 108 110 } 109 111 static psMemProblemCallback memProblemCallback = memProblemCallbackDefault; 110 112 111 psMemProblemCallback psMemProblemCallbackSet( psMemProblemCallback func)113 psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func) 112 114 { 113 115 psMemProblemCallback old = memProblemCallback; 114 116 115 if ( func != NULL) {117 if (func != NULL) { 116 118 memProblemCallback = func; 117 119 } else { … … 121 123 return old; 122 124 } 125 123 126 /* 124 127 * And now the I-want-to-be-informed callbacks … … 126 129 * Call the callbacks when these IDs are allocated/freed 127 130 */ 128 psMemoryId p_psMemAllocateID = 0; // notify user this block is allocated131 psMemoryId p_psMemAllocateID = 0; // notify user this block is allocated 129 132 psMemoryId p_psMemFreeID = 0; // notify user this block is freed 130 133 131 psMemoryId psMemAllocateCallbackSetID( psMemoryId id)134 psMemoryId psMemAllocateCallbackSetID(psMemoryId id) 132 135 { 133 136 psMemoryId old = p_psMemAllocateID; 137 134 138 p_psMemAllocateID = id; 135 139 … … 137 141 } 138 142 139 psMemoryId psMemFreeCallbackSetID( psMemoryId id)143 psMemoryId psMemFreeCallbackSetID(psMemoryId id) 140 144 { 141 145 psMemoryId old = p_psMemFreeID; 146 142 147 p_psMemFreeID = id; 143 148 … … 151 156 * isn't resignalled) 152 157 */ 153 static psMemoryId memAllocateCallbackDefault( const psMemBlock *ptr)154 { 155 static psMemoryId incr = 0; // "p_psMemAllocateID += incr"158 static psMemoryId memAllocateCallbackDefault(const psMemBlock * ptr) 159 { 160 static psMemoryId incr = 0; // "p_psMemAllocateID += incr" 156 161 157 162 return incr; 158 163 } 159 164 160 static psMemoryId memFreeCallbackDefault( const psMemBlock *ptr)161 { 162 static psMemoryId incr = 0; // "p_psMemFreeID += incr"165 static psMemoryId memFreeCallbackDefault(const psMemBlock * ptr) 166 { 167 static psMemoryId incr = 0; // "p_psMemFreeID += incr" 163 168 164 169 return incr; … … 171 176 static psMemFreeCallback memFreeCallback = memFreeCallbackDefault; 172 177 173 psMemAllocateCallback psMemAllocateCallbackSet( psMemAllocateCallback func)178 psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func) 174 179 { 175 180 psMemFreeCallback old = memAllocateCallback; 176 181 177 if ( func != NULL) {182 if (func != NULL) { 178 183 memAllocateCallback = func; 179 184 } else { … … 184 189 } 185 190 186 psMemFreeCallback psMemFreeCallbackSet( psMemFreeCallback func)191 psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func) 187 192 { 188 193 psMemFreeCallback old = memFreeCallback; 189 194 190 if ( func != NULL) {195 if (func != NULL) { 191 196 memFreeCallback = func; 192 197 } else { … … 200 205 * Return memory ID counter for next block to be allocated 201 206 */ 202 psMemoryId psMemGetId( void)207 psMemoryId psMemGetId(void) 203 208 { 204 209 psMemoryId id; 205 pthread_mutex_lock( &memIdMutex ); 210 211 pthread_mutex_lock(&memIdMutex); 206 212 id = memid + 1; 207 pthread_mutex_unlock( &memIdMutex);213 pthread_mutex_unlock(&memIdMutex); 208 214 209 215 return id; … … 216 222 */ 217 223 218 static int checkMemBlock( const psMemBlock *m, const char* funcName)224 static int checkMemBlock(const psMemBlock * m, const char *funcName) 219 225 { 220 226 // n.b. since this is called by psMemCheckCorruption while the memblock list is mutex locked, 221 227 // we shouldn't call such things as p_psAlloc/p_psFree here. 222 228 223 if ( m == NULL) {224 psError( funcName, "Memory Corruption: NULL memory block found.");229 if (m == NULL) { 230 psError(funcName, "Memory Corruption: NULL memory block found."); 225 231 return 1; 226 232 } 227 233 228 if ( m->refCounter == 0) {234 if (m->refCounter == 0) { 229 235 // using an unreferenced block of memory, are you? 230 psError( __func__, "Memory Corruption: memory block %ld was freed but still used.", 231 m->id ); 236 psError(__func__, "Memory Corruption: memory block %ld was freed but still used.", m->id); 232 237 return 1; 233 238 } 234 239 235 if ( m->startblock != P_PS_MEMMAGIC || m->endblock != P_PS_MEMMAGIC ) { 236 psError( funcName, "Memory Corruption: memory block %ld is corrupted (buffer underflow)", 237 m->id ); 240 if (m->startblock != P_PS_MEMMAGIC || m->endblock != P_PS_MEMMAGIC) { 241 psError(funcName, "Memory Corruption: memory block %ld is corrupted (buffer underflow)", m->id); 238 242 return 1; 239 243 } 240 if ( *( void** ) ( ( int8_t* ) ( m + 1 ) + m->userMemorySize ) != P_PS_MEMMAGIC ) { 241 psError( funcName, "Memory Corruption: memory block %ld is corrupted (buffer overflow)", 242 m->id ); 244 if (*(void **)((int8_t *) (m + 1) + m->userMemorySize) != P_PS_MEMMAGIC) { 245 psError(funcName, "Memory Corruption: memory block %ld is corrupted (buffer overflow)", m->id); 243 246 return 1; 244 247 } … … 247 250 } 248 251 249 int psMemCheckCorruption( bool abort_on_error)250 { 251 int nbad = 0; // number of bad blocks252 int psMemCheckCorruption(bool abort_on_error) 253 { 254 int nbad = 0; // number of bad blocks 252 255 253 256 // get exclusive access to the memBlock list to avoid it changing on us while we use it. 254 pthread_mutex_lock( &memBlockListMutex);255 256 for ( psMemBlock * iter = lastMemBlockAllocated; iter != NULL; iter = iter->nextBlock) {257 if ( checkMemBlock( iter, __func__ )) {257 pthread_mutex_lock(&memBlockListMutex); 258 259 for (psMemBlock * iter = lastMemBlockAllocated; iter != NULL; iter = iter->nextBlock) { 260 if (checkMemBlock(iter, __func__)) { 258 261 nbad++; 259 262 260 memProblemCallback( iter, __func__, __LINE__);261 262 if ( abort_on_error) {263 memProblemCallback(iter, __func__, __LINE__); 264 265 if (abort_on_error) { 263 266 // release the lock on the memblock list 264 pthread_mutex_unlock( &memBlockListMutex);265 psAbort( __func__, "Detected memory corruption");267 pthread_mutex_unlock(&memBlockListMutex); 268 psAbort(__func__, "Detected memory corruption"); 266 269 return nbad; 267 270 } … … 270 273 271 274 // release the lock on the memblock list 272 pthread_mutex_unlock( &memBlockListMutex);275 pthread_mutex_unlock(&memBlockListMutex); 273 276 return nbad; 274 277 } 275 278 276 void *p_psAlloc( size_t size, const char *file, int lineno)277 { 278 279 psMemBlock * ptr = NULL;279 void *p_psAlloc(size_t size, const char *file, int lineno) 280 { 281 282 psMemBlock *ptr = NULL; 280 283 281 284 // memory is of the size I want to bother recycling? 282 if ( size < P_PS_LARGE_BLOCK_SIZE) {285 if (size < P_PS_LARGE_BLOCK_SIZE) { 283 286 // find the bin we need. 284 287 int level = 0; 285 while ( size > recycleBinSize[ level ] ) { 288 289 while (size > recycleBinSize[level]) { 286 290 level++; 287 291 } 288 292 // Are we in one of the bins 289 if ( level < recycleBins) {290 291 size = recycleBinSize[ level]; // round-up size to next sized bin.292 293 pthread_mutex_lock( &recycleMemBlockListMutex);294 295 if ( recycleMemBlockList[ level ] != NULL) {296 ptr = recycleMemBlockList[ level];297 recycleMemBlockList[ level] = ptr->nextBlock;298 if ( recycleMemBlockList[ level ] != NULL) {299 recycleMemBlockList[ level ]->previousBlock = NULL;293 if (level < recycleBins) { 294 295 size = recycleBinSize[level]; // round-up size to next sized bin. 296 297 pthread_mutex_lock(&recycleMemBlockListMutex); 298 299 if (recycleMemBlockList[level] != NULL) { 300 ptr = recycleMemBlockList[level]; 301 recycleMemBlockList[level] = ptr->nextBlock; 302 if (recycleMemBlockList[level] != NULL) { 303 recycleMemBlockList[level]->previousBlock = NULL; 300 304 } 301 305 size = ptr->userMemorySize; 302 306 } 303 307 304 pthread_mutex_unlock( &recycleMemBlockListMutex ); 305 } 306 } 307 308 if ( ptr == NULL ) { 309 ptr = malloc( sizeof( psMemBlock ) + size + sizeof( void* ) ); 310 311 if ( ptr == NULL ) { 312 ptr = memExhaustedCallback( size ); 313 if ( ptr == NULL ) { 314 psAbort( __func__, "Failed to allocate %u bytes at %s:%d", 315 size, file, lineno ); 308 pthread_mutex_unlock(&recycleMemBlockListMutex); 309 } 310 } 311 312 if (ptr == NULL) { 313 ptr = malloc(sizeof(psMemBlock) + size + sizeof(void *)); 314 315 if (ptr == NULL) { 316 ptr = memExhaustedCallback(size); 317 if (ptr == NULL) { 318 psAbort(__func__, "Failed to allocate %u bytes at %s:%d", size, file, lineno); 316 319 } 317 320 } … … 320 323 ptr->endblock = P_PS_MEMMAGIC; 321 324 ptr->userMemorySize = size; 322 pthread_mutex_init( &ptr->refCounterMutex, NULL ); 323 } 324 325 pthread_mutex_init(&ptr->refCounterMutex, NULL); 326 } 325 327 // increment the memory id safely. 326 pthread_mutex_lock( &memBlockListMutex);327 *( psMemoryId*) & ptr->id = ++memid;328 pthread_mutex_unlock( &memBlockListMutex);328 pthread_mutex_lock(&memBlockListMutex); 329 *(psMemoryId *) & ptr->id = ++memid; 330 pthread_mutex_unlock(&memBlockListMutex); 329 331 330 332 ptr->file = file; 331 333 ptr->freeFcn = NULL; 332 *( unsigned int* ) &ptr->lineno = lineno;333 *( void** ) ( ( int8_t* ) ( ptr + 1 ) + size) = P_PS_MEMMAGIC;334 *(unsigned int *)&ptr->lineno = lineno; 335 *(void **)((int8_t *) (ptr + 1) + size) = P_PS_MEMMAGIC; 334 336 ptr->previousBlock = NULL; 335 337 336 ptr->refCounter = 1; // one user so far338 ptr->refCounter = 1; // one user so far 337 339 338 340 // need exclusive access of the memory block list now... 339 pthread_mutex_lock( &memBlockListMutex);341 pthread_mutex_lock(&memBlockListMutex); 340 342 341 343 // insert the new block to the front of the memBlock linked-list 342 344 ptr->nextBlock = lastMemBlockAllocated; 343 if ( ptr->nextBlock != NULL) {345 if (ptr->nextBlock != NULL) { 344 346 ptr->nextBlock->previousBlock = ptr; 345 347 } 346 348 lastMemBlockAllocated = ptr; 347 349 348 pthread_mutex_unlock( &memBlockListMutex ); 349 350 // Did the user ask to be informed about this allocation? 351 if ( ptr->id == p_psMemAllocateID ) { 352 p_psMemAllocateID += memAllocateCallback( ptr ); 353 } 354 350 pthread_mutex_unlock(&memBlockListMutex); 351 352 // Did the user ask to be informed about this allocation? 353 if (ptr->id == p_psMemAllocateID) { 354 p_psMemAllocateID += memAllocateCallback(ptr); 355 } 355 356 // And return the user the memory that they allocated 356 return ptr + 1; // user memory357 } 358 359 void *p_psRealloc( void *vptr, size_t size, const char *file, int lineno)360 { 361 if ( vptr == NULL) {362 return p_psAlloc( size, file, lineno);357 return ptr + 1; // user memory 358 } 359 360 void *p_psRealloc(void *vptr, size_t size, const char *file, int lineno) 361 { 362 if (vptr == NULL) { 363 return p_psAlloc(size, file, lineno); 363 364 } else { 364 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;365 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 365 366 bool isBlockLast = false; 366 367 367 if ( checkMemBlock( ptr, __func__ ) != 0 ) { 368 memProblemCallback( ptr, file, lineno ); 369 psAbort( file, "Realloc detected a memory corruption (id %ld @ %s:%d).", 370 ptr->id, ptr->file, ptr->lineno ); 371 } 372 373 pthread_mutex_lock( &memBlockListMutex ); 374 375 isBlockLast = ( ptr == lastMemBlockAllocated ); 376 377 ptr = ( psMemBlock* ) realloc( ptr, sizeof( psMemBlock ) + size + sizeof( void* ) ); 378 379 if ( ptr == NULL ) { 380 psAbort( __func__, "Failed to reallocate %ld bytes at %s:%d", 381 size, file, lineno ); 368 if (checkMemBlock(ptr, __func__) != 0) { 369 memProblemCallback(ptr, file, lineno); 370 psAbort(file, "Realloc detected a memory corruption (id %ld @ %s:%d).", 371 ptr->id, ptr->file, ptr->lineno); 372 } 373 374 pthread_mutex_lock(&memBlockListMutex); 375 376 isBlockLast = (ptr == lastMemBlockAllocated); 377 378 ptr = (psMemBlock *) realloc(ptr, sizeof(psMemBlock) + size + sizeof(void *)); 379 380 if (ptr == NULL) { 381 psAbort(__func__, "Failed to reallocate %ld bytes at %s:%d", size, file, lineno); 382 382 } 383 383 384 384 ptr->userMemorySize = size; 385 *( void** ) ( ( int8_t* ) ( ptr + 1 ) + size) = P_PS_MEMMAGIC;386 387 if ( isBlockLast) {385 *(void **)((int8_t *) (ptr + 1) + size) = P_PS_MEMMAGIC; 386 387 if (isBlockLast) { 388 388 lastMemBlockAllocated = ptr; 389 389 } 390 391 390 // the block location may have changed, so fix the linked list addresses. 392 if ( ptr->nextBlock != NULL) {391 if (ptr->nextBlock != NULL) { 393 392 ptr->nextBlock->previousBlock = ptr; 394 393 } 395 if ( ptr->previousBlock != NULL) {394 if (ptr->previousBlock != NULL) { 396 395 ptr->previousBlock->nextBlock = ptr; 397 396 } 398 397 399 pthread_mutex_unlock( &memBlockListMutex);400 401 // Did the user ask to be informed about this allocation?402 if ( ptr->id == p_psMemAllocateID) {403 p_psMemAllocateID += memAllocateCallback( ptr);404 } 405 406 return ptr + 1; // usr memory407 } 408 } 409 410 void p_psFree( void *vptr, const char *file, int lineno)411 { 412 ( void ) p_psMemDecrRefCounter( vptr, file, lineno );// this handles the free, if required.398 pthread_mutex_unlock(&memBlockListMutex); 399 400 // Did the user ask to be informed about this allocation? 401 if (ptr->id == p_psMemAllocateID) { 402 p_psMemAllocateID += memAllocateCallback(ptr); 403 } 404 405 return ptr + 1; // usr memory 406 } 407 } 408 409 void p_psFree(void *vptr, const char *file, int lineno) 410 { 411 (void)p_psMemDecrRefCounter(vptr, file, lineno); // this handles the free, if required. 413 412 } 414 413 … … 416 415 * Check for memory leaks. 417 416 */ 418 int psMemCheckLeaks( psMemoryId id0, psMemBlock ***arr, FILE *fd)417 int psMemCheckLeaks(psMemoryId id0, psMemBlock *** arr, FILE * fd) 419 418 { 420 419 int nleak = 0; 421 420 int j = 0; 422 psMemBlock *topBlock = lastMemBlockAllocated;423 424 pthread_mutex_lock( &memBlockListMutex);425 426 for ( psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) {427 if ( ( psMemGetRefCounter( iter + 1 ) > 0 ) && ( iter->id >= id0 )) {421 psMemBlock *topBlock = lastMemBlockAllocated; 422 423 pthread_mutex_lock(&memBlockListMutex); 424 425 for (psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) { 426 if ((psMemGetRefCounter(iter + 1) > 0) && (iter->id >= id0)) { 428 427 nleak++; 429 428 430 if ( fd != NULL) {431 if ( nleak == 1) {432 fprintf( fd, " %20s:line ID\n", "file");429 if (fd != NULL) { 430 if (nleak == 1) { 431 fprintf(fd, " %20s:line ID\n", "file"); 433 432 } 434 433 435 fprintf( fd, " %20s:%-4d %ld\n", iter->file, iter->lineno, iter->id);436 } 437 } 438 } 439 440 pthread_mutex_unlock( &memBlockListMutex);441 442 if ( nleak == 0 || arr == NULL) {434 fprintf(fd, " %20s:%-4d %ld\n", iter->file, iter->lineno, iter->id); 435 } 436 } 437 } 438 439 pthread_mutex_unlock(&memBlockListMutex); 440 441 if (nleak == 0 || arr == NULL) { 443 442 return nleak; 444 443 } 445 444 446 *arr = p_psAlloc( nleak * sizeof( psMemBlock ), __FILE__, __LINE__);447 pthread_mutex_lock( &memBlockListMutex);448 449 for ( psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) {450 if ( ( psMemGetRefCounter( iter + 1 ) > 0 ) && ( iter->id >= id0 )) {451 ( *arr ) [ j++] = iter;452 if ( j == nleak ) {// found them all445 *arr = p_psAlloc(nleak * sizeof(psMemBlock), __FILE__, __LINE__); 446 pthread_mutex_lock(&memBlockListMutex); 447 448 for (psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) { 449 if ((psMemGetRefCounter(iter + 1) > 0) && (iter->id >= id0)) { 450 (*arr)[j++] = iter; 451 if (j == nleak) { // found them all 453 452 break; 454 453 } … … 456 455 } 457 456 458 pthread_mutex_unlock( &memBlockListMutex);457 pthread_mutex_unlock(&memBlockListMutex); 459 458 460 459 return nleak; … … 465 464 */ 466 465 // return refCounter 467 psReferenceCount psMemGetRefCounter( void *vptr)468 { 469 psMemBlock * ptr;466 psReferenceCount psMemGetRefCounter(void *vptr) 467 { 468 psMemBlock *ptr; 470 469 unsigned int refCount; 471 470 472 if ( vptr == NULL) {471 if (vptr == NULL) { 473 472 return 0; 474 473 } 475 474 476 ptr = ( ( psMemBlock * ) vptr) - 1;477 478 if ( checkMemBlock( ptr, __func__ ) != 0) {479 memProblemCallback( ptr, __func__, __LINE__);480 } 481 482 pthread_mutex_lock( &ptr->refCounterMutex);475 ptr = ((psMemBlock *) vptr) - 1; 476 477 if (checkMemBlock(ptr, __func__) != 0) { 478 memProblemCallback(ptr, __func__, __LINE__); 479 } 480 481 pthread_mutex_lock(&ptr->refCounterMutex); 483 482 refCount = ptr->refCounter; 484 pthread_mutex_unlock( &ptr->refCounterMutex);483 pthread_mutex_unlock(&ptr->refCounterMutex); 485 484 486 485 return refCount; 487 486 } 487 488 488 // increment and return refCounter 489 void * p_psMemIncrRefCounter( void *vptr, const char *file, int lineno)490 { 491 psMemBlock * ptr;492 493 if ( vptr == NULL) {489 void *p_psMemIncrRefCounter(void *vptr, const char *file, int lineno) 490 { 491 psMemBlock *ptr; 492 493 if (vptr == NULL) { 494 494 return vptr; 495 495 } 496 496 497 ptr = ( ( psMemBlock * ) vptr) - 1;498 499 if ( checkMemBlock( ptr, __func__ )) {500 memProblemCallback( ptr, file, lineno);501 } 502 503 pthread_mutex_lock( &ptr->refCounterMutex);497 ptr = ((psMemBlock *) vptr) - 1; 498 499 if (checkMemBlock(ptr, __func__)) { 500 memProblemCallback(ptr, file, lineno); 501 } 502 503 pthread_mutex_lock(&ptr->refCounterMutex); 504 504 ptr->refCounter++; 505 pthread_mutex_unlock( &ptr->refCounterMutex);505 pthread_mutex_unlock(&ptr->refCounterMutex); 506 506 507 507 return vptr; … … 509 509 510 510 // decrement and return refCounter 511 void * p_psMemDecrRefCounter( void *vptr, const char *file, int lineno)512 { 513 if ( vptr == NULL) {511 void *p_psMemDecrRefCounter(void *vptr, const char *file, int lineno) 512 { 513 if (vptr == NULL) { 514 514 return NULL; 515 515 } 516 516 517 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;518 519 if ( checkMemBlock( ptr, __func__ ) != 0) {520 memProblemCallback( ptr, file, lineno);517 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 518 519 if (checkMemBlock(ptr, __func__) != 0) { 520 memProblemCallback(ptr, file, lineno); 521 521 return NULL; 522 522 } 523 523 524 pthread_mutex_lock( &ptr->refCounterMutex);525 526 if ( ptr->refCounter > 1) {527 // / XXX - Probably should have another mutex here.528 ptr->refCounter--; // multiple references, just decrement the count.529 pthread_mutex_unlock( &ptr->refCounterMutex);524 pthread_mutex_lock(&ptr->refCounterMutex); 525 526 if (ptr->refCounter > 1) { 527 // / XXX - Probably should have another mutex here. 528 ptr->refCounter--; // multiple references, just decrement the count. 529 pthread_mutex_unlock(&ptr->refCounterMutex); 530 530 531 531 } else { 532 pthread_mutex_unlock( &ptr->refCounterMutex);532 pthread_mutex_unlock(&ptr->refCounterMutex); 533 533 534 534 // Did the user ask to be informed about this deallocation? 535 if ( ptr->id == p_psMemFreeID) {536 p_psMemFreeID += memFreeCallback( ptr);537 } 538 539 if ( ptr->freeFcn != NULL) {540 ptr->freeFcn( vptr);541 } 542 543 pthread_mutex_lock( &memBlockListMutex);535 if (ptr->id == p_psMemFreeID) { 536 p_psMemFreeID += memFreeCallback(ptr); 537 } 538 539 if (ptr->freeFcn != NULL) { 540 ptr->freeFcn(vptr); 541 } 542 543 pthread_mutex_lock(&memBlockListMutex); 544 544 545 545 // cut the memBlock out of the memBlock list 546 if ( ptr->nextBlock != NULL) {546 if (ptr->nextBlock != NULL) { 547 547 ptr->nextBlock->previousBlock = ptr->previousBlock; 548 548 } 549 if ( ptr->previousBlock != NULL) {549 if (ptr->previousBlock != NULL) { 550 550 ptr->previousBlock->nextBlock = ptr->nextBlock; 551 551 } 552 if ( lastMemBlockAllocated == ptr) {552 if (lastMemBlockAllocated == ptr) { 553 553 lastMemBlockAllocated = ptr->nextBlock; 554 554 } 555 555 556 pthread_mutex_unlock( &memBlockListMutex ); 557 556 pthread_mutex_unlock(&memBlockListMutex); 558 557 559 558 // do we need to recycle? 560 if ( ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) {559 if (ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) { 561 560 562 561 int level = 1; 563 while ( ptr->userMemorySize >= recycleBinSize[ level ] ) { 562 563 while (ptr->userMemorySize >= recycleBinSize[level]) { 564 564 level++; 565 565 } … … 569 569 ptr->previousBlock = NULL; 570 570 571 pthread_mutex_lock( &recycleMemBlockListMutex);572 ptr->nextBlock = recycleMemBlockList[ level];573 if ( recycleMemBlockList[ level ] != NULL) {574 recycleMemBlockList[ level ]->previousBlock = ptr;575 } 576 recycleMemBlockList[ level] = ptr;577 pthread_mutex_unlock( &recycleMemBlockListMutex);571 pthread_mutex_lock(&recycleMemBlockListMutex); 572 ptr->nextBlock = recycleMemBlockList[level]; 573 if (recycleMemBlockList[level] != NULL) { 574 recycleMemBlockList[level]->previousBlock = ptr; 575 } 576 recycleMemBlockList[level] = ptr; 577 pthread_mutex_unlock(&recycleMemBlockListMutex); 578 578 579 579 } else { 580 580 // memory is larger than I want to recycle. 581 581 #ifdef PS_MEM_DEBUG 582 ( void ) p_psRealloc( vptr, 0, file, lineno);582 (void)p_psRealloc(vptr, 0, file, lineno); 583 583 ptr->previousBlock = NULL; 584 584 ptr->nextBlock = deadBlockList; 585 if ( deadBlockList != NULL) {585 if (deadBlockList != NULL) { 586 586 deadBlockList->previous = ptr; 587 587 } … … 589 589 #else 590 590 591 pthread_mutex_destroy( &ptr->refCounterMutex);592 free( ptr);591 pthread_mutex_destroy(&ptr->refCounterMutex); 592 free(ptr); 593 593 #endif 594 594 595 595 } 596 596 597 vptr = NULL; // since we freed it, make sure we return NULL.597 vptr = NULL; // since we freed it, make sure we return NULL. 598 598 } 599 599 … … 601 601 } 602 602 603 void p_psMemSetDeallocator( void* vptr, psFreeFcn freeFcn)604 { 605 if ( vptr == NULL) {606 return ;607 } 608 609 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;610 611 if ( checkMemBlock( ptr, __func__ ) != 0) {612 memProblemCallback( ptr, __func__, __LINE__);603 void p_psMemSetDeallocator(void *vptr, psFreeFcn freeFcn) 604 { 605 if (vptr == NULL) { 606 return; 607 } 608 609 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 610 611 if (checkMemBlock(ptr, __func__) != 0) { 612 memProblemCallback(ptr, __func__, __LINE__); 613 613 } 614 614 … … 616 616 617 617 } 618 psFreeFcn p_psMemGetDeallocator( void* vptr)619 { 620 if ( vptr == NULL) {618 psFreeFcn p_psMemGetDeallocator(void *vptr) 619 { 620 if (vptr == NULL) { 621 621 return NULL; 622 622 } 623 623 624 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;625 626 if ( checkMemBlock( ptr, __func__ ) != 0) {627 memProblemCallback( ptr, __func__, __LINE__);624 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 625 626 if (checkMemBlock(ptr, __func__) != 0) { 627 memProblemCallback(ptr, __func__, __LINE__); 628 628 } 629 629 -
trunk/psLib/src/sys/psMemory.h
r1406 r1407 1 1 #if !defined(PS_MEMORY_H) 2 #define PS_MEMORY_H 2 # define PS_MEMORY_H 3 3 4 /** @file psMemory.h 4 5 * … … 14 15 * @ingroup MemoryManagement 15 16 * 16 * @version $Revision: 1.2 3$ $Name: not supported by cvs2svn $17 * @date $Date: 2004-08-0 6 22:34:05$17 * @version $Revision: 1.24 $ $Name: not supported by cvs2svn $ 18 * @date $Date: 2004-08-07 00:06:06 $ 18 19 * 19 20 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 20 21 */ 21 22 22 # include <stdio.h>// needed for FILE23 # include <stdbool.h>24 # include <pthread.h>// we need a mutex to make this stuff thread safe.23 # include <stdio.h> // needed for FILE 24 # include <stdbool.h> 25 # include <pthread.h> // we need a mutex to make this stuff thread safe. 25 26 26 27 /** @addtogroup MemoryManagement … … 53 54 54 55 /// typedef for deallocator. 55 typedef void (*psFreeFcn) (void*ptr);56 typedef void (*psFreeFcn) (void *ptr); 56 57 57 58 /** Book-keeping data for storage allocator. … … 62 63 typedef struct psMemBlock 63 64 { 64 const void * startblock; ///< initialised to p_psMEMMAGIC65 struct psMemBlock * previousBlock; ///< previous block in allocation list66 struct psMemBlock * nextBlock; ///< next block allocation list67 psFreeFcn freeFcn; ///< deallocator. If NULL, use generic deallocation.68 size_t userMemorySize; ///< the size of the user-portion of the memory block69 const psMemoryId id; ///< a unique ID for this allocation70 const char * file; ///< set from __FILE__ in e.g. p_psAlloc71 const int lineno; ///< set from __LINE__ in e.g. p_psAlloc72 pthread_mutex_t refCounterMutex; ///< mutex to ensure exclusive access to reference counter73 psReferenceCount refCounter; ///< how many times pointer is referenced74 const void * endblock; ///< initialised to p_psMEMMAGIC65 const void *startblock; // /< initialised to p_psMEMMAGIC 66 struct psMemBlock *previousBlock; // /< previous block in allocation list 67 struct psMemBlock *nextBlock; // /< next block allocation list 68 psFreeFcn freeFcn; // /< deallocator. If NULL, use generic deallocation. 69 size_t userMemorySize; // /< the size of the user-portion of the memory block 70 const psMemoryId id; // /< a unique ID for this allocation 71 const char *file; // /< set from __FILE__ in e.g. p_psAlloc 72 const int lineno; // /< set from __LINE__ in e.g. p_psAlloc 73 pthread_mutex_t refCounterMutex; // /< mutex to ensure exclusive access to reference counter 74 psReferenceCount refCounter; // /< how many times pointer is referenced 75 const void *endblock; // /< initialised to p_psMEMMAGIC 75 76 } 76 77 psMemBlock; … … 81 82 * @ingroup memCallback 82 83 */ 83 typedef psMemoryId (*psMemAllocateCallback)( 84 const psMemBlock *ptr ///< the psMemBlock just allocated 85 ); 84 typedef psMemoryId(*psMemAllocateCallback) (const psMemBlock * ptr // /< the psMemBlock just allocated 85 ); 86 86 87 87 /** prototype of memory free callback used by memory functions … … 90 90 * @ingroup memCallback 91 91 */ 92 typedef psMemoryId (*psMemFreeCallback)( 93 const psMemBlock *ptr ///< the psMemBlock being freed 94 ); 92 typedef psMemoryId(*psMemFreeCallback) (const psMemBlock * ptr // /< the psMemBlock being freed 93 ); 95 94 96 95 /** prototype of a callback used in error conditions … … 101 100 * @ingroup memCallback 102 101 */ 103 typedef void (*psMemProblemCallback) (104 const psMemBlock *ptr, ///< the pointer to the problematic memoryblock.105 const char *file, ///< the file in which the problem originated106 int lineno ///< the line number in which the problem originated107 );102 typedef void (*psMemProblemCallback) (const psMemBlock * ptr, // /< the pointer to the problematic memory 103 // block. 104 const char *file, // /< the file in which the problem originated 105 int lineno // /< the line number in which the problem originated 106 ); 108 107 109 108 /** prototype of a callback function used when memory runs out … … 115 114 * @ingroup memCallback 116 115 */ 117 typedef void *(*psMemExhaustedCallback)( 118 size_t size //< the size of buffer required 119 ); 116 typedef void *(*psMemExhaustedCallback) (size_t size // < the size of buffer required 117 ); 120 118 121 119 /** Memory allocation. This operates much like malloc(), but is guaranteed to return a non-NULL value. … … 124 122 * @see psFree 125 123 */ 126 #ifdef DOXYGEN 127 void* psAlloc( 128 size_t size ///< Size required 129 ); 130 #else 131 void* p_psAlloc( 132 size_t size, ///< Size required 133 const char *file, ///< File of call 134 int lineno ///< Line number of call 135 ); 136 137 void p_psMemSetDeallocator(void* ptr, psFreeFcn freeFcn); 138 psFreeFcn p_psMemGetDeallocator(void* ptr); 124 # ifdef DOXYGEN 125 void *psAlloc(size_t size // /< Size required 126 ); 127 # else 128 void *p_psAlloc(size_t size, // /< Size required 129 const char *file, // /< File of call 130 int lineno // /< Line number of call 131 ); 132 133 void p_psMemSetDeallocator(void *ptr, psFreeFcn freeFcn); 134 psFreeFcn p_psMemGetDeallocator(void *ptr); 139 135 140 136 /// Memory allocation. psAlloc sends file and line number to p_psAlloc. 141 #define psAlloc(size) p_psAlloc(size, __FILE__, __LINE__) 142 #endif 143 137 # define psAlloc(size) p_psAlloc(size, __FILE__, __LINE__) 138 # endif 144 139 145 140 /** Memory re-allocation. This operates much like realloc(), but is guaranteed to return a non-NULL value. … … 148 143 * @see psAlloc, psFree 149 144 */ 150 # ifdef DOXYGEN151 void * psRealloc(void *ptr ///< Pointer to re-allocate152 size_t size, ///< Size required145 # ifdef DOXYGEN 146 void *psRealloc(void *ptr // /< Pointer to re-allocate 147 size_t size, // /< Size required 153 148 ); 154 #else 155 void* p_psRealloc(void *ptr, ///< Pointer to re-allocate 156 size_t size, ///< Size required 157 const char *file, ///< File of call 158 int lineno ///< Line number of call 149 # else 150 void *p_psRealloc(void *ptr, // /< Pointer to re-allocate 151 size_t size, // /< Size required 152 const char *file, // /< File of call 153 int lineno // /< Line number of call 154 ); 155 156 /// Memory re-allocation. psRealloc sends file and line number to p_psRealloc. 157 # define psRealloc(ptr, size) p_psRealloc(ptr, size, __FILE__, __LINE__) 158 159 # endif 160 161 /** Free memory. This operates much like free(). 162 * 163 * @see psAlloc, psRealloc 164 */ 165 # ifdef DOXYGEN 166 void psFree(void *ptr, // /< Pointer to free, if NULL, function returns immediately. 167 ); 168 # else 169 void p_psFree(void *ptr, // /< Pointer to free 170 const char *file, // /< File of call 171 int lineno // /< Line number of call 159 172 ); 160 173 161 /// Memory re-allocation. psRealloc sends file and line number to p_psRealloc.162 #define psRealloc(ptr, size) p_psRealloc(ptr, size, __FILE__, __LINE__)163 164 #endif165 166 167 /** Free memory. This operates much like free().168 *169 * @see psAlloc, psRealloc170 */171 #ifdef DOXYGEN172 void psFree(void *ptr, ///< Pointer to free, if NULL, function returns immediately.173 );174 #else175 void p_psFree(void *ptr, ///< Pointer to free176 const char *file, ///< File of call177 int lineno ///< Line number of call178 );179 180 174 /// Free memory. psFree sends file and line number to p_psFree. 181 # define psFree(size) p_psFree(size, __FILE__, __LINE__)182 183 # endif175 # define psFree(size) p_psFree(size, __FILE__, __LINE__) 176 177 # endif 184 178 185 179 /** Check for memory leaks. This scans for allocated memory buffers not freed with an ID not less than id0. … … 197 191 * @ingroup memTracing 198 192 */ 199 int psMemCheckLeaks( 200 psMemoryId id0, ///< don't list blocks with id < id0 201 psMemBlock ***arr, ///< pointer to array of pointers to leaked blocks, or NULL 202 FILE *fd ///< print list of leaks to fd (or NULL) 203 ); 193 int psMemCheckLeaks(psMemoryId id0, // /< don't list blocks with id < id0 194 psMemBlock *** arr, // /< pointer to array of pointers to leaked blocks, or NULL 195 FILE * fd // /< print list of leaks to fd (or NULL) 196 ); 204 197 205 198 /** Check for memory corruption. Scans all currently allocated memory buffers and checks for corruptions, … … 208 201 * @ingroup memTracing 209 202 */ 210 int psMemCheckCorruption( 211 bool abort_on_error ///< Abort on detecting corruption? 212 ); 203 int psMemCheckCorruption(bool abort_on_error // /< Abort on detecting corruption? 204 ); 213 205 214 206 /** Return reference counter … … 216 208 * @ingroup memRefCount 217 209 */ 218 psReferenceCount psMemGetRefCounter( 219 void *vptr ///< Pointer to get refCounter for 220 ); 210 psReferenceCount psMemGetRefCounter(void *vptr // /< Pointer to get refCounter for 211 ); 221 212 222 213 /** Increment reference counter and return the pointer … … 224 215 * @ingroup memRefCount 225 216 */ 226 #ifdef DOXYGEN 227 void* psMemIncrRefCounter( 228 void *vptr ///< Pointer to increment refCounter, and return 229 ); 230 #else 231 void* p_psMemIncrRefCounter( 232 void *vptr, ///< Pointer to increment refCounter, and return 233 const char *file, ///< File of call 234 int lineno ///< Line number of call 235 ); 236 #define psMemIncrRefCounter(vptr) p_psMemIncrRefCounter(vptr, __FILE__, __LINE__) 237 #endif 217 # ifdef DOXYGEN 218 void *psMemIncrRefCounter(void *vptr // /< Pointer to increment refCounter, and return 219 ); 220 # else 221 void *p_psMemIncrRefCounter(void *vptr, // /< Pointer to increment refCounter, and return 222 const char *file, // /< File of call 223 int lineno // /< Line number of call 224 ); 225 226 # define psMemIncrRefCounter(vptr) p_psMemIncrRefCounter(vptr, __FILE__, __LINE__) 227 # endif 238 228 239 229 /** Decrement reference counter and return the pointer … … 241 231 * @ingroup memRefCount 242 232 */ 243 #ifdef DOXYGEN 244 void* psMemDecrRefCounter( 245 void *vptr ///< Pointer to decrement refCounter, and return 246 ); 247 #else 248 void* p_psMemDecrRefCounter( 249 void *vptr, ///< Pointer to decrement refCounter, and return 250 const char *file, ///< File of call 251 int lineno ///< Line number of call 252 ); 253 #define psMemDecrRefCounter(vptr) p_psMemDecrRefCounter(vptr, __FILE__, __LINE__) 254 #endif 233 # ifdef DOXYGEN 234 void *psMemDecrRefCounter(void *vptr // /< Pointer to decrement refCounter, and return 235 ); 236 # else 237 void *p_psMemDecrRefCounter(void *vptr, // /< Pointer to decrement refCounter, and return 238 const char *file, // /< File of call 239 int lineno // /< Line number of call 240 ); 241 242 # define psMemDecrRefCounter(vptr) p_psMemDecrRefCounter(vptr, __FILE__, __LINE__) 243 # endif 255 244 256 245 /** Set callback for problems 257 246 * @ingroup memCallback 258 247 */ 259 psMemProblemCallback psMemProblemCallbackSet( 260 psMemProblemCallback func ///< Function to run 261 ); 248 psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func // /< Function to run 249 ); 262 250 263 251 /** Set callback for out-of-memory … … 265 253 * @ingroup memCallback 266 254 */ 267 psMemExhaustedCallback psMemExhaustedCallbackSet( 268 psMemExhaustedCallback func ///< Function to run 269 ); 255 psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func // /< Function to run 256 ); 270 257 271 258 /** Set call back for when a particular memory block is allocated … … 273 260 * @ingroup memCallback 274 261 */ 275 psMemAllocateCallback psMemAllocateCallbackSet( 276 psMemAllocateCallback func ///< Function to run 277 ); 262 psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func // /< Function to run 263 ); 278 264 279 265 /** Set call back for when a particular memory block is freed … … 281 267 * @ingroup memCallback 282 268 */ 283 psMemFreeCallback psMemFreeCallbackSet( 284 psMemFreeCallback func ///< Function to run 285 ); 269 psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func // /< Function to run 270 ); 286 271 287 272 /** get next memory ID … … 295 280 * @ingroup memCallback 296 281 */ 297 psMemoryId psMemAllocateCallbackSetID( 298 psMemoryId id ///< ID to set 299 ); 282 psMemoryId psMemAllocateCallbackSetID(psMemoryId id // /< ID to set 283 ); 300 284 301 285 /** set p_psMemFreeID to id … … 303 287 * @ingroup memCallback 304 288 */ 305 psMemoryId psMemFreeCallbackSetID( 306 psMemoryId id ///< ID to set 307 ); 289 psMemoryId psMemFreeCallbackSetID(psMemoryId id // /< ID to set 290 ); 308 291 309 292 //@} End of Memory Management Functions 310 293 311 # ifndef DOXYGEN294 # ifndef DOXYGEN 312 295 313 296 /* 314 297 * Ensure that any program using malloc/realloc/free will fail to compile 315 298 */ 316 #ifndef PS_ALLOW_MALLOC 317 #ifdef __GNUC__ 318 #pragma GCC poison malloc realloc calloc free 319 #else 320 #define malloc(S) _Pragma("error Use of malloc is not allowed. Use psAlloc instead.") 321 #define realloc(P,S) _Pragma("error Use of realloc is not allowed. Use psRealloc instead.") 322 #define calloc(S) _Pragma("error Use of calloc is not allowed. Use psAlloc instead.") 323 #define free(P) _Pragma("error Use of free is not allowed. Use psFree instead.") 324 #endif 325 #endif 326 327 #endif // doxygen skip 328 329 #endif // end of header file 299 # ifndef PS_ALLOW_MALLOC 300 # ifdef __GNUC__ 301 # pragma GCC poison malloc realloc calloc free 302 # else 303 # define malloc(S) _Pragma("error Use of malloc is not allowed. Use psAlloc instead.") 304 # define realloc(P,S) _Pragma("error Use of realloc is not allowed. Use psRealloc instead.") 305 # define calloc(S) _Pragma("error Use of calloc is not allowed. Use psAlloc instead.") 306 # define free(P) _Pragma("error Use of free is not allowed. Use psFree instead.") 307 # endif 308 # endif 309 310 # endif 311 // doxygen skip 312 313 #endif // end of header file -
trunk/psLib/src/sys/psString.c
r1406 r1407 1 1 2 /** @file psString.c 2 3 * … … 8 9 * @author Eric Van Alst, MHPCC 9 10 * 10 * @version $Revision: 1. 7$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.8 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 22 #include <stdlib.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 char *psStringCopy( 60 const char* str 61 ) 74 char *psStringCopy(const char *str) 62 75 { 63 76 // Allocate memory using psAlloc function … … 67 80 } 68 81 69 char *psStringNCopy( 70 const char* str, 71 int nChar 72 ) 82 char *psStringNCopy(const char *str, int nChar) 73 83 { 74 84 char *returnValue = NULL; 75 85 76 86 // Check the number of characters to copy is non-negative 77 if ( nChar < 0) {87 if (nChar < 0) { 78 88 // Log error message and return NULL 79 psError(__FILE__,"psStringNCopy with negative count specified %d", 80 nChar); 89 psError(__FILE__, "psStringNCopy with negative count specified %d", nChar); 81 90 return NULL; 82 91 } … … 84 93 // Copy input string to memory allocated up to nChar characters 85 94 // Return the copy 86 returnValue = strncpy(psAlloc((size_t) nChar + 1), str, (size_t)nChar);95 returnValue = strncpy(psAlloc((size_t) nChar + 1), str, (size_t) nChar); 87 96 88 97 // Ensure the last byte is NULL character 89 if ( nChar > 0) {90 returnValue[nChar -1] = '\0';98 if (nChar > 0) { 99 returnValue[nChar - 1] = '\0'; 91 100 } 92 93 101 // Return the string pointer 94 102 return returnValue; 95 103 } 96 97 -
trunk/psLib/src/sys/psString.h
r974 r1407 1 1 2 /** @file psString.h 2 3 * … … 10 11 * @author Eric Van Alst, MHPCC 11 12 * 12 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-0 6-10 01:58:06 $13 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_STRING_H 19 # define PS_STRING_H20 # define PS_STRING_H 20 21 21 22 /******************************************************************************/ 23 22 24 /* DEFINE STATEMENTS */ 25 23 26 /******************************************************************************/ 24 27 25 28 /** This macro will convert the arguement to a quoted string */ 26 # define PS_STRING(S) #S29 # define PS_STRING(S) #S 27 30 28 31 /******************************************************************************/ 32 29 33 /* TYPE DEFINITIONS */ 34 30 35 /******************************************************************************/ 31 36 … … 33 38 34 39 /*****************************************************************************/ 40 35 41 /* FUNCTION PROTOTYPES */ 42 36 43 /*****************************************************************************/ 37 44 38 45 // Doxygen group tags 46 39 47 /** @addtogroup SysUtils 40 48 * @{ … … 49 57 * 50 58 */ 51 char *psStringCopy(52 const char *str /**< Input string of characters to copy */53 );54 59 60 char *psStringCopy(const char *str 61 /**< Input string of characters to copy */ 62 ); 55 63 56 64 /** Copies the input string up to the specified number of characters … … 67 75 * 68 76 */ 77 69 78 /*@null@*/ 70 char *psStringNCopy(71 const char *str, /**< Input string of characters to copy */72 int nChar /**< Number of bytes to allocate for string copy */73 );74 79 75 /* @} */ // Doxygen - End of SystemGroup Functions 80 char *psStringNCopy(const char *str, 81 /**< Input string of characters to copy */ 82 83 int nChar 84 /**< Number of bytes to allocate for string copy */ 85 ); 86 87 /* @} */// Doxygen - End of SystemGroup Functions 76 88 77 89 #endif 78 -
trunk/psLib/src/sys/psTrace.c
r1406 r1407 1 1 2 /** @file psTrace.c 2 3 * \brief basic run-time trace facilities … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 17 16 18 /***************************************************************************** 17 19 NOTES: … … 34 36 #ifndef PS_NO_TRACE 35 37 36 # include <stdlib.h>37 # include <stdio.h>38 # include <string.h>39 # include <stdarg.h>40 # include "psMemory.h"41 # include "psTrace.h"42 # include "psString.h"43 # include "psError.h"44 45 static p_psComponent *p_psCroot = NULL; // The root of the trace component46 static FILE *p_psTraceFP = NULL; // File destination for messages.47 48 static void componentFree(p_psComponent * comp);49 static p_psComponent *componentAlloc(const char *name, int level);38 # include <stdlib.h> 39 # include <stdio.h> 40 # include <string.h> 41 # include <stdarg.h> 42 # include "psMemory.h" 43 # include "psTrace.h" 44 # include "psString.h" 45 # include "psError.h" 46 47 static p_psComponent *p_psCroot = NULL; // The root of the trace component 48 static FILE *p_psTraceFP = NULL; // File destination for messages. 49 50 static void componentFree(p_psComponent * comp); 51 static p_psComponent *componentAlloc(const char *name, int level); 50 52 51 53 /***************************************************************************** 52 54 componentAlloc(): allocate memory for a new node, and initialize members. 53 55 *****************************************************************************/ 54 static p_psComponent *componentAlloc(const char *name, 55 int level) 56 static p_psComponent *componentAlloc(const char *name, int level) 56 57 { 57 58 p_psComponent *comp = psAlloc(sizeof(p_psComponent)); 58 p_psMemSetDeallocator(comp,(psFreeFcn)componentFree); 59 60 p_psMemSetDeallocator(comp, (psFreeFcn) componentFree); 59 61 comp->name = psStringCopy(name); 60 62 comp->level = level; … … 64 66 } 65 67 66 67 68 /***************************************************************************** 68 69 componentFree(): free the current node in the root tree, and all children 69 70 nodes as well. 70 71 *****************************************************************************/ 71 static void componentFree(p_psComponent * comp)72 static void componentFree(p_psComponent * comp) 72 73 { 73 74 if (comp == NULL) { … … 85 86 } 86 87 87 88 88 /***************************************************************************** 89 89 initTrace(): simply initialize the component root tree. … … 96 96 } 97 97 98 99 98 /***************************************************************************** 100 99 Set all trace levels to zero. 101 100 *****************************************************************************/ 102 void p_psTraceReset(p_psComponent * currentNode)101 void p_psTraceReset(p_psComponent * currentNode) 103 102 { 104 103 int i = 0; … … 109 108 110 109 currentNode->level = 0; 111 for (i =0;i<currentNode->n;i++) {110 for (i = 0; i < currentNode->n; i++) { 112 111 if (NULL == currentNode->subcomp[i]) { 113 112 psError(__func__, 114 "Sub-component %d of node %s in the trace tree is NULL.\n", 115 i, currentNode->name); 113 "Sub-component %d of node %s in the trace tree is NULL.\n", i, currentNode->name); 116 114 } else { 117 115 p_psTraceReset(currentNode->subcomp[i]); … … 129 127 } 130 128 131 132 129 /***************************************************************************** 133 130 Free all nodes in the component tree. … … 137 134 psFree(p_psCroot); 138 135 } 139 140 136 141 137 /***************************************************************************** … … 145 141 to ANSI-C. 146 142 *****************************************************************************/ 147 static void componentAdd(const char *addNodeName, 148 int level) 149 { 150 int i = 0; // Loop index variable. 151 char name[strlen(addNodeName) + 1]; // buffer for writeable copy. 152 char *pname=name; 153 char *firstComponent = NULL; // first component of name 143 static void componentAdd(const char *addNodeName, int level) 144 { 145 int i = 0; // Loop index variable. 146 char name[strlen(addNodeName) + 1]; // buffer for writeable copy. 147 char *pname = name; 148 char *firstComponent = NULL; // first component of name 154 149 p_psComponent *currentNode = p_psCroot; 155 int nodeExists = 0;156 157 // Is this the root node? If so, simply set level and return.150 int nodeExists = 0; 151 152 // Is this the root node? If so, simply set level and return. 158 153 if (strcmp(".", addNodeName) == 0) { 159 154 p_psCroot->level = level; … … 162 157 163 158 if (addNodeName[0] != '.') { 164 printf("ERROR: failed to add %s to the root component tree.\n", 165 addNodeName); 159 printf("ERROR: failed to add %s to the root component tree.\n", addNodeName); 166 160 exit(1); 167 161 } … … 188 182 if (nodeExists == 0) { 189 183 currentNode->subcomp = psRealloc(currentNode->subcomp, 190 (currentNode->n + 1) * sizeof(p_psComponent*)); 191 currentNode->n = (currentNode->n)+1; 192 193 currentNode->subcomp[(currentNode->n)-1] = 194 componentAlloc(firstComponent, level); 195 } 196 } 197 } 198 184 (currentNode->n + 1) * sizeof(p_psComponent *)); 185 currentNode->n = (currentNode->n) + 1; 186 187 currentNode->subcomp[(currentNode->n) - 1] = componentAlloc(firstComponent, level); 188 } 189 } 190 } 199 191 200 192 /***************************************************************************** … … 210 202 *****************************************************************************/ 211 203 int psTraceSetLevel(const char *comp, // component of interest 212 int level) // desired trace level204 int level) // desired trace level 213 205 { 214 206 // If the root component tree does not exist, then initialize it. … … 216 208 initTrace(); 217 209 } 218 219 210 // Add the new component to the component tree. 220 211 componentAdd(comp, level); … … 223 214 return 0; 224 215 } 225 226 216 227 217 /***************************************************************************** … … 241 231 static int doGetTraceLevel(const char *aname) 242 232 { 243 char name[strlen(aname) + 1];// need a writeable copy: for strsep()244 char *pname=name;245 char *firstComponent = NULL;// first component of name233 char name[strlen(aname) + 1]; // need a writeable copy: for strsep() 234 char *pname = name; 235 char *firstComponent = NULL; // first component of name 246 236 p_psComponent *currentNode = p_psCroot; 247 int i = 0;237 int i = 0; 248 238 249 239 if (NULL == currentNode) { 250 return (PS_UNKNOWN_TRACE_LEVEL);240 return (PS_UNKNOWN_TRACE_LEVEL); 251 241 } 252 242 253 243 if (strcmp(".", aname) == 0) { 254 return (p_psCroot->level);244 return (p_psCroot->level); 255 245 } 256 246 257 247 if (aname[0] != '.') { 258 return (PS_UNKNOWN_TRACE_LEVEL);248 return (PS_UNKNOWN_TRACE_LEVEL); 259 249 } 260 250 … … 266 256 if (NULL == currentNode->subcomp[i]) { 267 257 psError(__func__, 268 "Sub-component %d of node %s in trace tree is NULL.\n", 269 i, currentNode->name); 258 "Sub-component %d of node %s in trace tree is NULL.\n", i, currentNode->name); 270 259 } 271 260 … … 273 262 currentNode = currentNode->subcomp[i]; 274 263 if (pname == NULL) { 275 return (currentNode->level);264 return (currentNode->level); 276 265 } 277 266 } 278 267 } 279 268 } 280 return(PS_UNKNOWN_TRACE_LEVEL); 281 } 282 269 return (PS_UNKNOWN_TRACE_LEVEL); 270 } 283 271 284 272 /***************************************************************************** … … 297 285 { 298 286 if (p_psCroot == NULL) { 299 return(PS_UNKNOWN_TRACE_LEVEL); 300 } 301 287 return (PS_UNKNOWN_TRACE_LEVEL); 288 } 302 289 // Search the component root tree, determine the trace level. 303 return(doGetTraceLevel(name)); 304 } 305 290 return (doGetTraceLevel(name)); 291 } 306 292 307 293 /***************************************************************************** … … 317 303 null 318 304 *****************************************************************************/ 319 static void doPrintTraceLevels(const p_psComponent *comp, 320 int depth) 305 static void doPrintTraceLevels(const p_psComponent * comp, int depth) 321 306 { 322 307 int i = 0; … … 327 312 } else { 328 313 if (comp->level == PS_UNKNOWN_TRACE_LEVEL) { 329 printf("%*s%-*s %s\n", depth, "", 20 - depth, 330 comp->name, "."); 314 printf("%*s%-*s %s\n", depth, "", 20 - depth, comp->name, "."); 331 315 } else { 332 printf("%*s%-*s %d\n", depth, "", 20 - depth, 333 comp->name, comp->level); 316 printf("%*s%-*s %d\n", depth, "", 20 - depth, comp->name, comp->level); 334 317 } 335 318 } 336 319 337 320 for (i = 0; i < comp->n; i++) { 338 doPrintTraceLevels(comp->subcomp[i], depth+1); 339 } 340 } 341 321 doPrintTraceLevels(comp->subcomp[i], depth + 1); 322 } 323 } 342 324 343 325 /***************************************************************************** … … 359 341 doPrintTraceLevels(p_psCroot, 0); 360 342 } 361 362 343 363 344 /***************************************************************************** … … 376 357 *****************************************************************************/ 377 358 void p_psTrace(const char *comp, // component being traced 378 int level, // desired trace level379 ...) // arguments359 int level, // desired trace level 360 ...) // arguments 380 361 { 381 362 char *fmt = NULL; … … 384 365 385 366 if (NULL == comp) { 386 psError(__func__, 387 "p_psTrace() called on a NULL trace level tree\n"); 388 } 389 367 psError(__func__, "p_psTrace() called on a NULL trace level tree\n"); 368 } 390 369 // Only display this message if it's trace level is less than the level 391 370 // of it's associatedcomponent. … … 413 392 va_end(ap); 414 393 } 415 416 // NOTE: should we free *fmt as well? Read the man page. 417 } 418 419 void psTraceSetDestination(FILE *fp) 394 // NOTE: should we free *fmt as well? Read the man page. 395 } 396 397 void psTraceSetDestination(FILE * fp) 420 398 { 421 399 p_psTraceFP = fp; -
trunk/psLib/src/sys/psTrace.h
r1393 r1407 1 1 2 /** @file psTrace.h 2 3 * \brief basic run-time trace facilities … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 5 19:38:52$12 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_TRACE_H) 17 # define PS_TRACE_H 118 # define PS_TRACE_H 1 18 19 19 #define PS_UNKNOWN_TRACE_LEVEL -9999 // we don't know this name's level 20 #define PS_DEFAULT_TRACE_LEVEL 0 21 20 # define PS_UNKNOWN_TRACE_LEVEL -9999 // we don't know this name's level 21 # define PS_DEFAULT_TRACE_LEVEL 0 22 22 23 23 /** \addtogroup LogTrace … … 29 29 //#define PS_NO_TRACE 1 ///< to turn off all tracing 30 30 31 #if defined(PS_NO_TRACE) 32 #define psTrace(facil, level, ...) (void)0 /* do nothing */ 33 #define p_psTrace(facil, level, ...) (void)0 /* do nothing */ 34 #define psTraceSetLevel(facil,level) 0 35 #define psTraceGetLevel(facil) 0 36 #define psTraceReset() (void)0 /* do nothing */ 37 #define psTraceFree() (void)0 /* do nothing */ 38 #define psTracePrintLevels() (void)0 /* do nothing */ 39 #define psTraceSetDestination(fp) (void)0 /* do nothing */ 40 #else 31 # if defined(PS_NO_TRACE) 32 # define psTrace(facil, level, ...) (void)0 33 /* do nothing */ 34 # define p_psTrace(facil, level, ...) (void)0 35 /* do nothing */ 36 # define psTraceSetLevel(facil,level) 0 37 # define psTraceGetLevel(facil) 0 38 # define psTraceReset() (void)0 /* do nothing */ 39 # define psTraceFree() (void)0 /* do nothing */ 40 # define psTracePrintLevels() (void)0 41 /* do nothing */ 42 # define psTraceSetDestination(fp) (void)0 43 /* do nothing */ 44 # else 41 45 42 /** Basic structure for the component tree. A component is a string of the43 form aaa.bbb.ccc, and may itself contain further subcomponents. The44 Component structure doesn't in fact contain it's full name, but only the45 last part. */46 typedef struct p_psComponent47 {48 const char *name;// last part of name of component49 int level;// trace level for this component50 int n;// number of subcomponents51 struct p_psComponent **subcomp;// next level of subcomponents52 }46 /** Basic structure for the component tree. A component is a string of the 47 form aaa.bbb.ccc, and may itself contain further subcomponents. The 48 Component structure doesn't in fact contain it's full name, but only the 49 last part. */ 50 typedef struct p_psComponent 51 { 52 const char *name; // last part of name of component 53 int level; // trace level for this component 54 int n; // number of subcomponents 55 struct p_psComponent **subcomp; // next level of subcomponents 56 } 53 57 p_psComponent; 54 58 55 # ifndef DOXYGEN59 # ifndef DOXYGEN 56 60 /// Send a trace message 57 void p_psTrace(const char *facil, ///< facilty of interest58 int myLevel, ///< desired trace level59 ...) ///< trace message arguments61 void p_psTrace(const char *facil, // /< facilty of interest 62 int myLevel, // /< desired trace level 63 ...) // /< trace message arguments 60 64 ; 61 # endif65 # endif 62 66 63 67 /// Set trace level 64 int psTraceSetLevel(const char *facil, ///< facilty of interest65 int level) ///< desired trace level68 int psTraceSetLevel(const char *facil, // /< facilty of interest 69 int level) // /< desired trace level 66 70 ; 67 71 68 72 /// Get the trace level 69 int psTraceGetLevel(const char *facil) ///< facilty of interest73 int psTraceGetLevel(const char *facil) // /< facilty of interest 70 74 ; 71 75 72 76 /// Set all trace levels to zero (do not free nodes in the component tree). 73 void psTraceReset() 74 ; 77 void psTraceReset(); 75 78 76 79 /// Free all nodes in the component tree. 77 void psTraceFree() 78 ; 80 void psTraceFree(); 79 81 80 82 /// print trace levels 81 void psTracePrintLevels(void) 82 ; 83 void psTracePrintLevels(void); 83 84 84 85 /// Set the destination of future trace messages. 85 void psTraceSetDestination(FILE * fp);86 void psTraceSetDestination(FILE * fp); 86 87 88 /* \} */// End of SystemGroup Functions 87 89 88 /* \} */ // End of SystemGroup Functions 89 90 #define psTrace(facil, level, ...) p_psTrace(facil, level, __VA_ARGS__) 91 #endif 90 # define psTrace(facil, level, ...) p_psTrace(facil, level, __VA_ARGS__) 91 # endif 92 92 93 93 #endif 94 -
trunk/psLib/src/sys/psType.h
r1385 r1407 1 1 2 /** @file psType.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 6$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 4 23:37:39$13 * @version $Revision: 1.17 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_TYPE_H 19 # define PS_TYPE_H20 # define PS_TYPE_H 20 21 21 # include <complex.h>22 # include <stdint.h>23 # include <float.h>22 # include <complex.h> 23 # include <stdint.h> 24 # include <float.h> 24 25 25 26 /// @addtogroup DataContainer … … 27 28 28 29 /******************************************************************************/ 30 29 31 /* TYPE DEFINITIONS */ 32 30 33 /******************************************************************************/ 31 34 … … 37 40 */ 38 41 39 typedef uint8_t psU8; ///< 8-bit unsigned int 40 typedef uint16_t psU16; ///< 16-bit unsigned int 41 typedef uint32_t psU32; ///< 32-bit unsigned int 42 typedef uint64_t psU64; ///< 64-bit unsigned int 43 typedef int8_t psS8; ///< 8-bit signed int 44 typedef int16_t psS16; ///< 16-bit signed int 45 typedef int32_t psS32; ///< 32-bit signed int 46 typedef int64_t psS64; ///< 64-bit signed int 47 typedef float psF32; ///< 32-bit floating point 48 typedef double psF64; ///< 64-bit floating point 49 typedef complex float psC32; ///< complex with 32-bit floating point Real and Imagary numbers 50 typedef complex double psC64; ///< complex with 64-bit floating point Real and Imagary numbers 51 typedef void* psPTR; ///< void pointer 52 42 typedef uint8_t psU8; // /< 8-bit unsigned int 43 typedef uint16_t psU16; // /< 16-bit unsigned int 44 typedef uint32_t psU32; // /< 32-bit unsigned int 45 typedef uint64_t psU64; // /< 64-bit unsigned int 46 typedef int8_t psS8; // /< 8-bit signed int 47 typedef int16_t psS16; // /< 16-bit signed int 48 typedef int32_t psS32; // /< 32-bit signed int 49 typedef int64_t psS64; // /< 64-bit signed int 50 typedef float psF32; // /< 32-bit floating point 51 typedef double psF64; // /< 64-bit floating point 52 typedef complex float psC32; // /< complex with 32-bit floating point Real and Imagary numbers 53 typedef complex double psC64; // /< complex with 64-bit floating point Real and Imagary numbers 54 typedef void *psPTR; // /< void pointer 53 55 54 56 typedef enum { 55 PS_TYPE_S8 = 0x0101, ///< Character. 56 PS_TYPE_S16 = 0x0102, ///< Short integer. 57 PS_TYPE_S32 = 0x0104, ///< Integer. 58 PS_TYPE_S64 = 0x0108, ///< Long integer. 59 PS_TYPE_U8 = 0x0301, ///< Unsigned character. 60 PS_TYPE_U16 = 0x0302, ///< Unsigned short integer. 61 PS_TYPE_U32 = 0x0304, ///< Unsigned integer. 62 PS_TYPE_U64 = 0x0308, ///< Unsigned long integer. 63 PS_TYPE_F32 = 0x0404, ///< Single-precision Floating point. 64 PS_TYPE_F64 = 0x0408, ///< Double-precision floating point. 65 PS_TYPE_C32 = 0x0808, ///< Complex numbers consisting of single-precision floating point. 66 PS_TYPE_C64 = 0x0810, ///< Complex numbers consisting of double-precision floating point. 67 PS_TYPE_PTR = 0x0000 ///< Something else that's not supported for arithmetic. 57 PS_TYPE_S8 = 0x0101, // /< Character. 58 PS_TYPE_S16 = 0x0102, // /< Short integer. 59 PS_TYPE_S32 = 0x0104, // /< Integer. 60 PS_TYPE_S64 = 0x0108, // /< Long integer. 61 PS_TYPE_U8 = 0x0301, // /< Unsigned character. 62 PS_TYPE_U16 = 0x0302, // /< Unsigned short integer. 63 PS_TYPE_U32 = 0x0304, // /< Unsigned integer. 64 PS_TYPE_U64 = 0x0308, // /< Unsigned long integer. 65 PS_TYPE_F32 = 0x0404, // /< Single-precision Floating point. 66 PS_TYPE_F64 = 0x0408, // /< Double-precision floating point. 67 PS_TYPE_C32 = 0x0808, // /< Complex numbers consisting of single-precision floating 68 // point. 69 PS_TYPE_C64 = 0x0810, // /< Complex numbers consisting of double-precision floating 70 // point. 71 PS_TYPE_PTR = 0x0000 // /< Something else that's not supported for arithmetic. 68 72 } psElemType; 69 73 70 # define PS_TYPE_MASK PS_TYPE_U8 ///< the psElemType to use for mask image71 # define PS_TYPE_MASK_DATA U8 ///< the data member to use for mask image72 # define PS_TYPE_MASK_NAME "psU8"73 typedef psU8 psMaskType; ///< the C datatype for a mask image74 # define PS_TYPE_MASK PS_TYPE_U8 // /< the psElemType to use for mask image 75 # define PS_TYPE_MASK_DATA U8 // /< the data member to use for mask image 76 # define PS_TYPE_MASK_NAME "psU8" 77 typedef psU8 psMaskType; // /< the C datatype for a mask image 74 78 75 # define PS_MIN_S8 INT8_MIN76 # define PS_MIN_S16 INT16_MIN77 # define PS_MIN_S32 INT32_MIN78 # define PS_MIN_S64 INT64_MIN79 # define PS_MIN_U8 080 # define PS_MIN_U16 081 # define PS_MIN_U32 082 # define PS_MIN_U64 083 # define PS_MIN_F32 -FLT_MAX84 # define PS_MIN_F64 -DBL_MAX85 # define PS_MIN_C32 -FLT_MAX86 # define PS_MIN_C64 -DBL_MAX79 # define PS_MIN_S8 INT8_MIN 80 # define PS_MIN_S16 INT16_MIN 81 # define PS_MIN_S32 INT32_MIN 82 # define PS_MIN_S64 INT64_MIN 83 # define PS_MIN_U8 0 84 # define PS_MIN_U16 0 85 # define PS_MIN_U32 0 86 # define PS_MIN_U64 0 87 # define PS_MIN_F32 -FLT_MAX 88 # define PS_MIN_F64 -DBL_MAX 89 # define PS_MIN_C32 -FLT_MAX 90 # define PS_MIN_C64 -DBL_MAX 87 91 88 # define PS_MAX_S8 INT8_MAX89 # define PS_MAX_S16 INT16_MAX90 # define PS_MAX_S32 INT32_MAX91 # define PS_MAX_S64 INT64_MAX92 # define PS_MAX_U8 UINT8_MAX93 # define PS_MAX_U16 UINT16_MAX94 # define PS_MAX_U32 UINT32_MAX95 # define PS_MAX_U64 UINT64_MAX96 # define PS_MAX_F32 FLT_MAX97 # define PS_MAX_F64 DBL_MAX98 # define PS_MAX_C32 FLT_MAX99 # define PS_MAX_C64 DBL_MAX92 # define PS_MAX_S8 INT8_MAX 93 # define PS_MAX_S16 INT16_MAX 94 # define PS_MAX_S32 INT32_MAX 95 # define PS_MAX_S64 INT64_MAX 96 # define PS_MAX_U8 UINT8_MAX 97 # define PS_MAX_U16 UINT16_MAX 98 # define PS_MAX_U32 UINT32_MAX 99 # define PS_MAX_U64 UINT64_MAX 100 # define PS_MAX_F32 FLT_MAX 101 # define PS_MAX_F64 DBL_MAX 102 # define PS_MAX_C32 FLT_MAX 103 # define PS_MAX_C64 DBL_MAX 100 104 101 105 /// Macro to get the bad pixel reason code (stored as part of mask value) 102 # define PS_BADPIXEL_BITMASK 0x0f103 # define PS_GET_BADPIXEL(maskValue) (maskValue & PS_BADPIXEL_BITMASK)106 # define PS_BADPIXEL_BITMASK 0x0f 107 # define PS_GET_BADPIXEL(maskValue) (maskValue & PS_BADPIXEL_BITMASK) 104 108 105 # define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)109 # define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0) 106 110 107 111 /// Macro to apply a bad pixel reason code to mask image 108 # define PS_SET_BADPIXEL(maskValue, reasonCode) \112 # define PS_SET_BADPIXEL(maskValue, reasonCode) \ 109 113 { \ 110 114 maskValue = (psMaskType)((reasonCode & PS_BADPIXEL_BITMASK) | (maskValue & ~PS_BADPIXEL_BITMASK)); \ … … 112 116 113 117 /// Macro to determine if the psElemType is an integer. 114 # define PS_IS_PSELEMTYPE_INT(x) ((x & 0x100) == 0x100)118 # define PS_IS_PSELEMTYPE_INT(x) ((x & 0x100) == 0x100) 115 119 /// Macro to determine if the psElemType is unsigned. 116 # define PS_IS_PSELEMTYPE_UNSIGNED(x) ((x & 0x200) == 0x200)120 # define PS_IS_PSELEMTYPE_UNSIGNED(x) ((x & 0x200) == 0x200) 117 121 /// Macro to determine if the psElemType is a real (non-complex) floating-point type. 118 # define PS_IS_PSELEMTYPE_REAL(x) ((x & 0x400) == 0x400)122 # define PS_IS_PSELEMTYPE_REAL(x) ((x & 0x400) == 0x400) 119 123 /// Macro to determine if the psElemType is complex number type. 120 # define PS_IS_PSELEMTYPE_COMPLEX(x) ((x & 0x800) == 0x800)124 # define PS_IS_PSELEMTYPE_COMPLEX(x) ((x & 0x800) == 0x800) 121 125 /// Macro to determine the storage size, in bytes, of the psElemType. 122 # define PSELEMTYPE_SIZEOF(x) ( (x==PS_TYPE_PTR) ? sizeof(void*) :(x & 0xFF) )126 # define PSELEMTYPE_SIZEOF(x) ( (x==PS_TYPE_PTR) ? sizeof(void*) :(x & 0xFF) ) 123 127 124 128 /** Dimensions of a data type. … … 128 132 */ 129 133 typedef enum { 130 PS_DIMEN_SCALAR, ///< Scalar.131 PS_DIMEN_VECTOR, ///< Vector.132 PS_DIMEN_TRANSV, ///< Transposed vector.133 PS_DIMEN_IMAGE, ///< Image.134 PS_DIMEN_OTHER ///< Something else that's not supported for arithmetic.134 PS_DIMEN_SCALAR, // /< Scalar. 135 PS_DIMEN_VECTOR, // /< Vector. 136 PS_DIMEN_TRANSV, // /< Transposed vector. 137 PS_DIMEN_IMAGE, // /< Image. 138 PS_DIMEN_OTHER // /< Something else that's not supported for arithmetic. 135 139 } psDimen; 136 140 … … 143 147 typedef struct 144 148 { 145 psElemType type; ///< Primitive type.146 psDimen dimen; ///< Dimensionality.149 psElemType type; // /< Primitive type. 150 psDimen dimen; // /< Dimensionality. 147 151 } 148 152 psType; -
trunk/psLib/src/sysUtils/psAbort.c
r1406 r1407 1 1 2 /** @file psAbort.c 2 3 * … … 9 10 * @author Eric Van Alst, MHPCC 10 11 * 11 * @version $Revision: 1. 7$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.8 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 16 17 17 18 /******************************************************************************/ 19 18 20 /* INCLUDE FILES */ 21 19 22 /******************************************************************************/ 20 23 #include <stdarg.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 void psAbort(const char *name, const char *fmt, ...)74 void psAbort(const char *name, const char *fmt, ...) 60 75 { 61 va_list argPtr;// variable list arguement pointer76 va_list argPtr; // variable list arguement pointer 62 77 63 78 // Get the variable list parameters to pass to logging function … … 73 88 abort(); 74 89 } 75 -
trunk/psLib/src/sysUtils/psAbort.h
r974 r1407 1 1 2 /** @file psAbort.h 2 3 * … … 11 12 * @author Eric Van Alst, MHPCC 12 13 * 13 * @version $Revision: 1. 4$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-0 6-10 01:58:06 $14 * @version $Revision: 1.5 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_ABORT_H 20 #define PS_ABORT_H 21 21 # define PS_ABORT_H 22 22 23 23 // Doxygen grouping tags 24 24 25 /** @addtogroup ErrorHandling 25 26 * @{ … … 36 37 * 37 38 */ 38 void psAbort( 39 const char* name, ///< Source of abort such as file or function detected 40 const char* fmt, ///< A printf style formatting statement defining msg 41 ... 42 ); 39 void psAbort(const char *name, // /< Source of abort such as file or function detected 40 const char *fmt, // /< A printf style formatting statement defining msg 41 ... 42 ); 43 43 44 /* @} */ // Doxygen - End of SystemGroup Functions44 /* @} */// Doxygen - End of SystemGroup Functions 45 45 46 46 #endif 47 -
trunk/psLib/src/sysUtils/psError.c
r1406 r1407 1 1 2 /** @file psError.c 2 3 * … … 10 11 * @author Eric Van Alst, MHPCC 11 12 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 /******************************************************************************/ 20 19 21 /* INCLUDE FILES */ 22 20 23 /******************************************************************************/ 21 24 #include <stdarg.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATIONS - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATIONS - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 void psError(const char *name, const char *fmt, ...)74 void psError(const char *name, const char *fmt, ...) 60 75 { 61 va_list argPtr;// variable list arguement pointer76 va_list argPtr; // variable list arguement pointer 62 77 63 // Get the variable list parameters to pass to logging function78 // Get the variable list parameters to pass to logging function 64 79 va_start(argPtr, fmt); 65 80 … … 70 85 va_end(argPtr); 71 86 } 72 -
trunk/psLib/src/sysUtils/psError.h
r974 r1407 1 1 2 /** @file psError.h 2 3 * … … 12 13 * @author Eric Van Alst, MHPCC 13 14 * 14 * @version $Revision: 1. 4$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-0 6-10 01:58:06 $15 * @version $Revision: 1.5 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PS_ERROR_H 21 # define PS_ERROR_H22 # define PS_ERROR_H 22 23 23 24 /** @addtogroup ErrorHandling … … 34 35 * 35 36 */ 36 void psError( 37 const char *name, ///< Source of error such as file or function detected 38 const char *fmt, ///< A printf style formatting statement defining msg 39 ... 40 ); 37 void psError(const char *name, // /< Source of error such as file or function detected 38 const char *fmt, // /< A printf style formatting statement defining msg 39 ... 40 ); 41 41 42 /* @} */ // End of SysUtils Functions42 /* @} */// End of SysUtils Functions 43 43 44 44 #endif 45 -
trunk/psLib/src/sysUtils/psHash.c
r1406 r1407 1 1 2 /** @file psHash.c 2 3 * … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 25 26 #include "psAbort.h" 26 27 27 static psHashBucket *hashBucketAlloc( const char *key, void *data, psHashBucket *next ); 28 static void hashBucketFree( psHashBucket *bucket ); 29 static void *doHashWork( psHash* table, const char* key, void* data, bool remove 30 ) 31 ; 32 static void hashFree( psHash *table ); 28 static psHashBucket *hashBucketAlloc(const char *key, void *data, psHashBucket * next); 29 static void hashBucketFree(psHashBucket * bucket); 30 static void *doHashWork(psHash * table, const char *key, void *data, bool remove 31 ); 32 static void hashFree(psHash * table); 33 33 34 34 /****************************************************************************** … … 40 40 The linked list 41 41 *****************************************************************************/ 42 psList *psHashKeyList( psHash *table)43 { 44 int i = 0; // Loop index variable42 psList *psHashKeyList(psHash * table) 43 { 44 int i = 0; // Loop index variable 45 45 psList *myLinkList = NULL; // The output data structure 46 psHashBucket *ptr = NULL; // Used to step thru linked list.47 48 if ( table == NULL) {46 psHashBucket *ptr = NULL; // Used to step thru linked list. 47 48 if (table == NULL) { 49 49 return NULL; 50 50 } 51 52 51 // Create the linked list 53 myLinkList = psListAlloc( NULL);52 myLinkList = psListAlloc(NULL); 54 53 55 54 // Loop through every bucket in the hash table. If that bucket is not 56 55 // NULL, then add the bucket's key to the linked list. 57 for ( i = 0;i < table->nbucket;i++) {58 if ( table->buckets[ i ] != NULL) {56 for (i = 0; i < table->nbucket; i++) { 57 if (table->buckets[i] != NULL) { 59 58 // Since a bucket contains a linked list of keys/data, we must 60 59 // step trough each key in that linked list: 61 60 62 ptr = table->buckets[ i];63 while ( ptr != NULL) {64 psListAdd( myLinkList, ptr->key, PS_LIST_HEAD);61 ptr = table->buckets[i]; 62 while (ptr != NULL) { 63 psListAdd(myLinkList, ptr->key, PS_LIST_HEAD); 65 64 ptr = ptr->next; 66 65 } … … 69 68 70 69 // Return the linked list 71 return ( myLinkList ); 72 } 73 74 70 return (myLinkList); 71 } 75 72 76 73 /****************************************************************************** … … 84 81 the new hash bucket. 85 82 *****************************************************************************/ 86 static psHashBucket *hashBucketAlloc( const char *key, 87 void *data, 88 psHashBucket *next ) 89 { 90 if ( key == NULL ) { 91 psAbort( __func__, "psHashBucket() called with NULL key." ); 92 } 93 83 static psHashBucket *hashBucketAlloc(const char *key, void *data, psHashBucket * next) 84 { 85 if (key == NULL) { 86 psAbort(__func__, "psHashBucket() called with NULL key."); 87 } 94 88 // Allocate memory for the new hash bucket. 95 psHashBucket *bucket = psAlloc( sizeof( psHashBucket ) ); 96 p_psMemSetDeallocator( bucket, ( psFreeFcn ) hashBucketFree ); 89 psHashBucket *bucket = psAlloc(sizeof(psHashBucket)); 90 91 p_psMemSetDeallocator(bucket, (psFreeFcn) hashBucketFree); 97 92 98 93 // Initialize the bucket. 99 bucket->key = psStringCopy( key);100 101 if ( data == NULL) {94 bucket->key = psStringCopy(key); 95 96 if (data == NULL) { 102 97 // NOTE: Should we flag a warning message? 103 98 bucket->data = NULL; 104 99 } else { 105 bucket->data = psMemIncrRefCounter( data);100 bucket->data = psMemIncrRefCounter(data); 106 101 } 107 102 … … 110 105 return bucket; 111 106 } 112 113 107 114 108 /****************************************************************************** … … 120 114 NONE 121 115 *****************************************************************************/ 122 static void hashBucketFree( psHashBucket *bucket ) 123 { 124 if ( bucket == NULL ) { 125 return ; 126 } 127 116 static void hashBucketFree(psHashBucket * bucket) 117 { 118 if (bucket == NULL) { 119 return; 120 } 128 121 // A bucket is actually a linked list of buckets. We recursively step 129 122 // through that linked list, free each bucket. 130 psFree( bucket->next ); 131 132 psFree( bucket->key ); 133 134 psFree( bucket->data ); 135 } 136 123 psFree(bucket->next); 124 125 psFree(bucket->key); 126 127 psFree(bucket->data); 128 } 137 129 138 130 /****************************************************************************** … … 144 136 The new hash table. 145 137 *****************************************************************************/ 146 psHash *psHashAlloc( int nbucket ) // initial number of buckets 147 { 148 int i = 0; // loop index variable 138 psHash *psHashAlloc(int nbucket) // initial number of buckets 139 { 140 int i = 0; // loop index variable 141 149 142 // Create the new hash table. 150 psHash *table = psAlloc( sizeof( psHash ) ); 151 p_psMemSetDeallocator( table, ( psFreeFcn ) hashFree ); 143 psHash *table = psAlloc(sizeof(psHash)); 144 145 p_psMemSetDeallocator(table, (psFreeFcn) hashFree); 152 146 153 147 // Allocate memory for the buckets. 154 table->buckets = psAlloc( nbucket * sizeof( psHashBucket * ));148 table->buckets = psAlloc(nbucket * sizeof(psHashBucket *)); 155 149 table->nbucket = nbucket; 156 150 157 psTrace( "utils.hash", 1, "Creating %d-element hash table\n", nbucket);151 psTrace("utils.hash", 1, "Creating %d-element hash table\n", nbucket); 158 152 159 153 // Initialize all buckets to NULL. 160 for ( i = 0; i < nbucket; i++)154 for (i = 0; i < nbucket; i++) 161 155 { 162 table->buckets[ i] = NULL;156 table->buckets[i] = NULL; 163 157 } 164 158 … … 166 160 return table; 167 161 } 168 169 170 162 171 163 /****************************************************************************** … … 179 171 NONE 180 172 *****************************************************************************/ 181 static void hashFree( psHash *table ) 182 { 183 int i = 0; // Loop index variable. 184 185 if ( table == NULL ) { 186 return ; 187 } 188 173 static void hashFree(psHash * table) 174 { 175 int i = 0; // Loop index variable. 176 177 if (table == NULL) { 178 return; 179 } 189 180 // Loop through each bucket in the hash table. If that bucket is not 190 181 // NULL, then free the bucket via a function call to hashBucketFree(); 191 for ( i = 0; i < table->nbucket; i++) {182 for (i = 0; i < table->nbucket; i++) { 192 183 193 184 // A bucket is composed of a linked list of buckets. 194 if ( table->buckets[ i ] != NULL) {195 psFree( table->buckets[ i ]);185 if (table->buckets[i] != NULL) { 186 psFree(table->buckets[i]); 196 187 } 197 188 } 198 189 199 190 // Free the bucket structure, then the hash table. 200 psFree( table->buckets);191 psFree(table->buckets); 201 192 } 202 193 … … 220 211 there is little common code between those functions. 221 212 *****************************************************************************/ 222 static void *doHashWork( psHash *table, const char *key, void *data, bool remove213 static void *doHashWork(psHash * table, const char *key, void *data, bool remove 223 214 ) 224 215 { 225 long int hash = 1; // This will contain an integer value 216 long int hash = 1; // This will contain an integer value 217 226 218 // "hashed" from the key. 227 char *tmpchar = NULL; // Used in computing the hash function. 228 psHashBucket *ptr = NULL; // Used to retrieve the hash bucket. 229 psHashBucket *optr = NULL; // "original pointer": used to step 219 char *tmpchar = NULL; // Used in computing the hash function. 220 psHashBucket *ptr = NULL; // Used to retrieve the hash bucket. 221 psHashBucket *optr = NULL; // "original pointer": used to step 222 230 223 // thru the linked list for a bucket. 231 224 … … 233 226 // function, but I'm checking it anyway since future coders might change 234 227 // the way this procedure is called. 235 if ( ( table == NULL ) || ( key == NULL ) ) { 236 237 psAbort( __func__, "psHashRemove() called with NULL key or table." ); 238 } 239 228 if ((table == NULL) || (key == NULL)) { 229 230 psAbort(__func__, "psHashRemove() called with NULL key or table."); 231 } 240 232 // NOTE: This is the originally supplied hash function. 241 // for (int i = 0, len = strlen(key); i < len; i++) {242 // hash = (hash << 1) ^ key[i];243 // }244 // hash &= (table->nbucket - 1);233 // for (int i = 0, len = strlen(key); i < len; i++) { 234 // hash = (hash << 1) ^ key[i]; 235 // } 236 // hash &= (table->nbucket - 1); 245 237 246 238 // This hash algorithm is from Sedgewick. NOTE: must reread to ensure that 247 239 // the size of the hash table is not required to be a prime number. 248 tmpchar = ( char * )key;249 for ( hash = 0; *tmpchar != '\0'; tmpchar++) {250 hash = ( 64 * hash + *tmpchar ) % ( table->nbucket);240 tmpchar = (char *)key; 241 for (hash = 0; *tmpchar != '\0'; tmpchar++) { 242 hash = (64 * hash + *tmpchar) % (table->nbucket); 251 243 } 252 244 253 245 // NOTE: This should not be necessary, but for now, I'm checking bounds 254 246 // anyway. 255 if ( ( hash < 0 ) || ( hash >= table->nbucket ) ) { 256 psAbort( __func__, "Internal hash function out of range (%d)", hash ); 257 } 258 247 if ((hash < 0) || (hash >= table->nbucket)) { 248 psAbort(__func__, "Internal hash function out of range (%d)", hash); 249 } 259 250 // ptr will have the correct hash bucket. 260 ptr = table->buckets[ hash];251 ptr = table->buckets[hash]; 261 252 262 253 // We know the correct hash bucket, now we need to know what to do. … … 264 255 // or a remove operation on the hash table. 265 256 266 if ( data == NULL ) { 267 if ( remove 268 ) { 269 // We search through the linked list for this bucket in 270 // the hash table and look for an entry for this key. 271 257 if (data == NULL) { 258 if (remove 259 ) { 260 // We search through the linked list for this bucket in 261 // the hash table and look for an entry for this key. 262 263 optr = ptr; 264 while (ptr != NULL) { 265 // Dtermine if this entry holds the correct key. 266 if (strcmp(key, ptr->key) == 0) { 267 // The following lines of code are fairly standard ways 268 // of removing an item from a single-linked list. 269 270 void *data = ptr->data; 271 272 optr->next = ptr->next; 273 if (ptr == table->buckets[hash]) { 274 table->buckets[hash] = ptr->next; 275 } 276 277 psFree(ptr); 278 279 // By definition, the data associated with that key 280 // must be returned, not freed. 281 return data; 282 } 272 283 optr = ptr; 273 while ( ptr != NULL ) { 274 // Dtermine if this entry holds the correct key. 275 if ( strcmp( key, ptr->key ) == 0 ) { 276 // The following lines of code are fairly standard ways 277 // of removing an item from a single-linked list. 278 279 void * data = ptr->data; 280 optr->next = ptr->next; 281 if ( ptr == table->buckets[ hash ] ) { 282 table->buckets[ hash ] = ptr->next; 283 } 284 285 psFree( ptr ); 286 287 // By definition, the data associated with that key 288 // must be returned, not freed. 289 return data; 290 } 291 optr = ptr; 292 ptr = ptr->next; 293 } 294 return NULL; // not in hash 284 ptr = ptr->next; 295 285 } 286 return NULL; // not in hash 287 } 296 288 else { 297 289 // If we get here, then a retrieve operation is requested. So, 298 290 // we step trough the linked list at this bucket, and return the 299 291 // data once we find it, or return NULL if we don't. 300 while ( ptr != NULL) {301 if ( strcmp( key, ptr->key ) == 0) {292 while (ptr != NULL) { 293 if (strcmp(key, ptr->key) == 0) { 302 294 return ptr->data; 303 295 } 304 296 ptr = ptr->next; 305 297 } 306 return NULL; // not in hash298 return NULL; // not in hash 307 299 } 308 300 } else { … … 312 304 // the hash table and look for a duplicate entry for this key. 313 305 314 while ( ptr != NULL) {315 if ( strcmp( key, ptr->key ) == 0) {306 while (ptr != NULL) { 307 if (strcmp(key, ptr->key) == 0) { 316 308 // We have found this key in the hash table. 317 309 318 psTrace( "utils.hash.insert", 3, "Replacing data for %s\n", 319 key ); 310 psTrace("utils.hash.insert", 3, "Replacing data for %s\n", key); 320 311 321 312 // NOTE: I have changed this behavior from the originally … … 323 314 // the new data was not inserted into the hash table. 324 315 325 psFree( ptr->data);326 327 ptr->data = psMemIncrRefCounter( data);316 psFree(ptr->data); 317 318 ptr->data = psMemIncrRefCounter(data); 328 319 return data; 329 320 } … … 333 324 // table. So, we insert this data at the head of that linked list. 334 325 335 table->buckets[ hash ] = hashBucketAlloc( key, 336 data, 337 table->buckets[ hash ] ); 326 table->buckets[hash] = hashBucketAlloc(key, data, table->buckets[hash]); 338 327 return data; 339 328 } … … 351 340 boolean value defining success or failure 352 341 *****************************************************************************/ 353 bool psHashAdd( psHash *table, const char *key, void *data)354 { 355 if ( table == NULL) {356 psAbort( __func__, "psHashInsert() called with NULL hash table.");357 } 358 if ( key == NULL) {359 psAbort( __func__, "psHashInsert() called with NULL key.");360 } 361 if ( data == NULL) {362 psAbort( __func__, "psHashLookup() called with NULL data.");363 } 364 365 return ( doHashWork( table, key, data, 0 ) != NULL);342 bool psHashAdd(psHash * table, const char *key, void *data) 343 { 344 if (table == NULL) { 345 psAbort(__func__, "psHashInsert() called with NULL hash table."); 346 } 347 if (key == NULL) { 348 psAbort(__func__, "psHashInsert() called with NULL key."); 349 } 350 if (data == NULL) { 351 psAbort(__func__, "psHashLookup() called with NULL data."); 352 } 353 354 return (doHashWork(table, key, data, 0) != NULL); 366 355 } 367 356 … … 377 366 The data associated with that key. 378 367 *****************************************************************************/ 379 void *psHashLookup( psHash *table, // table to lookup key in 380 const char *key ) // key to lookup 381 { 382 if ( table == NULL ) { 383 psAbort( __func__, "psHashLookup() called with NULL hash table." ); 384 } 385 if ( key == NULL ) { 386 psAbort( __func__, "psHashLookup() called with NULL key." ); 387 } 388 389 390 return doHashWork( table, key, NULL, 0 ); 368 void *psHashLookup(psHash * table, // table to lookup key in 369 const char *key) // key to lookup 370 { 371 if (table == NULL) { 372 psAbort(__func__, "psHashLookup() called with NULL hash table."); 373 } 374 if (key == NULL) { 375 psAbort(__func__, "psHashLookup() called with NULL key."); 376 } 377 378 return doHashWork(table, key, NULL, 0); 391 379 } 392 380 … … 401 389 boolean value defining success or failure 402 390 *****************************************************************************/ 403 bool psHashRemove( psHash *table, const char *key)404 { 405 void * data = NULL;391 bool psHashRemove(psHash * table, const char *key) 392 { 393 void *data = NULL; 406 394 bool retVal = false; 407 395 408 if ( table == NULL) {409 psAbort( __func__, "psHashRemove() called with NULL hash table.");410 } 411 if ( key == NULL) {412 psAbort( __func__, "psHashRemove() called with NULL key.");413 } 414 415 data = doHashWork( table, key, NULL, 1);416 if ( data != NULL) {417 psFree( data);396 if (table == NULL) { 397 psAbort(__func__, "psHashRemove() called with NULL hash table."); 398 } 399 if (key == NULL) { 400 psAbort(__func__, "psHashRemove() called with NULL key."); 401 } 402 403 data = doHashWork(table, key, NULL, 1); 404 if (data != NULL) { 405 psFree(data); 418 406 retVal = true; 419 407 } else { -
trunk/psLib/src/sysUtils/psHash.h
r1406 r1407 1 1 2 /** @file psHash.h 2 3 * @brief Contains support for basic hashing functions. … … 10 11 * @author George Gusciora, MHPCC 11 12 * 12 * @version $Revision: 1.1 8$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.19 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 #if !defined(PS_HASH_H) 18 # define PS_HASH_H19 # define PS_HASH_H 19 20 20 21 /** \addtogroup HashTable 21 22 * \{ 22 23 */ 23 # include<stdbool.h>24 # include<stdbool.h> 24 25 25 # include "psList.h"26 # include "psList.h" 26 27 27 28 /** A bucket that holds an item of data. */ 28 29 typedef struct psHashBucket 29 30 { 30 char *key; ///< key for this item of data31 void *data; ///< the data itself32 struct psHashBucket *next; ///< list of other possible keys31 char *key; // /< key for this item of data 32 void *data; // /< the data itself 33 struct psHashBucket *next; // /< list of other possible keys 33 34 } 34 35 psHashBucket; 35 36 36 37 //typedef struct HashTable psHash; ///< Opaque type for a hash table 38 37 39 /** The hash-table itself. */ 38 40 typedef struct psHash 39 41 { 40 int nbucket; ///< Number of buckets in hash table.41 psHashBucket **buckets; ///< The bucket data.42 int nbucket; // /< Number of buckets in hash table. 43 psHashBucket **buckets; // /< The bucket data. 42 44 } 43 45 psHash; 44 46 45 47 /// Allocate hash buckets in table. 46 psHash *psHashAlloc(int nbucket ///< The number of buckets to allocate.48 psHash *psHashAlloc(int nbucket // /< The number of buckets to allocate. 47 49 ); 48 50 49 51 /// Insert entry into table. 50 bool psHashAdd(psHash * table, ///< table to insert in51 const char *key, ///< key to use52 void *data ///< data to insert52 bool psHashAdd(psHash * table, // /< table to insert in 53 const char *key, // /< key to use 54 void *data // /< data to insert 53 55 ); 54 56 55 57 /// Lookup key in table. 56 void *psHashLookup(psHash * table, ///< table to lookup key in57 const char *key ///< key to lookup58 void *psHashLookup(psHash * table, // /< table to lookup key in 59 const char *key // /< key to lookup 58 60 ); 59 61 60 62 /// Remove key from table. 61 bool psHashRemove(psHash * table, ///< table to lookup key in62 const char *key ///< key to lookup63 bool psHashRemove(psHash * table, // /< table to lookup key in 64 const char *key // /< key to lookup 63 65 ); 64 66 65 67 /// List all keys in table. 66 psList *psHashKeyList(psHash * table ///< table to list keys from.68 psList *psHashKeyList(psHash * table // /< table to list keys from. 67 69 ); 68 70 69 /* \} */ // End of DataGroup Functions71 /* \} */// End of DataGroup Functions 70 72 71 73 #endif -
trunk/psLib/src/sysUtils/psLogMsg.c
r1406 r1407 1 1 2 /** @file psLogMsg.c 2 3 * @brief Procedures for logging messages. … … 11 12 * @author George Gusciora, MHPCC 12 13 * 13 * @version $Revision: 1.2 3$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.24 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 44 45 45 46 #define MAX_LOG_LINE_LENGTH 128 46 static FILE * logDest = (FILE*)1;// flag to initialize to stderr before using.47 static int globalLogLevel = PS_LOG_INFO; // log all messages at this or above48 static bool logTime = true; // Flag to include time info49 static bool logHost = true; // Flag to include host info50 static bool logLevel = true; // Flag to include level info51 static bool logName = true; // Flag to include name info52 static bool logMsg = true; // Flag to include message info47 static FILE *logDest = (FILE *) 1; // flag to initialize to stderr before using. 48 static int globalLogLevel = PS_LOG_INFO; // log all messages at this or above 49 static bool logTime = true; // Flag to include time info 50 static bool logHost = true; // Flag to include host info 51 static bool logLevel = true; // Flag to include level info 52 static bool logName = true; // Flag to include name info 53 static bool logMsg = true; // Flag to include message info 53 54 54 55 /***************************************************************************** … … 67 68 68 69 if ((level < MIN_LOG_LEVEL) || (level > MAX_LOG_LEVEL)) { 69 psLogMsg("logmsg", PS_LOG_WARN, 70 "Attempt to set invalid logMsg level: %d", level); 70 psLogMsg("logmsg", PS_LOG_WARN, "Attempt to set invalid logMsg level: %d", level); 71 71 level = (level < MIN_LOG_LEVEL) ? MIN_LOG_LEVEL : MAX_LOG_LEVEL; 72 72 } 73 74 73 // Set new global log level 75 74 globalLogLevel = level; … … 78 77 return oldLevel; 79 78 } 80 81 79 82 80 /***************************************************************************** … … 91 89 An integer specifying the old log destination. 92 90 *****************************************************************************/ 93 int psLogSetDestination(const char *dest)91 int psLogSetDestination(const char *dest) 94 92 { 95 93 char protocol[5]; … … 97 95 98 96 // if logDest has not been initialized, do so before using it 99 if (logDest ==(FILE*)1) {97 if (logDest == (FILE *) 1) { 100 98 logDest = stderr; 101 99 } 102 100 103 if (dest == NULL || strcmp(dest, "none")==0) {101 if (dest == NULL || strcmp(dest, "none") == 0) { 104 102 if (logDest != NULL && logDest != stderr && logDest != stdout) { 105 103 fclose(logDest); … … 109 107 } 110 108 111 if (sscanf(dest, "%4s:%256s",protocol,location) < 2) {112 psError(__func__, "The specified destination, %s, is malformed.", dest);109 if (sscanf(dest, "%4s:%256s", protocol, location) < 2) { 110 psError(__func__, "The specified destination, %s, is malformed.", dest); 113 111 return 1; 114 112 } 115 113 116 if (strcmp(protocol, "dest") == 0) {117 if (strcmp(location, "stderr") == 0) {114 if (strcmp(protocol, "dest") == 0) { 115 if (strcmp(location, "stderr") == 0) { 118 116 if (logDest != NULL && logDest != stderr && logDest != stdout) { 119 117 fclose(logDest); … … 122 120 return 0; 123 121 } 124 if (strcmp(location, "stdout") == 0) {122 if (strcmp(location, "stdout") == 0) { 125 123 if (logDest != NULL && logDest != stderr && logDest != stdout) { 126 124 fclose(logDest); … … 129 127 return 0; 130 128 } 131 psError(__func__, "The location, %s, for protocol 'dest' is invalid.",location);129 psError(__func__, "The location, %s, for protocol 'dest' is invalid.", location); 132 130 return 1; 133 } else 134 if (strcmp(protocol,"file") == 0) {135 FILE* file = fopen(location,"w"); 136 if (file == NULL) {137 psError(__func__,"Could not open file '%s' for output.",location);138 return 1;139 }140 if (logDest != NULL && logDest != stderr && logDest != stdout) {141 fclose(logDest);142 }143 logDest = file;144 return 0;145 }146 147 psError(__func__, "Do not know how to handle the protocol '%s'.",protocol);131 } else if (strcmp(protocol, "file") == 0) { 132 FILE *file = fopen(location, "w"); 133 134 if (file == NULL) { 135 psError(__func__, "Could not open file '%s' for output.", location); 136 return 1; 137 } 138 if (logDest != NULL && logDest != stderr && logDest != stdout) { 139 fclose(logDest); 140 } 141 logDest = file; 142 return 0; 143 } 144 145 psError(__func__, "Do not know how to handle the protocol '%s'.", protocol); 148 146 return 1; 149 147 } … … 181 179 fmt = "THLNM"; 182 180 } 183 184 181 // Step through each character in the format string. For each letter 185 182 // in that string, set/unset the appropriate logging. … … 214 211 215 212 if (!logMsg) { 216 psTrace("utils.logMsg", 1, 217 "You must at least log error messages (You chose \"%s\")", 218 fmt); 219 } 220 } 221 222 223 224 #if !defined(HOST_NAME_MAX) // should be in limits.h 225 # define HOST_NAME_MAX 256 213 psTrace("utils.logMsg", 1, "You must at least log error messages (You chose \"%s\")", fmt); 214 } 215 } 216 217 #if !defined(HOST_NAME_MAX) // should be in limits.h 218 # define HOST_NAME_MAX 256 226 219 #endif 220 227 221 /***************************************************************************** 228 222 psVLogMsg(): This routine sends the message, which is a printf style … … 239 233 NULL. 240 234 *****************************************************************************/ 241 void psLogMsgV(const char *name, 242 int level, 243 const char *fmt, 244 va_list ap) 245 { 246 static int first = 1; // Flag for calling gethostname() 235 void psLogMsgV(const char *name, int level, const char *fmt, va_list ap) 236 { 237 static int first = 1; // Flag for calling gethostname() 247 238 static char hostname[HOST_NAME_MAX + 1]; 239 248 240 // Buffer for hostname. 249 char clevel =0;// letter-name for level250 char head[MAX_LOG_LINE_LENGTH +2];// the added two are for the ending | and \0251 char *head_ptr = head; // where we've got to in head241 char clevel = 0; // letter-name for level 242 char head[MAX_LOG_LINE_LENGTH + 2]; // the added two are for the ending | and \0 243 char *head_ptr = head; // where we've got to in head 252 244 int maxLength = MAX_LOG_LINE_LENGTH; 253 time_t clock = time(NULL); // The current time.245 time_t clock = time(NULL); // The current time. 254 246 struct tm *utc = gmtime(&clock); // The current gm time. 255 247 256 248 // if logDest has not been initialized, do so before using it 257 if (logDest ==(FILE*)1) {249 if (logDest == (FILE *) 1) { 258 250 logDest = stderr; 259 251 } 260 261 252 // If logging is off, or if the level is too high, return immediately. 262 253 if ((level > globalLogLevel) || (logDest == NULL)) { 263 254 return; 264 255 } 265 266 256 // If I have not been here yet, determine my hostname and save it. 267 257 if (first) { … … 297 287 298 288 default: 299 psTrace("utils.logMsg", 2, "Invalid logMsg level: %d (%s)\n", 300 level, fmt); 289 psTrace("utils.logMsg", 2, "Invalid logMsg level: %d (%s)\n", level, fmt); 301 290 level = (level < 0) ? 0 : 9; 302 291 break; … … 307 296 maxLength -= snprintf(head_ptr, maxLength, "%4d:%02d:%02d %02d:%02d:%02dZ", 308 297 utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday, 309 utc->tm_hour, utc->tm_min, utc->tm_sec) -1;298 utc->tm_hour, utc->tm_min, utc->tm_sec) - 1; 310 299 head_ptr += strlen(head_ptr); 311 300 } … … 336 325 if (head_ptr > head) { 337 326 *head_ptr++ = '|'; 338 } else 339 if (!logMsg) { // no output desired 340 return; 341 } 327 } else if (!logMsg) { // no output desired 328 return; 329 } 342 330 *head_ptr = '\0'; 343 331 … … 352 340 } 353 341 } 354 355 342 356 343 /***************************************************************************** … … 369 356 NULL 370 357 *****************************************************************************/ 371 void psLogMsg(const char *name, 372 int level, 373 const char *fmt, 374 ...) 358 void psLogMsg(const char *name, int level, const char *fmt, ...) 375 359 { 376 360 va_list ap; -
trunk/psLib/src/sysUtils/psLogMsg.h
r1406 r1407 1 1 2 /** @file psLogMsg.h 2 3 * @brief Procedures for logging messages. … … 11 12 * @author George Gusciora, MHPCC 12 13 * 13 * @version $Revision: 1.1 2$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.13 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 17 18 */ 18 19 #if !defined(PS_LOG_MSG_H) 19 # define PS_LOG_MSG_H20 # include <stdarg.h>20 # define PS_LOG_MSG_H 21 # include <stdarg.h> 21 22 22 23 /** @addtogroup LogTrace … … 29 30 /// In future versions, this procedure will take a character string as an 30 31 /// argument which can specify more general log destinations. 31 int psLogSetDestination(const char * dest ///< Specifies where to send messages.32 int psLogSetDestination(const char *dest // /< Specifies where to send messages. 32 33 ); 33 34 34 35 35 /// This procedure sets the message level for future log messages. Subsequent … … 38 38 /// Ie. higher values set by this procedure will cause more log messages to 39 39 /// be displayed. 40 int psLogSetLevel(int level ///< Specifies the system log level40 int psLogSetLevel(int level // /< Specifies the system log level 41 41 ); 42 43 42 44 43 /// This procedure sets the log format for future log messages. The argument … … 47 46 /// Deleting a letter from the string will cause the associated information 48 47 /// to not be logged. 49 void psLogSetFormat(const char *fmt ///< Specifies the system log format48 void psLogSetFormat(const char *fmt // /< Specifies the system log format 50 49 ); 51 52 50 53 51 /// This procedure logs a message to the destination set by a prior … … 55 53 /// specified by a prior call to psLogSetLevel(). The message is specified 56 54 /// with a printf-stype string an arguments. 57 void psLogMsg(const char *name, ///< name of the log source58 int myLevel, ///< severity level of this log message59 const char *fmt, ... ///< printf-style format command55 void psLogMsg(const char *name, // /< name of the log source 56 int myLevel, // /< severity level of this log message 57 const char *fmt, ... // /< printf-style format command 60 58 ); 61 62 59 63 60 /// This procedure is functionally equivalent to psLogMsg(), except that 64 61 /// it takes a va_list as the message parameter, not a printf-style string. 65 void psLogMsgV(const char *name, ///< name of the log source66 int myLevel, ///< severity level of this log message67 const char *fmt, ///< printf-style format command68 va_list ap ///< varargs argument list62 void psLogMsgV(const char *name, // /< name of the log source 63 int myLevel, // /< severity level of this log message 64 const char *fmt, // /< printf-style format command 65 va_list ap // /< varargs argument list 69 66 ); 70 67 … … 74 71 PS_LOG_ERROR, 75 72 PS_LOG_WARN, 76 PS_LOG_INFO }; 73 PS_LOG_INFO 74 }; 77 75 78 76 ///< Destinations for log messages … … 80 78 PS_LOG_NONE, 81 79 PS_LOG_TO_STDERR, 82 PS_LOG_TO_STDOUT }; 80 PS_LOG_TO_STDOUT 81 }; 83 82 84 83 /// @} -
trunk/psLib/src/sysUtils/psMemory.c
r1406 r1407 1 1 2 /** @file psMemory.c 2 3 * … … 8 9 * @author Robert Lupton, Princeton University 9 10 * 10 * @version $Revision: 1.3 2$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.33 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 14 15 */ 15 16 16 #define PS_ALLOW_MALLOC // we're allowed to call malloc()17 #define PS_ALLOW_MALLOC // we're allowed to call malloc() 17 18 18 19 #include <stdlib.h> … … 26 27 #include "psLogMsg.h" 27 28 28 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header29 30 #define P_PS_LARGE_BLOCK_SIZE 65536 // size where under, we try to recycle31 32 static int checkMemBlock( const psMemBlock *m, const char* funcName);29 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header 30 31 #define P_PS_LARGE_BLOCK_SIZE 65536 // size where under, we try to recycle 32 33 static int checkMemBlock(const psMemBlock * m, const char *funcName); 33 34 static psMemBlock *lastMemBlockAllocated = NULL; 34 35 static pthread_mutex_t memBlockListMutex = PTHREAD_MUTEX_INITIALIZER; … … 38 39 39 40 static int recycleBins = 13; 40 static int recycleBinSize[ 14 ] =41 {42 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE43 }; 41 static int recycleBinSize[14] = { 42 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE 43 }; 44 44 45 // N.B. recycleBinSize should be terminated by P_PS_LARGE_BLOCK_SIZE (simplifies search loops) 45 static psMemBlock* recycleMemBlockList[ 13 ] = 46 { 47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 48 }; 46 static psMemBlock *recycleMemBlockList[13] = { 47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 48 }; 49 49 50 50 #ifdef PS_MEM_DEBUG 51 static psMemBlock * deadBlockList;// a place to put dead memBlocks in debug mode.51 static psMemBlock *deadBlockList; // a place to put dead memBlocks in debug mode. 52 52 #endif 53 53 54 /** 54 55 * Unique ID for allocated blocks … … 59 60 * Default memExhausted callback. 60 61 */ 61 static void *memExhaustedCallbackDefault( size_t size)62 { 63 void * ptr = NULL;64 65 pthread_mutex_lock( &recycleMemBlockListMutex);62 static void *memExhaustedCallbackDefault(size_t size) 63 { 64 void *ptr = NULL; 65 66 pthread_mutex_lock(&recycleMemBlockListMutex); 66 67 int level = recycleBins - 1; 67 while ( level >= 0 && ptr == NULL ) { 68 while ( recycleMemBlockList[ level ] != NULL && ptr == NULL ) { 69 psMemBlock * old = recycleMemBlockList[ level ]; 70 recycleMemBlockList[ level ] = recycleMemBlockList[ level ] ->nextBlock; 71 free( old ); 72 ptr = malloc( size ); 68 69 while (level >= 0 && ptr == NULL) { 70 while (recycleMemBlockList[level] != NULL && ptr == NULL) { 71 psMemBlock *old = recycleMemBlockList[level]; 72 73 recycleMemBlockList[level] = recycleMemBlockList[level]->nextBlock; 74 free(old); 75 ptr = malloc(size); 73 76 } 74 77 level--; 75 78 } 76 pthread_mutex_unlock( &recycleMemBlockListMutex);79 pthread_mutex_unlock(&recycleMemBlockListMutex); 77 80 78 81 return ptr; … … 81 84 static psMemExhaustedCallback memExhaustedCallback = memExhaustedCallbackDefault; 82 85 83 psMemExhaustedCallback psMemExhaustedCallbackSet( psMemExhaustedCallback func)86 psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func) 84 87 { 85 88 psMemExhaustedCallback old = memExhaustedCallback; 86 89 87 if ( func != NULL) {90 if (func != NULL) { 88 91 memExhaustedCallback = func; 89 92 } else { … … 94 97 } 95 98 96 static void memProblemCallbackDefault( const psMemBlock *ptr, 97 const char *file, int lineno ) 98 { 99 if ( ptr->refCounter < 1 ) { 100 psError( __func__, 101 "Block %ld allocated at %s:%d freed more than once at %s:%d\n", 102 ptr->id, ptr->file, ptr->lineno, file, lineno ); 103 } 104 105 if ( lineno > 0 ) { 106 psAbort( __func__, "Detected a problem in the memory system at %s:%d", file, lineno ); 99 static void memProblemCallbackDefault(const psMemBlock * ptr, const char *file, int lineno) 100 { 101 if (ptr->refCounter < 1) { 102 psError(__func__, 103 "Block %ld allocated at %s:%d freed more than once at %s:%d\n", 104 ptr->id, ptr->file, ptr->lineno, file, lineno); 105 } 106 107 if (lineno > 0) { 108 psAbort(__func__, "Detected a problem in the memory system at %s:%d", file, lineno); 107 109 } 108 110 } 109 111 static psMemProblemCallback memProblemCallback = memProblemCallbackDefault; 110 112 111 psMemProblemCallback psMemProblemCallbackSet( psMemProblemCallback func)113 psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func) 112 114 { 113 115 psMemProblemCallback old = memProblemCallback; 114 116 115 if ( func != NULL) {117 if (func != NULL) { 116 118 memProblemCallback = func; 117 119 } else { … … 121 123 return old; 122 124 } 125 123 126 /* 124 127 * And now the I-want-to-be-informed callbacks … … 126 129 * Call the callbacks when these IDs are allocated/freed 127 130 */ 128 psMemoryId p_psMemAllocateID = 0; // notify user this block is allocated131 psMemoryId p_psMemAllocateID = 0; // notify user this block is allocated 129 132 psMemoryId p_psMemFreeID = 0; // notify user this block is freed 130 133 131 psMemoryId psMemAllocateCallbackSetID( psMemoryId id)134 psMemoryId psMemAllocateCallbackSetID(psMemoryId id) 132 135 { 133 136 psMemoryId old = p_psMemAllocateID; 137 134 138 p_psMemAllocateID = id; 135 139 … … 137 141 } 138 142 139 psMemoryId psMemFreeCallbackSetID( psMemoryId id)143 psMemoryId psMemFreeCallbackSetID(psMemoryId id) 140 144 { 141 145 psMemoryId old = p_psMemFreeID; 146 142 147 p_psMemFreeID = id; 143 148 … … 151 156 * isn't resignalled) 152 157 */ 153 static psMemoryId memAllocateCallbackDefault( const psMemBlock *ptr)154 { 155 static psMemoryId incr = 0; // "p_psMemAllocateID += incr"158 static psMemoryId memAllocateCallbackDefault(const psMemBlock * ptr) 159 { 160 static psMemoryId incr = 0; // "p_psMemAllocateID += incr" 156 161 157 162 return incr; 158 163 } 159 164 160 static psMemoryId memFreeCallbackDefault( const psMemBlock *ptr)161 { 162 static psMemoryId incr = 0; // "p_psMemFreeID += incr"165 static psMemoryId memFreeCallbackDefault(const psMemBlock * ptr) 166 { 167 static psMemoryId incr = 0; // "p_psMemFreeID += incr" 163 168 164 169 return incr; … … 171 176 static psMemFreeCallback memFreeCallback = memFreeCallbackDefault; 172 177 173 psMemAllocateCallback psMemAllocateCallbackSet( psMemAllocateCallback func)178 psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func) 174 179 { 175 180 psMemFreeCallback old = memAllocateCallback; 176 181 177 if ( func != NULL) {182 if (func != NULL) { 178 183 memAllocateCallback = func; 179 184 } else { … … 184 189 } 185 190 186 psMemFreeCallback psMemFreeCallbackSet( psMemFreeCallback func)191 psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func) 187 192 { 188 193 psMemFreeCallback old = memFreeCallback; 189 194 190 if ( func != NULL) {195 if (func != NULL) { 191 196 memFreeCallback = func; 192 197 } else { … … 200 205 * Return memory ID counter for next block to be allocated 201 206 */ 202 psMemoryId psMemGetId( void)207 psMemoryId psMemGetId(void) 203 208 { 204 209 psMemoryId id; 205 pthread_mutex_lock( &memIdMutex ); 210 211 pthread_mutex_lock(&memIdMutex); 206 212 id = memid + 1; 207 pthread_mutex_unlock( &memIdMutex);213 pthread_mutex_unlock(&memIdMutex); 208 214 209 215 return id; … … 216 222 */ 217 223 218 static int checkMemBlock( const psMemBlock *m, const char* funcName)224 static int checkMemBlock(const psMemBlock * m, const char *funcName) 219 225 { 220 226 // n.b. since this is called by psMemCheckCorruption while the memblock list is mutex locked, 221 227 // we shouldn't call such things as p_psAlloc/p_psFree here. 222 228 223 if ( m == NULL) {224 psError( funcName, "Memory Corruption: NULL memory block found.");229 if (m == NULL) { 230 psError(funcName, "Memory Corruption: NULL memory block found."); 225 231 return 1; 226 232 } 227 233 228 if ( m->refCounter == 0) {234 if (m->refCounter == 0) { 229 235 // using an unreferenced block of memory, are you? 230 psError( __func__, "Memory Corruption: memory block %ld was freed but still used.", 231 m->id ); 236 psError(__func__, "Memory Corruption: memory block %ld was freed but still used.", m->id); 232 237 return 1; 233 238 } 234 239 235 if ( m->startblock != P_PS_MEMMAGIC || m->endblock != P_PS_MEMMAGIC ) { 236 psError( funcName, "Memory Corruption: memory block %ld is corrupted (buffer underflow)", 237 m->id ); 240 if (m->startblock != P_PS_MEMMAGIC || m->endblock != P_PS_MEMMAGIC) { 241 psError(funcName, "Memory Corruption: memory block %ld is corrupted (buffer underflow)", m->id); 238 242 return 1; 239 243 } 240 if ( *( void** ) ( ( int8_t* ) ( m + 1 ) + m->userMemorySize ) != P_PS_MEMMAGIC ) { 241 psError( funcName, "Memory Corruption: memory block %ld is corrupted (buffer overflow)", 242 m->id ); 244 if (*(void **)((int8_t *) (m + 1) + m->userMemorySize) != P_PS_MEMMAGIC) { 245 psError(funcName, "Memory Corruption: memory block %ld is corrupted (buffer overflow)", m->id); 243 246 return 1; 244 247 } … … 247 250 } 248 251 249 int psMemCheckCorruption( bool abort_on_error)250 { 251 int nbad = 0; // number of bad blocks252 int psMemCheckCorruption(bool abort_on_error) 253 { 254 int nbad = 0; // number of bad blocks 252 255 253 256 // get exclusive access to the memBlock list to avoid it changing on us while we use it. 254 pthread_mutex_lock( &memBlockListMutex);255 256 for ( psMemBlock * iter = lastMemBlockAllocated; iter != NULL; iter = iter->nextBlock) {257 if ( checkMemBlock( iter, __func__ )) {257 pthread_mutex_lock(&memBlockListMutex); 258 259 for (psMemBlock * iter = lastMemBlockAllocated; iter != NULL; iter = iter->nextBlock) { 260 if (checkMemBlock(iter, __func__)) { 258 261 nbad++; 259 262 260 memProblemCallback( iter, __func__, __LINE__);261 262 if ( abort_on_error) {263 memProblemCallback(iter, __func__, __LINE__); 264 265 if (abort_on_error) { 263 266 // release the lock on the memblock list 264 pthread_mutex_unlock( &memBlockListMutex);265 psAbort( __func__, "Detected memory corruption");267 pthread_mutex_unlock(&memBlockListMutex); 268 psAbort(__func__, "Detected memory corruption"); 266 269 return nbad; 267 270 } … … 270 273 271 274 // release the lock on the memblock list 272 pthread_mutex_unlock( &memBlockListMutex);275 pthread_mutex_unlock(&memBlockListMutex); 273 276 return nbad; 274 277 } 275 278 276 void *p_psAlloc( size_t size, const char *file, int lineno)277 { 278 279 psMemBlock * ptr = NULL;279 void *p_psAlloc(size_t size, const char *file, int lineno) 280 { 281 282 psMemBlock *ptr = NULL; 280 283 281 284 // memory is of the size I want to bother recycling? 282 if ( size < P_PS_LARGE_BLOCK_SIZE) {285 if (size < P_PS_LARGE_BLOCK_SIZE) { 283 286 // find the bin we need. 284 287 int level = 0; 285 while ( size > recycleBinSize[ level ] ) { 288 289 while (size > recycleBinSize[level]) { 286 290 level++; 287 291 } 288 292 // Are we in one of the bins 289 if ( level < recycleBins) {290 291 size = recycleBinSize[ level]; // round-up size to next sized bin.292 293 pthread_mutex_lock( &recycleMemBlockListMutex);294 295 if ( recycleMemBlockList[ level ] != NULL) {296 ptr = recycleMemBlockList[ level];297 recycleMemBlockList[ level] = ptr->nextBlock;298 if ( recycleMemBlockList[ level ] != NULL) {299 recycleMemBlockList[ level ]->previousBlock = NULL;293 if (level < recycleBins) { 294 295 size = recycleBinSize[level]; // round-up size to next sized bin. 296 297 pthread_mutex_lock(&recycleMemBlockListMutex); 298 299 if (recycleMemBlockList[level] != NULL) { 300 ptr = recycleMemBlockList[level]; 301 recycleMemBlockList[level] = ptr->nextBlock; 302 if (recycleMemBlockList[level] != NULL) { 303 recycleMemBlockList[level]->previousBlock = NULL; 300 304 } 301 305 size = ptr->userMemorySize; 302 306 } 303 307 304 pthread_mutex_unlock( &recycleMemBlockListMutex ); 305 } 306 } 307 308 if ( ptr == NULL ) { 309 ptr = malloc( sizeof( psMemBlock ) + size + sizeof( void* ) ); 310 311 if ( ptr == NULL ) { 312 ptr = memExhaustedCallback( size ); 313 if ( ptr == NULL ) { 314 psAbort( __func__, "Failed to allocate %u bytes at %s:%d", 315 size, file, lineno ); 308 pthread_mutex_unlock(&recycleMemBlockListMutex); 309 } 310 } 311 312 if (ptr == NULL) { 313 ptr = malloc(sizeof(psMemBlock) + size + sizeof(void *)); 314 315 if (ptr == NULL) { 316 ptr = memExhaustedCallback(size); 317 if (ptr == NULL) { 318 psAbort(__func__, "Failed to allocate %u bytes at %s:%d", size, file, lineno); 316 319 } 317 320 } … … 320 323 ptr->endblock = P_PS_MEMMAGIC; 321 324 ptr->userMemorySize = size; 322 pthread_mutex_init( &ptr->refCounterMutex, NULL ); 323 } 324 325 pthread_mutex_init(&ptr->refCounterMutex, NULL); 326 } 325 327 // increment the memory id safely. 326 pthread_mutex_lock( &memBlockListMutex);327 *( psMemoryId*) & ptr->id = ++memid;328 pthread_mutex_unlock( &memBlockListMutex);328 pthread_mutex_lock(&memBlockListMutex); 329 *(psMemoryId *) & ptr->id = ++memid; 330 pthread_mutex_unlock(&memBlockListMutex); 329 331 330 332 ptr->file = file; 331 333 ptr->freeFcn = NULL; 332 *( unsigned int* ) &ptr->lineno = lineno;333 *( void** ) ( ( int8_t* ) ( ptr + 1 ) + size) = P_PS_MEMMAGIC;334 *(unsigned int *)&ptr->lineno = lineno; 335 *(void **)((int8_t *) (ptr + 1) + size) = P_PS_MEMMAGIC; 334 336 ptr->previousBlock = NULL; 335 337 336 ptr->refCounter = 1; // one user so far338 ptr->refCounter = 1; // one user so far 337 339 338 340 // need exclusive access of the memory block list now... 339 pthread_mutex_lock( &memBlockListMutex);341 pthread_mutex_lock(&memBlockListMutex); 340 342 341 343 // insert the new block to the front of the memBlock linked-list 342 344 ptr->nextBlock = lastMemBlockAllocated; 343 if ( ptr->nextBlock != NULL) {345 if (ptr->nextBlock != NULL) { 344 346 ptr->nextBlock->previousBlock = ptr; 345 347 } 346 348 lastMemBlockAllocated = ptr; 347 349 348 pthread_mutex_unlock( &memBlockListMutex ); 349 350 // Did the user ask to be informed about this allocation? 351 if ( ptr->id == p_psMemAllocateID ) { 352 p_psMemAllocateID += memAllocateCallback( ptr ); 353 } 354 350 pthread_mutex_unlock(&memBlockListMutex); 351 352 // Did the user ask to be informed about this allocation? 353 if (ptr->id == p_psMemAllocateID) { 354 p_psMemAllocateID += memAllocateCallback(ptr); 355 } 355 356 // And return the user the memory that they allocated 356 return ptr + 1; // user memory357 } 358 359 void *p_psRealloc( void *vptr, size_t size, const char *file, int lineno)360 { 361 if ( vptr == NULL) {362 return p_psAlloc( size, file, lineno);357 return ptr + 1; // user memory 358 } 359 360 void *p_psRealloc(void *vptr, size_t size, const char *file, int lineno) 361 { 362 if (vptr == NULL) { 363 return p_psAlloc(size, file, lineno); 363 364 } else { 364 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;365 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 365 366 bool isBlockLast = false; 366 367 367 if ( checkMemBlock( ptr, __func__ ) != 0 ) { 368 memProblemCallback( ptr, file, lineno ); 369 psAbort( file, "Realloc detected a memory corruption (id %ld @ %s:%d).", 370 ptr->id, ptr->file, ptr->lineno ); 371 } 372 373 pthread_mutex_lock( &memBlockListMutex ); 374 375 isBlockLast = ( ptr == lastMemBlockAllocated ); 376 377 ptr = ( psMemBlock* ) realloc( ptr, sizeof( psMemBlock ) + size + sizeof( void* ) ); 378 379 if ( ptr == NULL ) { 380 psAbort( __func__, "Failed to reallocate %ld bytes at %s:%d", 381 size, file, lineno ); 368 if (checkMemBlock(ptr, __func__) != 0) { 369 memProblemCallback(ptr, file, lineno); 370 psAbort(file, "Realloc detected a memory corruption (id %ld @ %s:%d).", 371 ptr->id, ptr->file, ptr->lineno); 372 } 373 374 pthread_mutex_lock(&memBlockListMutex); 375 376 isBlockLast = (ptr == lastMemBlockAllocated); 377 378 ptr = (psMemBlock *) realloc(ptr, sizeof(psMemBlock) + size + sizeof(void *)); 379 380 if (ptr == NULL) { 381 psAbort(__func__, "Failed to reallocate %ld bytes at %s:%d", size, file, lineno); 382 382 } 383 383 384 384 ptr->userMemorySize = size; 385 *( void** ) ( ( int8_t* ) ( ptr + 1 ) + size) = P_PS_MEMMAGIC;386 387 if ( isBlockLast) {385 *(void **)((int8_t *) (ptr + 1) + size) = P_PS_MEMMAGIC; 386 387 if (isBlockLast) { 388 388 lastMemBlockAllocated = ptr; 389 389 } 390 391 390 // the block location may have changed, so fix the linked list addresses. 392 if ( ptr->nextBlock != NULL) {391 if (ptr->nextBlock != NULL) { 393 392 ptr->nextBlock->previousBlock = ptr; 394 393 } 395 if ( ptr->previousBlock != NULL) {394 if (ptr->previousBlock != NULL) { 396 395 ptr->previousBlock->nextBlock = ptr; 397 396 } 398 397 399 pthread_mutex_unlock( &memBlockListMutex);400 401 // Did the user ask to be informed about this allocation?402 if ( ptr->id == p_psMemAllocateID) {403 p_psMemAllocateID += memAllocateCallback( ptr);404 } 405 406 return ptr + 1; // usr memory407 } 408 } 409 410 void p_psFree( void *vptr, const char *file, int lineno)411 { 412 ( void ) p_psMemDecrRefCounter( vptr, file, lineno );// this handles the free, if required.398 pthread_mutex_unlock(&memBlockListMutex); 399 400 // Did the user ask to be informed about this allocation? 401 if (ptr->id == p_psMemAllocateID) { 402 p_psMemAllocateID += memAllocateCallback(ptr); 403 } 404 405 return ptr + 1; // usr memory 406 } 407 } 408 409 void p_psFree(void *vptr, const char *file, int lineno) 410 { 411 (void)p_psMemDecrRefCounter(vptr, file, lineno); // this handles the free, if required. 413 412 } 414 413 … … 416 415 * Check for memory leaks. 417 416 */ 418 int psMemCheckLeaks( psMemoryId id0, psMemBlock ***arr, FILE *fd)417 int psMemCheckLeaks(psMemoryId id0, psMemBlock *** arr, FILE * fd) 419 418 { 420 419 int nleak = 0; 421 420 int j = 0; 422 psMemBlock *topBlock = lastMemBlockAllocated;423 424 pthread_mutex_lock( &memBlockListMutex);425 426 for ( psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) {427 if ( ( psMemGetRefCounter( iter + 1 ) > 0 ) && ( iter->id >= id0 )) {421 psMemBlock *topBlock = lastMemBlockAllocated; 422 423 pthread_mutex_lock(&memBlockListMutex); 424 425 for (psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) { 426 if ((psMemGetRefCounter(iter + 1) > 0) && (iter->id >= id0)) { 428 427 nleak++; 429 428 430 if ( fd != NULL) {431 if ( nleak == 1) {432 fprintf( fd, " %20s:line ID\n", "file");429 if (fd != NULL) { 430 if (nleak == 1) { 431 fprintf(fd, " %20s:line ID\n", "file"); 433 432 } 434 433 435 fprintf( fd, " %20s:%-4d %ld\n", iter->file, iter->lineno, iter->id);436 } 437 } 438 } 439 440 pthread_mutex_unlock( &memBlockListMutex);441 442 if ( nleak == 0 || arr == NULL) {434 fprintf(fd, " %20s:%-4d %ld\n", iter->file, iter->lineno, iter->id); 435 } 436 } 437 } 438 439 pthread_mutex_unlock(&memBlockListMutex); 440 441 if (nleak == 0 || arr == NULL) { 443 442 return nleak; 444 443 } 445 444 446 *arr = p_psAlloc( nleak * sizeof( psMemBlock ), __FILE__, __LINE__);447 pthread_mutex_lock( &memBlockListMutex);448 449 for ( psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) {450 if ( ( psMemGetRefCounter( iter + 1 ) > 0 ) && ( iter->id >= id0 )) {451 ( *arr ) [ j++] = iter;452 if ( j == nleak ) {// found them all445 *arr = p_psAlloc(nleak * sizeof(psMemBlock), __FILE__, __LINE__); 446 pthread_mutex_lock(&memBlockListMutex); 447 448 for (psMemBlock * iter = topBlock; iter != NULL; iter = iter->nextBlock) { 449 if ((psMemGetRefCounter(iter + 1) > 0) && (iter->id >= id0)) { 450 (*arr)[j++] = iter; 451 if (j == nleak) { // found them all 453 452 break; 454 453 } … … 456 455 } 457 456 458 pthread_mutex_unlock( &memBlockListMutex);457 pthread_mutex_unlock(&memBlockListMutex); 459 458 460 459 return nleak; … … 465 464 */ 466 465 // return refCounter 467 psReferenceCount psMemGetRefCounter( void *vptr)468 { 469 psMemBlock * ptr;466 psReferenceCount psMemGetRefCounter(void *vptr) 467 { 468 psMemBlock *ptr; 470 469 unsigned int refCount; 471 470 472 if ( vptr == NULL) {471 if (vptr == NULL) { 473 472 return 0; 474 473 } 475 474 476 ptr = ( ( psMemBlock * ) vptr) - 1;477 478 if ( checkMemBlock( ptr, __func__ ) != 0) {479 memProblemCallback( ptr, __func__, __LINE__);480 } 481 482 pthread_mutex_lock( &ptr->refCounterMutex);475 ptr = ((psMemBlock *) vptr) - 1; 476 477 if (checkMemBlock(ptr, __func__) != 0) { 478 memProblemCallback(ptr, __func__, __LINE__); 479 } 480 481 pthread_mutex_lock(&ptr->refCounterMutex); 483 482 refCount = ptr->refCounter; 484 pthread_mutex_unlock( &ptr->refCounterMutex);483 pthread_mutex_unlock(&ptr->refCounterMutex); 485 484 486 485 return refCount; 487 486 } 487 488 488 // increment and return refCounter 489 void * p_psMemIncrRefCounter( void *vptr, const char *file, int lineno)490 { 491 psMemBlock * ptr;492 493 if ( vptr == NULL) {489 void *p_psMemIncrRefCounter(void *vptr, const char *file, int lineno) 490 { 491 psMemBlock *ptr; 492 493 if (vptr == NULL) { 494 494 return vptr; 495 495 } 496 496 497 ptr = ( ( psMemBlock * ) vptr) - 1;498 499 if ( checkMemBlock( ptr, __func__ )) {500 memProblemCallback( ptr, file, lineno);501 } 502 503 pthread_mutex_lock( &ptr->refCounterMutex);497 ptr = ((psMemBlock *) vptr) - 1; 498 499 if (checkMemBlock(ptr, __func__)) { 500 memProblemCallback(ptr, file, lineno); 501 } 502 503 pthread_mutex_lock(&ptr->refCounterMutex); 504 504 ptr->refCounter++; 505 pthread_mutex_unlock( &ptr->refCounterMutex);505 pthread_mutex_unlock(&ptr->refCounterMutex); 506 506 507 507 return vptr; … … 509 509 510 510 // decrement and return refCounter 511 void * p_psMemDecrRefCounter( void *vptr, const char *file, int lineno)512 { 513 if ( vptr == NULL) {511 void *p_psMemDecrRefCounter(void *vptr, const char *file, int lineno) 512 { 513 if (vptr == NULL) { 514 514 return NULL; 515 515 } 516 516 517 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;518 519 if ( checkMemBlock( ptr, __func__ ) != 0) {520 memProblemCallback( ptr, file, lineno);517 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 518 519 if (checkMemBlock(ptr, __func__) != 0) { 520 memProblemCallback(ptr, file, lineno); 521 521 return NULL; 522 522 } 523 523 524 pthread_mutex_lock( &ptr->refCounterMutex);525 526 if ( ptr->refCounter > 1) {527 // / XXX - Probably should have another mutex here.528 ptr->refCounter--; // multiple references, just decrement the count.529 pthread_mutex_unlock( &ptr->refCounterMutex);524 pthread_mutex_lock(&ptr->refCounterMutex); 525 526 if (ptr->refCounter > 1) { 527 // / XXX - Probably should have another mutex here. 528 ptr->refCounter--; // multiple references, just decrement the count. 529 pthread_mutex_unlock(&ptr->refCounterMutex); 530 530 531 531 } else { 532 pthread_mutex_unlock( &ptr->refCounterMutex);532 pthread_mutex_unlock(&ptr->refCounterMutex); 533 533 534 534 // Did the user ask to be informed about this deallocation? 535 if ( ptr->id == p_psMemFreeID) {536 p_psMemFreeID += memFreeCallback( ptr);537 } 538 539 if ( ptr->freeFcn != NULL) {540 ptr->freeFcn( vptr);541 } 542 543 pthread_mutex_lock( &memBlockListMutex);535 if (ptr->id == p_psMemFreeID) { 536 p_psMemFreeID += memFreeCallback(ptr); 537 } 538 539 if (ptr->freeFcn != NULL) { 540 ptr->freeFcn(vptr); 541 } 542 543 pthread_mutex_lock(&memBlockListMutex); 544 544 545 545 // cut the memBlock out of the memBlock list 546 if ( ptr->nextBlock != NULL) {546 if (ptr->nextBlock != NULL) { 547 547 ptr->nextBlock->previousBlock = ptr->previousBlock; 548 548 } 549 if ( ptr->previousBlock != NULL) {549 if (ptr->previousBlock != NULL) { 550 550 ptr->previousBlock->nextBlock = ptr->nextBlock; 551 551 } 552 if ( lastMemBlockAllocated == ptr) {552 if (lastMemBlockAllocated == ptr) { 553 553 lastMemBlockAllocated = ptr->nextBlock; 554 554 } 555 555 556 pthread_mutex_unlock( &memBlockListMutex ); 557 556 pthread_mutex_unlock(&memBlockListMutex); 558 557 559 558 // do we need to recycle? 560 if ( ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) {559 if (ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) { 561 560 562 561 int level = 1; 563 while ( ptr->userMemorySize >= recycleBinSize[ level ] ) { 562 563 while (ptr->userMemorySize >= recycleBinSize[level]) { 564 564 level++; 565 565 } … … 569 569 ptr->previousBlock = NULL; 570 570 571 pthread_mutex_lock( &recycleMemBlockListMutex);572 ptr->nextBlock = recycleMemBlockList[ level];573 if ( recycleMemBlockList[ level ] != NULL) {574 recycleMemBlockList[ level ]->previousBlock = ptr;575 } 576 recycleMemBlockList[ level] = ptr;577 pthread_mutex_unlock( &recycleMemBlockListMutex);571 pthread_mutex_lock(&recycleMemBlockListMutex); 572 ptr->nextBlock = recycleMemBlockList[level]; 573 if (recycleMemBlockList[level] != NULL) { 574 recycleMemBlockList[level]->previousBlock = ptr; 575 } 576 recycleMemBlockList[level] = ptr; 577 pthread_mutex_unlock(&recycleMemBlockListMutex); 578 578 579 579 } else { 580 580 // memory is larger than I want to recycle. 581 581 #ifdef PS_MEM_DEBUG 582 ( void ) p_psRealloc( vptr, 0, file, lineno);582 (void)p_psRealloc(vptr, 0, file, lineno); 583 583 ptr->previousBlock = NULL; 584 584 ptr->nextBlock = deadBlockList; 585 if ( deadBlockList != NULL) {585 if (deadBlockList != NULL) { 586 586 deadBlockList->previous = ptr; 587 587 } … … 589 589 #else 590 590 591 pthread_mutex_destroy( &ptr->refCounterMutex);592 free( ptr);591 pthread_mutex_destroy(&ptr->refCounterMutex); 592 free(ptr); 593 593 #endif 594 594 595 595 } 596 596 597 vptr = NULL; // since we freed it, make sure we return NULL.597 vptr = NULL; // since we freed it, make sure we return NULL. 598 598 } 599 599 … … 601 601 } 602 602 603 void p_psMemSetDeallocator( void* vptr, psFreeFcn freeFcn)604 { 605 if ( vptr == NULL) {606 return ;607 } 608 609 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;610 611 if ( checkMemBlock( ptr, __func__ ) != 0) {612 memProblemCallback( ptr, __func__, __LINE__);603 void p_psMemSetDeallocator(void *vptr, psFreeFcn freeFcn) 604 { 605 if (vptr == NULL) { 606 return; 607 } 608 609 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 610 611 if (checkMemBlock(ptr, __func__) != 0) { 612 memProblemCallback(ptr, __func__, __LINE__); 613 613 } 614 614 … … 616 616 617 617 } 618 psFreeFcn p_psMemGetDeallocator( void* vptr)619 { 620 if ( vptr == NULL) {618 psFreeFcn p_psMemGetDeallocator(void *vptr) 619 { 620 if (vptr == NULL) { 621 621 return NULL; 622 622 } 623 623 624 psMemBlock *ptr = ( ( psMemBlock * ) vptr) - 1;625 626 if ( checkMemBlock( ptr, __func__ ) != 0) {627 memProblemCallback( ptr, __func__, __LINE__);624 psMemBlock *ptr = ((psMemBlock *) vptr) - 1; 625 626 if (checkMemBlock(ptr, __func__) != 0) { 627 memProblemCallback(ptr, __func__, __LINE__); 628 628 } 629 629 -
trunk/psLib/src/sysUtils/psMemory.h
r1406 r1407 1 1 #if !defined(PS_MEMORY_H) 2 #define PS_MEMORY_H 2 # define PS_MEMORY_H 3 3 4 /** @file psMemory.h 4 5 * … … 14 15 * @ingroup MemoryManagement 15 16 * 16 * @version $Revision: 1.2 3$ $Name: not supported by cvs2svn $17 * @date $Date: 2004-08-0 6 22:34:05$17 * @version $Revision: 1.24 $ $Name: not supported by cvs2svn $ 18 * @date $Date: 2004-08-07 00:06:06 $ 18 19 * 19 20 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 20 21 */ 21 22 22 # include <stdio.h>// needed for FILE23 # include <stdbool.h>24 # include <pthread.h>// we need a mutex to make this stuff thread safe.23 # include <stdio.h> // needed for FILE 24 # include <stdbool.h> 25 # include <pthread.h> // we need a mutex to make this stuff thread safe. 25 26 26 27 /** @addtogroup MemoryManagement … … 53 54 54 55 /// typedef for deallocator. 55 typedef void (*psFreeFcn) (void*ptr);56 typedef void (*psFreeFcn) (void *ptr); 56 57 57 58 /** Book-keeping data for storage allocator. … … 62 63 typedef struct psMemBlock 63 64 { 64 const void * startblock; ///< initialised to p_psMEMMAGIC65 struct psMemBlock * previousBlock; ///< previous block in allocation list66 struct psMemBlock * nextBlock; ///< next block allocation list67 psFreeFcn freeFcn; ///< deallocator. If NULL, use generic deallocation.68 size_t userMemorySize; ///< the size of the user-portion of the memory block69 const psMemoryId id; ///< a unique ID for this allocation70 const char * file; ///< set from __FILE__ in e.g. p_psAlloc71 const int lineno; ///< set from __LINE__ in e.g. p_psAlloc72 pthread_mutex_t refCounterMutex; ///< mutex to ensure exclusive access to reference counter73 psReferenceCount refCounter; ///< how many times pointer is referenced74 const void * endblock; ///< initialised to p_psMEMMAGIC65 const void *startblock; // /< initialised to p_psMEMMAGIC 66 struct psMemBlock *previousBlock; // /< previous block in allocation list 67 struct psMemBlock *nextBlock; // /< next block allocation list 68 psFreeFcn freeFcn; // /< deallocator. If NULL, use generic deallocation. 69 size_t userMemorySize; // /< the size of the user-portion of the memory block 70 const psMemoryId id; // /< a unique ID for this allocation 71 const char *file; // /< set from __FILE__ in e.g. p_psAlloc 72 const int lineno; // /< set from __LINE__ in e.g. p_psAlloc 73 pthread_mutex_t refCounterMutex; // /< mutex to ensure exclusive access to reference counter 74 psReferenceCount refCounter; // /< how many times pointer is referenced 75 const void *endblock; // /< initialised to p_psMEMMAGIC 75 76 } 76 77 psMemBlock; … … 81 82 * @ingroup memCallback 82 83 */ 83 typedef psMemoryId (*psMemAllocateCallback)( 84 const psMemBlock *ptr ///< the psMemBlock just allocated 85 ); 84 typedef psMemoryId(*psMemAllocateCallback) (const psMemBlock * ptr // /< the psMemBlock just allocated 85 ); 86 86 87 87 /** prototype of memory free callback used by memory functions … … 90 90 * @ingroup memCallback 91 91 */ 92 typedef psMemoryId (*psMemFreeCallback)( 93 const psMemBlock *ptr ///< the psMemBlock being freed 94 ); 92 typedef psMemoryId(*psMemFreeCallback) (const psMemBlock * ptr // /< the psMemBlock being freed 93 ); 95 94 96 95 /** prototype of a callback used in error conditions … … 101 100 * @ingroup memCallback 102 101 */ 103 typedef void (*psMemProblemCallback) (104 const psMemBlock *ptr, ///< the pointer to the problematic memoryblock.105 const char *file, ///< the file in which the problem originated106 int lineno ///< the line number in which the problem originated107 );102 typedef void (*psMemProblemCallback) (const psMemBlock * ptr, // /< the pointer to the problematic memory 103 // block. 104 const char *file, // /< the file in which the problem originated 105 int lineno // /< the line number in which the problem originated 106 ); 108 107 109 108 /** prototype of a callback function used when memory runs out … … 115 114 * @ingroup memCallback 116 115 */ 117 typedef void *(*psMemExhaustedCallback)( 118 size_t size //< the size of buffer required 119 ); 116 typedef void *(*psMemExhaustedCallback) (size_t size // < the size of buffer required 117 ); 120 118 121 119 /** Memory allocation. This operates much like malloc(), but is guaranteed to return a non-NULL value. … … 124 122 * @see psFree 125 123 */ 126 #ifdef DOXYGEN 127 void* psAlloc( 128 size_t size ///< Size required 129 ); 130 #else 131 void* p_psAlloc( 132 size_t size, ///< Size required 133 const char *file, ///< File of call 134 int lineno ///< Line number of call 135 ); 136 137 void p_psMemSetDeallocator(void* ptr, psFreeFcn freeFcn); 138 psFreeFcn p_psMemGetDeallocator(void* ptr); 124 # ifdef DOXYGEN 125 void *psAlloc(size_t size // /< Size required 126 ); 127 # else 128 void *p_psAlloc(size_t size, // /< Size required 129 const char *file, // /< File of call 130 int lineno // /< Line number of call 131 ); 132 133 void p_psMemSetDeallocator(void *ptr, psFreeFcn freeFcn); 134 psFreeFcn p_psMemGetDeallocator(void *ptr); 139 135 140 136 /// Memory allocation. psAlloc sends file and line number to p_psAlloc. 141 #define psAlloc(size) p_psAlloc(size, __FILE__, __LINE__) 142 #endif 143 137 # define psAlloc(size) p_psAlloc(size, __FILE__, __LINE__) 138 # endif 144 139 145 140 /** Memory re-allocation. This operates much like realloc(), but is guaranteed to return a non-NULL value. … … 148 143 * @see psAlloc, psFree 149 144 */ 150 # ifdef DOXYGEN151 void * psRealloc(void *ptr ///< Pointer to re-allocate152 size_t size, ///< Size required145 # ifdef DOXYGEN 146 void *psRealloc(void *ptr // /< Pointer to re-allocate 147 size_t size, // /< Size required 153 148 ); 154 #else 155 void* p_psRealloc(void *ptr, ///< Pointer to re-allocate 156 size_t size, ///< Size required 157 const char *file, ///< File of call 158 int lineno ///< Line number of call 149 # else 150 void *p_psRealloc(void *ptr, // /< Pointer to re-allocate 151 size_t size, // /< Size required 152 const char *file, // /< File of call 153 int lineno // /< Line number of call 154 ); 155 156 /// Memory re-allocation. psRealloc sends file and line number to p_psRealloc. 157 # define psRealloc(ptr, size) p_psRealloc(ptr, size, __FILE__, __LINE__) 158 159 # endif 160 161 /** Free memory. This operates much like free(). 162 * 163 * @see psAlloc, psRealloc 164 */ 165 # ifdef DOXYGEN 166 void psFree(void *ptr, // /< Pointer to free, if NULL, function returns immediately. 167 ); 168 # else 169 void p_psFree(void *ptr, // /< Pointer to free 170 const char *file, // /< File of call 171 int lineno // /< Line number of call 159 172 ); 160 173 161 /// Memory re-allocation. psRealloc sends file and line number to p_psRealloc.162 #define psRealloc(ptr, size) p_psRealloc(ptr, size, __FILE__, __LINE__)163 164 #endif165 166 167 /** Free memory. This operates much like free().168 *169 * @see psAlloc, psRealloc170 */171 #ifdef DOXYGEN172 void psFree(void *ptr, ///< Pointer to free, if NULL, function returns immediately.173 );174 #else175 void p_psFree(void *ptr, ///< Pointer to free176 const char *file, ///< File of call177 int lineno ///< Line number of call178 );179 180 174 /// Free memory. psFree sends file and line number to p_psFree. 181 # define psFree(size) p_psFree(size, __FILE__, __LINE__)182 183 # endif175 # define psFree(size) p_psFree(size, __FILE__, __LINE__) 176 177 # endif 184 178 185 179 /** Check for memory leaks. This scans for allocated memory buffers not freed with an ID not less than id0. … … 197 191 * @ingroup memTracing 198 192 */ 199 int psMemCheckLeaks( 200 psMemoryId id0, ///< don't list blocks with id < id0 201 psMemBlock ***arr, ///< pointer to array of pointers to leaked blocks, or NULL 202 FILE *fd ///< print list of leaks to fd (or NULL) 203 ); 193 int psMemCheckLeaks(psMemoryId id0, // /< don't list blocks with id < id0 194 psMemBlock *** arr, // /< pointer to array of pointers to leaked blocks, or NULL 195 FILE * fd // /< print list of leaks to fd (or NULL) 196 ); 204 197 205 198 /** Check for memory corruption. Scans all currently allocated memory buffers and checks for corruptions, … … 208 201 * @ingroup memTracing 209 202 */ 210 int psMemCheckCorruption( 211 bool abort_on_error ///< Abort on detecting corruption? 212 ); 203 int psMemCheckCorruption(bool abort_on_error // /< Abort on detecting corruption? 204 ); 213 205 214 206 /** Return reference counter … … 216 208 * @ingroup memRefCount 217 209 */ 218 psReferenceCount psMemGetRefCounter( 219 void *vptr ///< Pointer to get refCounter for 220 ); 210 psReferenceCount psMemGetRefCounter(void *vptr // /< Pointer to get refCounter for 211 ); 221 212 222 213 /** Increment reference counter and return the pointer … … 224 215 * @ingroup memRefCount 225 216 */ 226 #ifdef DOXYGEN 227 void* psMemIncrRefCounter( 228 void *vptr ///< Pointer to increment refCounter, and return 229 ); 230 #else 231 void* p_psMemIncrRefCounter( 232 void *vptr, ///< Pointer to increment refCounter, and return 233 const char *file, ///< File of call 234 int lineno ///< Line number of call 235 ); 236 #define psMemIncrRefCounter(vptr) p_psMemIncrRefCounter(vptr, __FILE__, __LINE__) 237 #endif 217 # ifdef DOXYGEN 218 void *psMemIncrRefCounter(void *vptr // /< Pointer to increment refCounter, and return 219 ); 220 # else 221 void *p_psMemIncrRefCounter(void *vptr, // /< Pointer to increment refCounter, and return 222 const char *file, // /< File of call 223 int lineno // /< Line number of call 224 ); 225 226 # define psMemIncrRefCounter(vptr) p_psMemIncrRefCounter(vptr, __FILE__, __LINE__) 227 # endif 238 228 239 229 /** Decrement reference counter and return the pointer … … 241 231 * @ingroup memRefCount 242 232 */ 243 #ifdef DOXYGEN 244 void* psMemDecrRefCounter( 245 void *vptr ///< Pointer to decrement refCounter, and return 246 ); 247 #else 248 void* p_psMemDecrRefCounter( 249 void *vptr, ///< Pointer to decrement refCounter, and return 250 const char *file, ///< File of call 251 int lineno ///< Line number of call 252 ); 253 #define psMemDecrRefCounter(vptr) p_psMemDecrRefCounter(vptr, __FILE__, __LINE__) 254 #endif 233 # ifdef DOXYGEN 234 void *psMemDecrRefCounter(void *vptr // /< Pointer to decrement refCounter, and return 235 ); 236 # else 237 void *p_psMemDecrRefCounter(void *vptr, // /< Pointer to decrement refCounter, and return 238 const char *file, // /< File of call 239 int lineno // /< Line number of call 240 ); 241 242 # define psMemDecrRefCounter(vptr) p_psMemDecrRefCounter(vptr, __FILE__, __LINE__) 243 # endif 255 244 256 245 /** Set callback for problems 257 246 * @ingroup memCallback 258 247 */ 259 psMemProblemCallback psMemProblemCallbackSet( 260 psMemProblemCallback func ///< Function to run 261 ); 248 psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func // /< Function to run 249 ); 262 250 263 251 /** Set callback for out-of-memory … … 265 253 * @ingroup memCallback 266 254 */ 267 psMemExhaustedCallback psMemExhaustedCallbackSet( 268 psMemExhaustedCallback func ///< Function to run 269 ); 255 psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func // /< Function to run 256 ); 270 257 271 258 /** Set call back for when a particular memory block is allocated … … 273 260 * @ingroup memCallback 274 261 */ 275 psMemAllocateCallback psMemAllocateCallbackSet( 276 psMemAllocateCallback func ///< Function to run 277 ); 262 psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func // /< Function to run 263 ); 278 264 279 265 /** Set call back for when a particular memory block is freed … … 281 267 * @ingroup memCallback 282 268 */ 283 psMemFreeCallback psMemFreeCallbackSet( 284 psMemFreeCallback func ///< Function to run 285 ); 269 psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func // /< Function to run 270 ); 286 271 287 272 /** get next memory ID … … 295 280 * @ingroup memCallback 296 281 */ 297 psMemoryId psMemAllocateCallbackSetID( 298 psMemoryId id ///< ID to set 299 ); 282 psMemoryId psMemAllocateCallbackSetID(psMemoryId id // /< ID to set 283 ); 300 284 301 285 /** set p_psMemFreeID to id … … 303 287 * @ingroup memCallback 304 288 */ 305 psMemoryId psMemFreeCallbackSetID( 306 psMemoryId id ///< ID to set 307 ); 289 psMemoryId psMemFreeCallbackSetID(psMemoryId id // /< ID to set 290 ); 308 291 309 292 //@} End of Memory Management Functions 310 293 311 # ifndef DOXYGEN294 # ifndef DOXYGEN 312 295 313 296 /* 314 297 * Ensure that any program using malloc/realloc/free will fail to compile 315 298 */ 316 #ifndef PS_ALLOW_MALLOC 317 #ifdef __GNUC__ 318 #pragma GCC poison malloc realloc calloc free 319 #else 320 #define malloc(S) _Pragma("error Use of malloc is not allowed. Use psAlloc instead.") 321 #define realloc(P,S) _Pragma("error Use of realloc is not allowed. Use psRealloc instead.") 322 #define calloc(S) _Pragma("error Use of calloc is not allowed. Use psAlloc instead.") 323 #define free(P) _Pragma("error Use of free is not allowed. Use psFree instead.") 324 #endif 325 #endif 326 327 #endif // doxygen skip 328 329 #endif // end of header file 299 # ifndef PS_ALLOW_MALLOC 300 # ifdef __GNUC__ 301 # pragma GCC poison malloc realloc calloc free 302 # else 303 # define malloc(S) _Pragma("error Use of malloc is not allowed. Use psAlloc instead.") 304 # define realloc(P,S) _Pragma("error Use of realloc is not allowed. Use psRealloc instead.") 305 # define calloc(S) _Pragma("error Use of calloc is not allowed. Use psAlloc instead.") 306 # define free(P) _Pragma("error Use of free is not allowed. Use psFree instead.") 307 # endif 308 # endif 309 310 # endif 311 // doxygen skip 312 313 #endif // end of header file -
trunk/psLib/src/sysUtils/psString.c
r1406 r1407 1 1 2 /** @file psString.c 2 3 * … … 8 9 * @author Eric Van Alst, MHPCC 9 10 * 10 * @version $Revision: 1. 7$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.8 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 22 #include <stdlib.h> … … 24 27 25 28 /******************************************************************************/ 29 26 30 /* DEFINE STATEMENTS */ 31 27 32 /******************************************************************************/ 28 33 … … 30 35 31 36 /******************************************************************************/ 37 32 38 /* TYPE DEFINITIONS */ 39 33 40 /******************************************************************************/ 34 41 … … 36 43 37 44 /*****************************************************************************/ 45 38 46 /* GLOBAL VARIABLES */ 47 39 48 /*****************************************************************************/ 40 49 … … 42 51 43 52 /*****************************************************************************/ 53 44 54 /* FILE STATIC VARIABLES */ 55 45 56 /*****************************************************************************/ 46 57 … … 48 59 49 60 /*****************************************************************************/ 61 50 62 /* FUNCTION IMPLEMENTATION - LOCAL */ 63 51 64 /*****************************************************************************/ 52 65 … … 54 67 55 68 /*****************************************************************************/ 69 56 70 /* FUNCTION IMPLEMENTATION - PUBLIC */ 71 57 72 /*****************************************************************************/ 58 73 59 char *psStringCopy( 60 const char* str 61 ) 74 char *psStringCopy(const char *str) 62 75 { 63 76 // Allocate memory using psAlloc function … … 67 80 } 68 81 69 char *psStringNCopy( 70 const char* str, 71 int nChar 72 ) 82 char *psStringNCopy(const char *str, int nChar) 73 83 { 74 84 char *returnValue = NULL; 75 85 76 86 // Check the number of characters to copy is non-negative 77 if ( nChar < 0) {87 if (nChar < 0) { 78 88 // Log error message and return NULL 79 psError(__FILE__,"psStringNCopy with negative count specified %d", 80 nChar); 89 psError(__FILE__, "psStringNCopy with negative count specified %d", nChar); 81 90 return NULL; 82 91 } … … 84 93 // Copy input string to memory allocated up to nChar characters 85 94 // Return the copy 86 returnValue = strncpy(psAlloc((size_t) nChar + 1), str, (size_t)nChar);95 returnValue = strncpy(psAlloc((size_t) nChar + 1), str, (size_t) nChar); 87 96 88 97 // Ensure the last byte is NULL character 89 if ( nChar > 0) {90 returnValue[nChar -1] = '\0';98 if (nChar > 0) { 99 returnValue[nChar - 1] = '\0'; 91 100 } 92 93 101 // Return the string pointer 94 102 return returnValue; 95 103 } 96 97 -
trunk/psLib/src/sysUtils/psString.h
r974 r1407 1 1 2 /** @file psString.h 2 3 * … … 10 11 * @author Eric Van Alst, MHPCC 11 12 * 12 * @version $Revision: 1. 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-0 6-10 01:58:06 $13 * @version $Revision: 1.6 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_STRING_H 19 # define PS_STRING_H20 # define PS_STRING_H 20 21 21 22 /******************************************************************************/ 23 22 24 /* DEFINE STATEMENTS */ 25 23 26 /******************************************************************************/ 24 27 25 28 /** This macro will convert the arguement to a quoted string */ 26 # define PS_STRING(S) #S29 # define PS_STRING(S) #S 27 30 28 31 /******************************************************************************/ 32 29 33 /* TYPE DEFINITIONS */ 34 30 35 /******************************************************************************/ 31 36 … … 33 38 34 39 /*****************************************************************************/ 40 35 41 /* FUNCTION PROTOTYPES */ 42 36 43 /*****************************************************************************/ 37 44 38 45 // Doxygen group tags 46 39 47 /** @addtogroup SysUtils 40 48 * @{ … … 49 57 * 50 58 */ 51 char *psStringCopy(52 const char *str /**< Input string of characters to copy */53 );54 59 60 char *psStringCopy(const char *str 61 /**< Input string of characters to copy */ 62 ); 55 63 56 64 /** Copies the input string up to the specified number of characters … … 67 75 * 68 76 */ 77 69 78 /*@null@*/ 70 char *psStringNCopy(71 const char *str, /**< Input string of characters to copy */72 int nChar /**< Number of bytes to allocate for string copy */73 );74 79 75 /* @} */ // Doxygen - End of SystemGroup Functions 80 char *psStringNCopy(const char *str, 81 /**< Input string of characters to copy */ 82 83 int nChar 84 /**< Number of bytes to allocate for string copy */ 85 ); 86 87 /* @} */// Doxygen - End of SystemGroup Functions 76 88 77 89 #endif 78 -
trunk/psLib/src/sysUtils/psTrace.c
r1406 r1407 1 1 2 /** @file psTrace.c 2 3 * \brief basic run-time trace facilities … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 6 22:34:05$12 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 17 16 18 /***************************************************************************** 17 19 NOTES: … … 34 36 #ifndef PS_NO_TRACE 35 37 36 # include <stdlib.h>37 # include <stdio.h>38 # include <string.h>39 # include <stdarg.h>40 # include "psMemory.h"41 # include "psTrace.h"42 # include "psString.h"43 # include "psError.h"44 45 static p_psComponent *p_psCroot = NULL; // The root of the trace component46 static FILE *p_psTraceFP = NULL; // File destination for messages.47 48 static void componentFree(p_psComponent * comp);49 static p_psComponent *componentAlloc(const char *name, int level);38 # include <stdlib.h> 39 # include <stdio.h> 40 # include <string.h> 41 # include <stdarg.h> 42 # include "psMemory.h" 43 # include "psTrace.h" 44 # include "psString.h" 45 # include "psError.h" 46 47 static p_psComponent *p_psCroot = NULL; // The root of the trace component 48 static FILE *p_psTraceFP = NULL; // File destination for messages. 49 50 static void componentFree(p_psComponent * comp); 51 static p_psComponent *componentAlloc(const char *name, int level); 50 52 51 53 /***************************************************************************** 52 54 componentAlloc(): allocate memory for a new node, and initialize members. 53 55 *****************************************************************************/ 54 static p_psComponent *componentAlloc(const char *name, 55 int level) 56 static p_psComponent *componentAlloc(const char *name, int level) 56 57 { 57 58 p_psComponent *comp = psAlloc(sizeof(p_psComponent)); 58 p_psMemSetDeallocator(comp,(psFreeFcn)componentFree); 59 60 p_psMemSetDeallocator(comp, (psFreeFcn) componentFree); 59 61 comp->name = psStringCopy(name); 60 62 comp->level = level; … … 64 66 } 65 67 66 67 68 /***************************************************************************** 68 69 componentFree(): free the current node in the root tree, and all children 69 70 nodes as well. 70 71 *****************************************************************************/ 71 static void componentFree(p_psComponent * comp)72 static void componentFree(p_psComponent * comp) 72 73 { 73 74 if (comp == NULL) { … … 85 86 } 86 87 87 88 88 /***************************************************************************** 89 89 initTrace(): simply initialize the component root tree. … … 96 96 } 97 97 98 99 98 /***************************************************************************** 100 99 Set all trace levels to zero. 101 100 *****************************************************************************/ 102 void p_psTraceReset(p_psComponent * currentNode)101 void p_psTraceReset(p_psComponent * currentNode) 103 102 { 104 103 int i = 0; … … 109 108 110 109 currentNode->level = 0; 111 for (i =0;i<currentNode->n;i++) {110 for (i = 0; i < currentNode->n; i++) { 112 111 if (NULL == currentNode->subcomp[i]) { 113 112 psError(__func__, 114 "Sub-component %d of node %s in the trace tree is NULL.\n", 115 i, currentNode->name); 113 "Sub-component %d of node %s in the trace tree is NULL.\n", i, currentNode->name); 116 114 } else { 117 115 p_psTraceReset(currentNode->subcomp[i]); … … 129 127 } 130 128 131 132 129 /***************************************************************************** 133 130 Free all nodes in the component tree. … … 137 134 psFree(p_psCroot); 138 135 } 139 140 136 141 137 /***************************************************************************** … … 145 141 to ANSI-C. 146 142 *****************************************************************************/ 147 static void componentAdd(const char *addNodeName, 148 int level) 149 { 150 int i = 0; // Loop index variable. 151 char name[strlen(addNodeName) + 1]; // buffer for writeable copy. 152 char *pname=name; 153 char *firstComponent = NULL; // first component of name 143 static void componentAdd(const char *addNodeName, int level) 144 { 145 int i = 0; // Loop index variable. 146 char name[strlen(addNodeName) + 1]; // buffer for writeable copy. 147 char *pname = name; 148 char *firstComponent = NULL; // first component of name 154 149 p_psComponent *currentNode = p_psCroot; 155 int nodeExists = 0;156 157 // Is this the root node? If so, simply set level and return.150 int nodeExists = 0; 151 152 // Is this the root node? If so, simply set level and return. 158 153 if (strcmp(".", addNodeName) == 0) { 159 154 p_psCroot->level = level; … … 162 157 163 158 if (addNodeName[0] != '.') { 164 printf("ERROR: failed to add %s to the root component tree.\n", 165 addNodeName); 159 printf("ERROR: failed to add %s to the root component tree.\n", addNodeName); 166 160 exit(1); 167 161 } … … 188 182 if (nodeExists == 0) { 189 183 currentNode->subcomp = psRealloc(currentNode->subcomp, 190 (currentNode->n + 1) * sizeof(p_psComponent*)); 191 currentNode->n = (currentNode->n)+1; 192 193 currentNode->subcomp[(currentNode->n)-1] = 194 componentAlloc(firstComponent, level); 195 } 196 } 197 } 198 184 (currentNode->n + 1) * sizeof(p_psComponent *)); 185 currentNode->n = (currentNode->n) + 1; 186 187 currentNode->subcomp[(currentNode->n) - 1] = componentAlloc(firstComponent, level); 188 } 189 } 190 } 199 191 200 192 /***************************************************************************** … … 210 202 *****************************************************************************/ 211 203 int psTraceSetLevel(const char *comp, // component of interest 212 int level) // desired trace level204 int level) // desired trace level 213 205 { 214 206 // If the root component tree does not exist, then initialize it. … … 216 208 initTrace(); 217 209 } 218 219 210 // Add the new component to the component tree. 220 211 componentAdd(comp, level); … … 223 214 return 0; 224 215 } 225 226 216 227 217 /***************************************************************************** … … 241 231 static int doGetTraceLevel(const char *aname) 242 232 { 243 char name[strlen(aname) + 1];// need a writeable copy: for strsep()244 char *pname=name;245 char *firstComponent = NULL;// first component of name233 char name[strlen(aname) + 1]; // need a writeable copy: for strsep() 234 char *pname = name; 235 char *firstComponent = NULL; // first component of name 246 236 p_psComponent *currentNode = p_psCroot; 247 int i = 0;237 int i = 0; 248 238 249 239 if (NULL == currentNode) { 250 return (PS_UNKNOWN_TRACE_LEVEL);240 return (PS_UNKNOWN_TRACE_LEVEL); 251 241 } 252 242 253 243 if (strcmp(".", aname) == 0) { 254 return (p_psCroot->level);244 return (p_psCroot->level); 255 245 } 256 246 257 247 if (aname[0] != '.') { 258 return (PS_UNKNOWN_TRACE_LEVEL);248 return (PS_UNKNOWN_TRACE_LEVEL); 259 249 } 260 250 … … 266 256 if (NULL == currentNode->subcomp[i]) { 267 257 psError(__func__, 268 "Sub-component %d of node %s in trace tree is NULL.\n", 269 i, currentNode->name); 258 "Sub-component %d of node %s in trace tree is NULL.\n", i, currentNode->name); 270 259 } 271 260 … … 273 262 currentNode = currentNode->subcomp[i]; 274 263 if (pname == NULL) { 275 return (currentNode->level);264 return (currentNode->level); 276 265 } 277 266 } 278 267 } 279 268 } 280 return(PS_UNKNOWN_TRACE_LEVEL); 281 } 282 269 return (PS_UNKNOWN_TRACE_LEVEL); 270 } 283 271 284 272 /***************************************************************************** … … 297 285 { 298 286 if (p_psCroot == NULL) { 299 return(PS_UNKNOWN_TRACE_LEVEL); 300 } 301 287 return (PS_UNKNOWN_TRACE_LEVEL); 288 } 302 289 // Search the component root tree, determine the trace level. 303 return(doGetTraceLevel(name)); 304 } 305 290 return (doGetTraceLevel(name)); 291 } 306 292 307 293 /***************************************************************************** … … 317 303 null 318 304 *****************************************************************************/ 319 static void doPrintTraceLevels(const p_psComponent *comp, 320 int depth) 305 static void doPrintTraceLevels(const p_psComponent * comp, int depth) 321 306 { 322 307 int i = 0; … … 327 312 } else { 328 313 if (comp->level == PS_UNKNOWN_TRACE_LEVEL) { 329 printf("%*s%-*s %s\n", depth, "", 20 - depth, 330 comp->name, "."); 314 printf("%*s%-*s %s\n", depth, "", 20 - depth, comp->name, "."); 331 315 } else { 332 printf("%*s%-*s %d\n", depth, "", 20 - depth, 333 comp->name, comp->level); 316 printf("%*s%-*s %d\n", depth, "", 20 - depth, comp->name, comp->level); 334 317 } 335 318 } 336 319 337 320 for (i = 0; i < comp->n; i++) { 338 doPrintTraceLevels(comp->subcomp[i], depth+1); 339 } 340 } 341 321 doPrintTraceLevels(comp->subcomp[i], depth + 1); 322 } 323 } 342 324 343 325 /***************************************************************************** … … 359 341 doPrintTraceLevels(p_psCroot, 0); 360 342 } 361 362 343 363 344 /***************************************************************************** … … 376 357 *****************************************************************************/ 377 358 void p_psTrace(const char *comp, // component being traced 378 int level, // desired trace level379 ...) // arguments359 int level, // desired trace level 360 ...) // arguments 380 361 { 381 362 char *fmt = NULL; … … 384 365 385 366 if (NULL == comp) { 386 psError(__func__, 387 "p_psTrace() called on a NULL trace level tree\n"); 388 } 389 367 psError(__func__, "p_psTrace() called on a NULL trace level tree\n"); 368 } 390 369 // Only display this message if it's trace level is less than the level 391 370 // of it's associatedcomponent. … … 413 392 va_end(ap); 414 393 } 415 416 // NOTE: should we free *fmt as well? Read the man page. 417 } 418 419 void psTraceSetDestination(FILE *fp) 394 // NOTE: should we free *fmt as well? Read the man page. 395 } 396 397 void psTraceSetDestination(FILE * fp) 420 398 { 421 399 p_psTraceFP = fp; -
trunk/psLib/src/sysUtils/psTrace.h
r1393 r1407 1 1 2 /** @file psTrace.h 2 3 * \brief basic run-time trace facilities … … 9 10 * @author George Gusciora, MHPCC 10 11 * 11 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $12 * @date $Date: 2004-08-0 5 19:38:52$12 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 13 14 * 14 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 15 16 */ 16 17 #if !defined(PS_TRACE_H) 17 # define PS_TRACE_H 118 # define PS_TRACE_H 1 18 19 19 #define PS_UNKNOWN_TRACE_LEVEL -9999 // we don't know this name's level 20 #define PS_DEFAULT_TRACE_LEVEL 0 21 20 # define PS_UNKNOWN_TRACE_LEVEL -9999 // we don't know this name's level 21 # define PS_DEFAULT_TRACE_LEVEL 0 22 22 23 23 /** \addtogroup LogTrace … … 29 29 //#define PS_NO_TRACE 1 ///< to turn off all tracing 30 30 31 #if defined(PS_NO_TRACE) 32 #define psTrace(facil, level, ...) (void)0 /* do nothing */ 33 #define p_psTrace(facil, level, ...) (void)0 /* do nothing */ 34 #define psTraceSetLevel(facil,level) 0 35 #define psTraceGetLevel(facil) 0 36 #define psTraceReset() (void)0 /* do nothing */ 37 #define psTraceFree() (void)0 /* do nothing */ 38 #define psTracePrintLevels() (void)0 /* do nothing */ 39 #define psTraceSetDestination(fp) (void)0 /* do nothing */ 40 #else 31 # if defined(PS_NO_TRACE) 32 # define psTrace(facil, level, ...) (void)0 33 /* do nothing */ 34 # define p_psTrace(facil, level, ...) (void)0 35 /* do nothing */ 36 # define psTraceSetLevel(facil,level) 0 37 # define psTraceGetLevel(facil) 0 38 # define psTraceReset() (void)0 /* do nothing */ 39 # define psTraceFree() (void)0 /* do nothing */ 40 # define psTracePrintLevels() (void)0 41 /* do nothing */ 42 # define psTraceSetDestination(fp) (void)0 43 /* do nothing */ 44 # else 41 45 42 /** Basic structure for the component tree. A component is a string of the43 form aaa.bbb.ccc, and may itself contain further subcomponents. The44 Component structure doesn't in fact contain it's full name, but only the45 last part. */46 typedef struct p_psComponent47 {48 const char *name;// last part of name of component49 int level;// trace level for this component50 int n;// number of subcomponents51 struct p_psComponent **subcomp;// next level of subcomponents52 }46 /** Basic structure for the component tree. A component is a string of the 47 form aaa.bbb.ccc, and may itself contain further subcomponents. The 48 Component structure doesn't in fact contain it's full name, but only the 49 last part. */ 50 typedef struct p_psComponent 51 { 52 const char *name; // last part of name of component 53 int level; // trace level for this component 54 int n; // number of subcomponents 55 struct p_psComponent **subcomp; // next level of subcomponents 56 } 53 57 p_psComponent; 54 58 55 # ifndef DOXYGEN59 # ifndef DOXYGEN 56 60 /// Send a trace message 57 void p_psTrace(const char *facil, ///< facilty of interest58 int myLevel, ///< desired trace level59 ...) ///< trace message arguments61 void p_psTrace(const char *facil, // /< facilty of interest 62 int myLevel, // /< desired trace level 63 ...) // /< trace message arguments 60 64 ; 61 # endif65 # endif 62 66 63 67 /// Set trace level 64 int psTraceSetLevel(const char *facil, ///< facilty of interest65 int level) ///< desired trace level68 int psTraceSetLevel(const char *facil, // /< facilty of interest 69 int level) // /< desired trace level 66 70 ; 67 71 68 72 /// Get the trace level 69 int psTraceGetLevel(const char *facil) ///< facilty of interest73 int psTraceGetLevel(const char *facil) // /< facilty of interest 70 74 ; 71 75 72 76 /// Set all trace levels to zero (do not free nodes in the component tree). 73 void psTraceReset() 74 ; 77 void psTraceReset(); 75 78 76 79 /// Free all nodes in the component tree. 77 void psTraceFree() 78 ; 80 void psTraceFree(); 79 81 80 82 /// print trace levels 81 void psTracePrintLevels(void) 82 ; 83 void psTracePrintLevels(void); 83 84 84 85 /// Set the destination of future trace messages. 85 void psTraceSetDestination(FILE * fp);86 void psTraceSetDestination(FILE * fp); 86 87 88 /* \} */// End of SystemGroup Functions 87 89 88 /* \} */ // End of SystemGroup Functions 89 90 #define psTrace(facil, level, ...) p_psTrace(facil, level, __VA_ARGS__) 91 #endif 90 # define psTrace(facil, level, ...) p_psTrace(facil, level, __VA_ARGS__) 91 # endif 92 92 93 93 #endif 94 -
trunk/psLib/src/sysUtils/psType.h
r1385 r1407 1 1 2 /** @file psType.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 6$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 4 23:37:39$13 * @version $Revision: 1.17 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 #ifndef PS_TYPE_H 19 # define PS_TYPE_H20 # define PS_TYPE_H 20 21 21 # include <complex.h>22 # include <stdint.h>23 # include <float.h>22 # include <complex.h> 23 # include <stdint.h> 24 # include <float.h> 24 25 25 26 /// @addtogroup DataContainer … … 27 28 28 29 /******************************************************************************/ 30 29 31 /* TYPE DEFINITIONS */ 32 30 33 /******************************************************************************/ 31 34 … … 37 40 */ 38 41 39 typedef uint8_t psU8; ///< 8-bit unsigned int 40 typedef uint16_t psU16; ///< 16-bit unsigned int 41 typedef uint32_t psU32; ///< 32-bit unsigned int 42 typedef uint64_t psU64; ///< 64-bit unsigned int 43 typedef int8_t psS8; ///< 8-bit signed int 44 typedef int16_t psS16; ///< 16-bit signed int 45 typedef int32_t psS32; ///< 32-bit signed int 46 typedef int64_t psS64; ///< 64-bit signed int 47 typedef float psF32; ///< 32-bit floating point 48 typedef double psF64; ///< 64-bit floating point 49 typedef complex float psC32; ///< complex with 32-bit floating point Real and Imagary numbers 50 typedef complex double psC64; ///< complex with 64-bit floating point Real and Imagary numbers 51 typedef void* psPTR; ///< void pointer 52 42 typedef uint8_t psU8; // /< 8-bit unsigned int 43 typedef uint16_t psU16; // /< 16-bit unsigned int 44 typedef uint32_t psU32; // /< 32-bit unsigned int 45 typedef uint64_t psU64; // /< 64-bit unsigned int 46 typedef int8_t psS8; // /< 8-bit signed int 47 typedef int16_t psS16; // /< 16-bit signed int 48 typedef int32_t psS32; // /< 32-bit signed int 49 typedef int64_t psS64; // /< 64-bit signed int 50 typedef float psF32; // /< 32-bit floating point 51 typedef double psF64; // /< 64-bit floating point 52 typedef complex float psC32; // /< complex with 32-bit floating point Real and Imagary numbers 53 typedef complex double psC64; // /< complex with 64-bit floating point Real and Imagary numbers 54 typedef void *psPTR; // /< void pointer 53 55 54 56 typedef enum { 55 PS_TYPE_S8 = 0x0101, ///< Character. 56 PS_TYPE_S16 = 0x0102, ///< Short integer. 57 PS_TYPE_S32 = 0x0104, ///< Integer. 58 PS_TYPE_S64 = 0x0108, ///< Long integer. 59 PS_TYPE_U8 = 0x0301, ///< Unsigned character. 60 PS_TYPE_U16 = 0x0302, ///< Unsigned short integer. 61 PS_TYPE_U32 = 0x0304, ///< Unsigned integer. 62 PS_TYPE_U64 = 0x0308, ///< Unsigned long integer. 63 PS_TYPE_F32 = 0x0404, ///< Single-precision Floating point. 64 PS_TYPE_F64 = 0x0408, ///< Double-precision floating point. 65 PS_TYPE_C32 = 0x0808, ///< Complex numbers consisting of single-precision floating point. 66 PS_TYPE_C64 = 0x0810, ///< Complex numbers consisting of double-precision floating point. 67 PS_TYPE_PTR = 0x0000 ///< Something else that's not supported for arithmetic. 57 PS_TYPE_S8 = 0x0101, // /< Character. 58 PS_TYPE_S16 = 0x0102, // /< Short integer. 59 PS_TYPE_S32 = 0x0104, // /< Integer. 60 PS_TYPE_S64 = 0x0108, // /< Long integer. 61 PS_TYPE_U8 = 0x0301, // /< Unsigned character. 62 PS_TYPE_U16 = 0x0302, // /< Unsigned short integer. 63 PS_TYPE_U32 = 0x0304, // /< Unsigned integer. 64 PS_TYPE_U64 = 0x0308, // /< Unsigned long integer. 65 PS_TYPE_F32 = 0x0404, // /< Single-precision Floating point. 66 PS_TYPE_F64 = 0x0408, // /< Double-precision floating point. 67 PS_TYPE_C32 = 0x0808, // /< Complex numbers consisting of single-precision floating 68 // point. 69 PS_TYPE_C64 = 0x0810, // /< Complex numbers consisting of double-precision floating 70 // point. 71 PS_TYPE_PTR = 0x0000 // /< Something else that's not supported for arithmetic. 68 72 } psElemType; 69 73 70 # define PS_TYPE_MASK PS_TYPE_U8 ///< the psElemType to use for mask image71 # define PS_TYPE_MASK_DATA U8 ///< the data member to use for mask image72 # define PS_TYPE_MASK_NAME "psU8"73 typedef psU8 psMaskType; ///< the C datatype for a mask image74 # define PS_TYPE_MASK PS_TYPE_U8 // /< the psElemType to use for mask image 75 # define PS_TYPE_MASK_DATA U8 // /< the data member to use for mask image 76 # define PS_TYPE_MASK_NAME "psU8" 77 typedef psU8 psMaskType; // /< the C datatype for a mask image 74 78 75 # define PS_MIN_S8 INT8_MIN76 # define PS_MIN_S16 INT16_MIN77 # define PS_MIN_S32 INT32_MIN78 # define PS_MIN_S64 INT64_MIN79 # define PS_MIN_U8 080 # define PS_MIN_U16 081 # define PS_MIN_U32 082 # define PS_MIN_U64 083 # define PS_MIN_F32 -FLT_MAX84 # define PS_MIN_F64 -DBL_MAX85 # define PS_MIN_C32 -FLT_MAX86 # define PS_MIN_C64 -DBL_MAX79 # define PS_MIN_S8 INT8_MIN 80 # define PS_MIN_S16 INT16_MIN 81 # define PS_MIN_S32 INT32_MIN 82 # define PS_MIN_S64 INT64_MIN 83 # define PS_MIN_U8 0 84 # define PS_MIN_U16 0 85 # define PS_MIN_U32 0 86 # define PS_MIN_U64 0 87 # define PS_MIN_F32 -FLT_MAX 88 # define PS_MIN_F64 -DBL_MAX 89 # define PS_MIN_C32 -FLT_MAX 90 # define PS_MIN_C64 -DBL_MAX 87 91 88 # define PS_MAX_S8 INT8_MAX89 # define PS_MAX_S16 INT16_MAX90 # define PS_MAX_S32 INT32_MAX91 # define PS_MAX_S64 INT64_MAX92 # define PS_MAX_U8 UINT8_MAX93 # define PS_MAX_U16 UINT16_MAX94 # define PS_MAX_U32 UINT32_MAX95 # define PS_MAX_U64 UINT64_MAX96 # define PS_MAX_F32 FLT_MAX97 # define PS_MAX_F64 DBL_MAX98 # define PS_MAX_C32 FLT_MAX99 # define PS_MAX_C64 DBL_MAX92 # define PS_MAX_S8 INT8_MAX 93 # define PS_MAX_S16 INT16_MAX 94 # define PS_MAX_S32 INT32_MAX 95 # define PS_MAX_S64 INT64_MAX 96 # define PS_MAX_U8 UINT8_MAX 97 # define PS_MAX_U16 UINT16_MAX 98 # define PS_MAX_U32 UINT32_MAX 99 # define PS_MAX_U64 UINT64_MAX 100 # define PS_MAX_F32 FLT_MAX 101 # define PS_MAX_F64 DBL_MAX 102 # define PS_MAX_C32 FLT_MAX 103 # define PS_MAX_C64 DBL_MAX 100 104 101 105 /// Macro to get the bad pixel reason code (stored as part of mask value) 102 # define PS_BADPIXEL_BITMASK 0x0f103 # define PS_GET_BADPIXEL(maskValue) (maskValue & PS_BADPIXEL_BITMASK)106 # define PS_BADPIXEL_BITMASK 0x0f 107 # define PS_GET_BADPIXEL(maskValue) (maskValue & PS_BADPIXEL_BITMASK) 104 108 105 # define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)109 # define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0) 106 110 107 111 /// Macro to apply a bad pixel reason code to mask image 108 # define PS_SET_BADPIXEL(maskValue, reasonCode) \112 # define PS_SET_BADPIXEL(maskValue, reasonCode) \ 109 113 { \ 110 114 maskValue = (psMaskType)((reasonCode & PS_BADPIXEL_BITMASK) | (maskValue & ~PS_BADPIXEL_BITMASK)); \ … … 112 116 113 117 /// Macro to determine if the psElemType is an integer. 114 # define PS_IS_PSELEMTYPE_INT(x) ((x & 0x100) == 0x100)118 # define PS_IS_PSELEMTYPE_INT(x) ((x & 0x100) == 0x100) 115 119 /// Macro to determine if the psElemType is unsigned. 116 # define PS_IS_PSELEMTYPE_UNSIGNED(x) ((x & 0x200) == 0x200)120 # define PS_IS_PSELEMTYPE_UNSIGNED(x) ((x & 0x200) == 0x200) 117 121 /// Macro to determine if the psElemType is a real (non-complex) floating-point type. 118 # define PS_IS_PSELEMTYPE_REAL(x) ((x & 0x400) == 0x400)122 # define PS_IS_PSELEMTYPE_REAL(x) ((x & 0x400) == 0x400) 119 123 /// Macro to determine if the psElemType is complex number type. 120 # define PS_IS_PSELEMTYPE_COMPLEX(x) ((x & 0x800) == 0x800)124 # define PS_IS_PSELEMTYPE_COMPLEX(x) ((x & 0x800) == 0x800) 121 125 /// Macro to determine the storage size, in bytes, of the psElemType. 122 # define PSELEMTYPE_SIZEOF(x) ( (x==PS_TYPE_PTR) ? sizeof(void*) :(x & 0xFF) )126 # define PSELEMTYPE_SIZEOF(x) ( (x==PS_TYPE_PTR) ? sizeof(void*) :(x & 0xFF) ) 123 127 124 128 /** Dimensions of a data type. … … 128 132 */ 129 133 typedef enum { 130 PS_DIMEN_SCALAR, ///< Scalar.131 PS_DIMEN_VECTOR, ///< Vector.132 PS_DIMEN_TRANSV, ///< Transposed vector.133 PS_DIMEN_IMAGE, ///< Image.134 PS_DIMEN_OTHER ///< Something else that's not supported for arithmetic.134 PS_DIMEN_SCALAR, // /< Scalar. 135 PS_DIMEN_VECTOR, // /< Vector. 136 PS_DIMEN_TRANSV, // /< Transposed vector. 137 PS_DIMEN_IMAGE, // /< Image. 138 PS_DIMEN_OTHER // /< Something else that's not supported for arithmetic. 135 139 } psDimen; 136 140 … … 143 147 typedef struct 144 148 { 145 psElemType type; ///< Primitive type.146 psDimen dimen; ///< Dimensionality.149 psElemType type; // /< Primitive type. 150 psDimen dimen; // /< Dimensionality. 147 151 } 148 152 psType; -
trunk/psLib/src/types/psArray.c
r1406 r1407 1 1 2 /** @file psArray.c 2 3 * … … 8 9 * @author Ross Harman, MHPCC 9 10 * 10 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $11 * @date $Date: 2004-08-0 6 22:34:05$11 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 12 * @date $Date: 2004-08-07 00:06:06 $ 12 13 * 13 14 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 16 17 /******************************************************************************/ 18 17 19 /* INCLUDE FILES */ 20 18 21 /******************************************************************************/ 19 #include<stdlib.h> // for qsort, etc.22 #include<stdlib.h> // for qsort, etc. 20 23 21 24 #include "psMemory.h" … … 24 27 #include "psLogMsg.h" 25 28 29 /*****************************************************************************/ 30 31 /* FUNCTION IMPLEMENTATION - LOCAL */ 26 32 27 33 /*****************************************************************************/ 28 /* FUNCTION IMPLEMENTATION - LOCAL */ 29 /*****************************************************************************/ 30 static void arrayFree(psArray *restrict psArr); 34 static void arrayFree(psArray * restrict psArr); 31 35 32 36 /*****************************************************************************/ 37 33 38 /* FUNCTION IMPLEMENTATION - PUBLIC */ 39 34 40 /*****************************************************************************/ 35 psArray *psArrayAlloc(unsigned int nalloc)41 psArray *psArrayAlloc(unsigned int nalloc) 36 42 { 37 43 psArray *psArr = NULL; 38 44 39 45 // Invalid nalloc 40 if (nalloc < 1) {46 if (nalloc < 1) { 41 47 psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc); 42 48 return NULL; 43 49 } 44 45 50 // Create vector struct 46 psArr = (psArray *) psAlloc(sizeof(psArray));47 p_psMemSetDeallocator(psArr, (psFreeFcn)arrayFree);51 psArr = (psArray *) psAlloc(sizeof(psArray)); 52 p_psMemSetDeallocator(psArr, (psFreeFcn) arrayFree); 48 53 49 54 psArr->nalloc = nalloc; … … 51 56 52 57 // Create vector data array 53 psArr->data = psAlloc(nalloc *sizeof(psPTR));58 psArr->data = psAlloc(nalloc * sizeof(psPTR)); 54 59 55 60 return psArr; 56 61 } 57 62 58 psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in)63 psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in) 59 64 { 60 65 // Invalid nalloc 61 if (nalloc < 1) {66 if (nalloc < 1) { 62 67 psError(__func__, "Invalid value for realloc (%d)\n", nalloc); 63 68 return NULL; 64 69 } 65 70 66 if (in == NULL) {71 if (in == NULL) { 67 72 psError(__func__, "Null input vector\n"); 68 73 return NULL; 69 } else 70 if(in->nalloc != nalloc) { // No need to realloc to same size 71 if(nalloc < in->n) { 72 for (int i = nalloc; i < in->n; i++) { // For reduction in vector size 73 psFree(in->data[i]); 74 } 75 in->n = nalloc; 74 } else if (in->nalloc != nalloc) { // No need to realloc to same size 75 if (nalloc < in->n) { 76 for (int i = nalloc; i < in->n; i++) { // For reduction in vector size 77 psFree(in->data[i]); 76 78 } 77 78 // Realloc after decrementation to avoid accessing freed array elements 79 in->data = psRealloc(in->data,nalloc*sizeof(psPTR)); 80 in->nalloc = nalloc; 79 in->n = nalloc; 81 80 } 81 // Realloc after decrementation to avoid accessing freed array elements 82 in->data = psRealloc(in->data, nalloc * sizeof(psPTR)); 83 in->nalloc = nalloc; 84 } 82 85 83 86 return in; 84 87 } 85 88 86 static void arrayFree(psArray * restrict psArr)89 static void arrayFree(psArray * restrict psArr) 87 90 { 88 91 if (psArr == NULL) { … … 95 98 } 96 99 97 void psArrayElementFree(psArray * restrict psArr)100 void psArrayElementFree(psArray * restrict psArr) 98 101 { 99 102 100 if (psArr == NULL) {103 if (psArr == NULL) { 101 104 return; 102 105 } 103 106 104 for (int i = 0; i < psArr->n; i++) {107 for (int i = 0; i < psArr->n; i++) { 105 108 psFree(psArr->data[i]); 106 109 psArr->data[i] = NULL; … … 108 111 } 109 112 110 psArray * psArraySort(psArray* in, psComparePtrFcn compare)113 psArray *psArraySort(psArray * in, psComparePtrFcn compare) 111 114 { 112 115 if (in == NULL) { … … 114 117 } 115 118 116 qsort(in->data, in->n, sizeof(psPTR), 117 (int(*)(const void *, const void *))compare); 118 119 qsort(in->data, in->n, sizeof(psPTR), (int (*)(const void *, const void *))compare); 119 120 120 121 return in; -
trunk/psLib/src/types/psArray.h
r1228 r1407 1 1 2 /** @file psArray.h 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 1$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-0 7-15 22:18:02$14 * @version $Revision: 1.12 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 #ifndef PS_ARRAY_H 20 # define PS_ARRAY_H21 # define PS_ARRAY_H 21 22 22 # include "psType.h"23 # include "psCompare.h"23 # include "psType.h" 24 # include "psCompare.h" 24 25 25 26 /// @addtogroup Array … … 33 34 typedef struct 34 35 { 35 unsigned int nalloc; ///< Total number of elements available.36 unsigned int n; ///< Number of elements in use.37 psPTR * data; ///< An Array of pointer elements36 unsigned int nalloc; // /< Total number of elements available. 37 unsigned int n; // /< Number of elements in use. 38 psPTR *data; // /< An Array of pointer elements 38 39 } 39 40 psArray; 40 41 41 42 /*****************************************************************************/ 43 42 44 /* FUNCTION PROTOTYPES */ 45 43 46 /*****************************************************************************/ 44 47 … … 51 54 * 52 55 */ 53 psArray *psArrayAlloc( 54 unsigned int nalloc ///< Total number of elements to make available. 55 ); 56 psArray *psArrayAlloc(unsigned int nalloc // /< Total number of elements to make available. 57 ); 56 58 57 59 /** Reallocate an array. … … 63 65 * 64 66 */ 65 psArray *psArrayRealloc( 66 unsigned int nalloc, ///< Total number of elements to make available. 67 psArray *restrict psArr ///< array to reallocate. 68 ); 67 psArray *psArrayRealloc(unsigned int nalloc, // /< Total number of elements to make available. 68 psArray * restrict psArr // /< array to reallocate. 69 ); 69 70 70 71 /** Deallocate/Dereference elements of an array. … … 75 76 * 76 77 */ 77 void psArrayElementFree( 78 psArray *restrict psArr ///< Void pointer array to destroy. 79 ); 78 void psArrayElementFree(psArray * restrict psArr // /< Void pointer array to destroy. 79 ); 80 80 81 81 /** Sort the array according to an external compare function. … … 86 86 * @return psArray* The sorted array. 87 87 */ 88 psArray * psArraySort(psArray* in, psComparePtrFcn compare);88 psArray *psArraySort(psArray * in, psComparePtrFcn compare); 89 89 90 90 /// @} -
trunk/psLib/src/types/psBitSet.c
r1406 r1407 1 1 2 /** @file psBitSet.c 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 6 22:34:05$13 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 17 18 18 19 /******************************************************************************/ 20 19 21 /* INCLUDE FILES */ 22 20 23 /******************************************************************************/ 21 24 #include <string.h> … … 31 34 32 35 /******************************************************************************/ 36 33 37 /* DEFINE STATEMENTS */ 34 /******************************************************************************/ 35 36 // None 37 38 /******************************************************************************/ 38 39 /******************************************************************************/ 40 41 // None 42 43 /******************************************************************************/ 44 39 45 /* TYPE DEFINITIONS */ 40 /******************************************************************************/ 41 42 // None 43 44 /*****************************************************************************/ 46 47 /******************************************************************************/ 48 49 // None 50 51 /*****************************************************************************/ 52 45 53 /* GLOBAL VARIABLES */ 46 /*****************************************************************************/ 47 48 // None 49 50 /*****************************************************************************/ 54 55 /*****************************************************************************/ 56 57 // None 58 59 /*****************************************************************************/ 60 51 61 /* FILE STATIC VARIABLES */ 52 /*****************************************************************************/ 53 54 // None 55 56 /*****************************************************************************/ 62 63 /*****************************************************************************/ 64 65 // None 66 67 /*****************************************************************************/ 68 57 69 /* FUNCTION IMPLEMENTATION - LOCAL */ 58 /*****************************************************************************/ 59 static void psBitSetFree(psBitSet *restrict inBitSet); 60 70 71 /*****************************************************************************/ 72 static void psBitSetFree(psBitSet * restrict inBitSet); 61 73 62 74 /** Private function to create a mask. … … 70 82 { 71 83 char mask = (char)0x01; 84 72 85 // Ignore splint warning about negative bit shifts 73 /* @i@*/74 mask = mask << (bit %8);86 /* @i@ */ 87 mask = mask << (bit % 8); 75 88 76 89 return mask; … … 78 91 79 92 /*****************************************************************************/ 93 80 94 /* FUNCTION IMPLEMENTATION - PUBLIC */ 81 /*****************************************************************************/ 82 psBitSet* psBitSetAlloc(int n) 95 96 /*****************************************************************************/ 97 psBitSet *psBitSetAlloc(int n) 83 98 { 84 99 int numBytes = 0; 85 100 psBitSet *newObj = NULL; 86 101 87 if (n <= 0) {102 if (n <= 0) { 88 103 psError(__func__, " : Line %d - Allocation size must be > 0: size = %d", __LINE__, n); 89 104 return 0; 90 105 } 91 106 92 numBytes = ceil(n /8.0);107 numBytes = ceil(n / 8.0); 93 108 newObj = psAlloc(sizeof(psBitSet)); 94 if (newObj == NULL) {95 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);96 } 97 p_psMemSetDeallocator(newObj, (psFreeFcn)psBitSetFree);109 if (newObj == NULL) { 110 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 111 } 112 p_psMemSetDeallocator(newObj, (psFreeFcn) psBitSetFree); 98 113 newObj->n = numBytes; 99 114 100 115 // Ignore splint warning about releasing pointer members, since they've not been allocated yet 101 /* @i@*/102 newObj->bits = psAlloc(sizeof(char) *numBytes);103 if (newObj->bits == NULL) {104 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__);116 /* @i@ */ 117 newObj->bits = psAlloc(sizeof(char) * numBytes); 118 if (newObj->bits == NULL) { 119 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 105 120 } 106 121 … … 110 125 } 111 126 112 static void psBitSetFree(psBitSet * restrict inBitSet)113 { 114 if (inBitSet == NULL) {127 static void psBitSetFree(psBitSet * restrict inBitSet) 128 { 129 if (inBitSet == NULL) { 115 130 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 116 131 return; … … 119 134 } 120 135 121 psBitSet * psBitSetSet(psBitSet *inBitSet, int bit)122 { 123 char *byte = NULL;124 125 if (inBitSet == NULL) {136 psBitSet *psBitSetSet(psBitSet * inBitSet, int bit) 137 { 138 char *byte = NULL; 139 140 if (inBitSet == NULL) { 126 141 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 127 142 return inBitSet; 128 } else 129 if(bit < 0) { 130 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 131 return inBitSet; 132 } else 133 if(bit > inBitSet->n*8-1) { 134 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 135 return inBitSet; 136 } 137 143 } else if (bit < 0) { 144 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 145 return inBitSet; 146 } else if (bit > inBitSet->n * 8 - 1) { 147 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 148 return inBitSet; 149 } 138 150 // Variable byte is the byte in the array that contains the bit to be set 139 byte = inBitSet->bits +bit/8;151 byte = inBitSet->bits + bit / 8; 140 152 *byte |= mask(bit); 141 153 … … 143 155 } 144 156 145 bool psBitSetTest(const psBitSet *inBitSet, int bit) 146 { 147 char* byte = NULL; 148 149 if(inBitSet == NULL) { 150 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 151 return 0; 152 } else 153 if(bit < 0) { 154 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 155 return 0; 156 } else 157 if(bit > inBitSet->n*8-1) { 158 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 159 return 0; 160 } 161 157 bool psBitSetTest(const psBitSet * inBitSet, int bit) 158 { 159 char *byte = NULL; 160 161 if (inBitSet == NULL) { 162 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 163 return 0; 164 } else if (bit < 0) { 165 psError(__func__, " : Line %d - Bit position too small: %d", __LINE__, bit); 166 return 0; 167 } else if (bit > inBitSet->n * 8 - 1) { 168 psError(__func__, " : Line %d - Bit position too large: %d", __LINE__, bit); 169 return 0; 170 } 162 171 // Variable byte is the byte in the array that contains the bit to be tested 163 byte = inBitSet->bits +bit/8;164 if ((int)(*byte&mask(bit)) == 0) {172 byte = inBitSet->bits + bit / 8; 173 if ((int)(*byte & mask(bit)) == 0) { 165 174 return 0; 166 175 } … … 169 178 } 170 179 171 psBitSet * psBitSetOp(psBitSet *outBitSet, const psBitSet *restrict inBitSet1, char *operator,172 const psBitSet * restrict inBitSet2)180 psBitSet *psBitSetOp(psBitSet * outBitSet, const psBitSet * restrict inBitSet1, char *operator, 181 const psBitSet * restrict inBitSet2) 173 182 { 174 183 int i = 0; … … 179 188 char *inBits2 = NULL; 180 189 181 if (inBitSet1 == NULL) {190 if (inBitSet1 == NULL) { 182 191 psError(__func__, " : Line %d - Null psBitSet for inBitSet1 argument", __LINE__); 183 192 return outBitSet; 184 193 } 185 194 186 if (operator == NULL) {195 if (operator == NULL) { 187 196 psError(__func__, " : Line %d - Null input operator\n", __LINE__); 188 197 return outBitSet; 189 198 } 190 199 191 if (inBitSet2 == NULL) {200 if (inBitSet2 == NULL) { 192 201 psError(__func__, " : Line %d - Null psBitSet for inBitSet2 argument", __LINE__); 193 202 return outBitSet; 194 203 } 195 204 196 if (outBitSet == NULL) {197 outBitSet = psBitSetAlloc(inBitSet1->n *8);198 } 199 200 if (inBitSet1->n != inBitSet2->n || outBitSet->n != inBitSet1->n) {205 if (outBitSet == NULL) { 206 outBitSet = psBitSetAlloc(inBitSet1->n * 8); 207 } 208 209 if (inBitSet1->n != inBitSet2->n || outBitSet->n != inBitSet1->n) { 201 210 psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__); 202 211 return outBitSet; … … 209 218 210 219 tempChar = toupper(operator[0]); 211 switch (tempChar) {220 switch (tempChar) { 212 221 case 'A': 213 for (i=0; i<n; i++) {222 for (i = 0; i < n; i++) { 214 223 outBits[i] = inBits1[i] & inBits2[i]; 215 224 } 216 225 break; 217 226 case 'O': 218 for (i=0; i<n; i++) {227 for (i = 0; i < n; i++) { 219 228 outBits[i] = inBits1[i] | inBits2[i]; 220 229 } 221 230 break; 222 231 case 'X': 223 for (i=0; i<n; i++) {232 for (i = 0; i < n; i++) { 224 233 outBits[i] = inBits1[i] ^ inBits2[i]; 225 234 } … … 232 241 } 233 242 234 psBitSet * psBitSetNot(psBitSet *outBitSet, const psBitSet *restrict inBitSet)243 psBitSet *psBitSetNot(psBitSet * outBitSet, const psBitSet * restrict inBitSet) 235 244 { 236 245 int i = 0; … … 239 248 char *inBits = NULL; 240 249 241 if (inBitSet == NULL) {250 if (inBitSet == NULL) { 242 251 psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__); 243 252 return outBitSet; … … 245 254 246 255 n = inBitSet->n; 247 if (n == 0) {256 if (n == 0) { 248 257 psError(__func__, " : Line %d - No elements in inBitSet", __LINE__); 249 258 return outBitSet; 250 259 } 251 260 252 if (outBitSet == NULL) {253 outBitSet = psBitSetAlloc(n *8);254 } 255 256 if (inBitSet->n != outBitSet->n) {261 if (outBitSet == NULL) { 262 outBitSet = psBitSetAlloc(n * 8); 263 } 264 265 if (inBitSet->n != outBitSet->n) { 257 266 psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__); 258 267 return outBitSet; … … 262 271 inBits = inBitSet->bits; 263 272 264 for (i=0; i<n; i++) {273 for (i = 0; i < n; i++) { 265 274 outBits[i] = ~inBits[i]; 266 275 } … … 269 278 } 270 279 271 char *psBitSetToString(const psBitSet * restrict inBitSet)280 char *psBitSetToString(const psBitSet * restrict inBitSet) 272 281 { 273 282 int i = 0; 274 int numBits = inBitSet->n*8; 275 char* outString = psAlloc((size_t)numBits+1); 276 if(outString == NULL) { 277 psAbort(__func__," : Line %d - Failed to allocate memory", __LINE__); 278 } 279 280 for(i=0; i<numBits; i++) { 281 outString[numBits-i-1] = (psBitSetTest(inBitSet, i) == 1)?'1':'0'; 283 int numBits = inBitSet->n * 8; 284 char *outString = psAlloc((size_t) numBits + 1); 285 286 if (outString == NULL) { 287 psAbort(__func__, " : Line %d - Failed to allocate memory", __LINE__); 288 } 289 290 for (i = 0; i < numBits; i++) { 291 outString[numBits - i - 1] = (psBitSetTest(inBitSet, i) == 1) ? '1' : '0'; 282 292 } 283 293 -
trunk/psLib/src/types/psBitSet.h
r1172 r1407 1 1 2 /** @file psBitSet.h 2 3 * … … 12 13 * @author Ross Harman, MHPCC 13 14 * 14 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $15 * @date $Date: 2004-0 7-01 21:48:11$15 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 16 * @date $Date: 2004-08-07 00:06:06 $ 16 17 * 17 18 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 19 20 20 21 #ifndef PSBITSET_H 21 # define PSBITSET_H22 # define PSBITSET_H 22 23 23 24 /// @addtogroup BitSet … … 25 26 26 27 /******************************************************************************/ 28 27 29 /* TYPE DEFINITIONS */ 30 28 31 /******************************************************************************/ 29 32 … … 35 38 typedef struct 36 39 { 40 37 41 int n; /**< Number of bytes in the array */ 42 38 43 char *bits; /**< Aray of bytes holding bits */ 39 44 } … … 41 46 42 47 /*****************************************************************************/ 48 43 49 /* FUNCTION PROTOTYPES */ 50 44 51 /*****************************************************************************/ 45 52 … … 51 58 * @return psBitSet*: Pointer to struct containing array of bits and size of array. 52 59 */ 60 53 61 /*@null@*/ 54 psBitSet* psBitSetAlloc( 55 int n /**< Number of bits in psBitSet array */ 56 ); 62 63 psBitSet *psBitSetAlloc(int n 64 /**< Number of bits in psBitSet array */ 65 ); 57 66 58 67 /** Set a bit. … … 64 73 * @return psBitSet*: Pointer to struct containing psBitSet. 65 74 */ 66 psBitSet* psBitSetSet( 67 /*@returned@*/psBitSet *restrict inMask, /**< Pointer to psBitSet to be set. */ 68 int bit /**< Bit to be set. */ 75 psBitSet *psBitSetSet( 76 77 /* @returned@ */ psBitSet * restrict inMask, 78 /**< Pointer to psBitSet to be set. */ 79 80 int bit/**< Bit to be set. */ 69 81 ); 70 82 … … 78 90 * @return int: Value of bit, either one or zero. 79 91 */ 80 bool psBitSetTest( 81 const psBitSet *restrict inMask, /**< Pointer psBitSet to be tested. */ 82 int bit /**< Bit to be tested. */ 83 ); 92 93 bool psBitSetTest(const psBitSet * restrict inMask, 94 /**< Pointer psBitSet to be tested. */ 95 96 int bit /**< Bit to be tested. */ 97 ); 84 98 85 99 /** Perform a binary operation on two psBitSets … … 90 104 * @return psBitSet*: Pointer to struct containing result of binary operation. 91 105 */ 92 psBitSet* psBitSetOp( 93 /*@returned@*/psBitSet *restrict outMask, /**< Resulting psBitSet from binary operation */ 94 const psBitSet *restrict inMask1, /**< First psBitSet on which to operate */ 95 char *operator, /**< Bit operation */ 96 const psBitSet *restrict inMask2 /**< First psBitSet on which to operate */ 106 psBitSet *psBitSetOp( 107 108 /* @returned@ */ psBitSet * restrict outMask, 109 /**< Resulting psBitSet from binary operation */ 110 111 const psBitSet * restrict inMask1, 112 /**< First psBitSet on which to operate */ 113 114 char *operator, /**< Bit operation */ 115 116 const psBitSet * restrict inMask2 117 /**< First psBitSet on which to operate */ 97 118 ); 98 119 … … 103 124 * @return psBitSet*: Pointer to struct containing result of operation. 104 125 */ 105 psBitSet* psBitSetNot( 106 psBitSet *outBitSet, /**< Resulting psBitSet from operation */ 107 const psBitSet *restrict inBitSet /**< Input psBitSet */ 108 ); 126 127 psBitSet *psBitSetNot(psBitSet * outBitSet, 128 /**< Resulting psBitSet from operation */ 129 130 const psBitSet * restrict inBitSet 131 /**< Input psBitSet */ 132 ); 109 133 110 134 /** Convert the psBitSet to a string of ones and zeros. … … 115 139 * @return char*: Pointer to character array containing string data. 116 140 */ 117 char *psBitSetToString( 118 const psBitSet *restrict inMask /**< psBitSet to convert */ 119 ); 141 142 char *psBitSetToString(const psBitSet * restrict inMask 143 /**< psBitSet to convert */ 144 ); 120 145 121 146 /// @} -
trunk/psLib/src/types/psList.c
r1406 r1407 1 1 2 /** @file psList.c 2 3 * @brief Support for doubly linked lists … … 6 7 * @author Robert Daniel DeSonia, MHPCC 7 8 * 8 * @version $Revision: 1.1 3$ $Name: not supported by cvs2svn $9 * @date $Date: 2004-08-0 6 22:34:05$9 * @version $Revision: 1.14 $ $Name: not supported by cvs2svn $ 10 * @date $Date: 2004-08-07 00:06:06 $ 10 11 * 11 12 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 15 16 #include <stdbool.h> 16 17 #include <stdio.h> 17 #include <pthread.h> // we need a mutex to make this stuff thread safe.18 #include <pthread.h> // we need a mutex to make this stuff thread safe. 18 19 19 20 #include "psError.h" … … 24 25 #include "psLogMsg.h" 25 26 26 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head27 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail27 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head 28 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail 28 29 29 30 // private functions. 30 static psListElem* listGetIterator(psList* list); 31 static int listGetIteratorIndex(psList* list); 32 static void listSetIterator(psList *list, int where, bool lockList); 33 static void listFree(psList *list); 34 31 static psListElem *listGetIterator(psList * list); 32 static int listGetIteratorIndex(psList * list); 33 static void listSetIterator(psList * list, int where, bool lockList); 34 static void listFree(psList * list); 35 35 36 36 psList *psListAlloc(void *data) 37 37 { 38 38 psList *list = psAlloc(sizeof(psList)); 39 p_psMemSetDeallocator(list,(psFreeFcn)listFree); 39 40 p_psMemSetDeallocator(list, (psFreeFcn) listFree); 40 41 41 42 list->size = 0; … … 44 45 list->iterIndex = PS_LIST_HEAD; 45 46 46 pthread_mutex_init(&(list->lock), NULL)47 pthread_mutex_init(&(list->lock), NULL) 47 48 ; 48 49 … … 54 55 } 55 56 56 static void listFree(psList * list)57 static void listFree(psList * list) 57 58 { 58 59 if (list == NULL) { … … 63 64 ; 64 65 65 for (psListElem *ptr = list->head; ptr != NULL;) {66 for (psListElem * ptr = list->head; ptr != NULL;) { 66 67 psListElem *next = ptr->next; 67 68 … … 80 81 } 81 82 82 bool psListAdd(psList * list, void *data, int where)83 { 84 psListElem *position;85 psListElem *elem;83 bool psListAdd(psList * list, void *data, int where) 84 { 85 psListElem *position; 86 psListElem *elem; 86 87 int cursorIndex = 0; 87 88 … … 95 96 96 97 if (where <= PS_LIST_UNKNOWN) { 97 /// XXX What is the better way to communicate this failure to the caller? 98 psLogMsg(__func__,PS_LOG_WARN, 99 "The given insert location (%i) for psListAdd is invalid.", 100 where); 98 // / XXX What is the better way to communicate this failure to the caller? 99 psLogMsg(__func__, PS_LOG_WARN, "The given insert location (%i) for psListAdd is invalid.", where); 101 100 return false; 102 101 } … … 108 107 109 108 if (where > 0 && where > list->size) { 110 psLogMsg(__func__,PS_LOG_WARN, 111 "Invalid index %d (only %d elements in psList); assuming tail.", 112 where, list->size); 109 psLogMsg(__func__, PS_LOG_WARN, 110 "Invalid index %d (only %d elements in psList); assuming tail.", where, list->size); 113 111 where = PS_LIST_TAIL; 114 112 } … … 138 136 139 137 if (position == NULL) { 140 psError(__func__,"%s failed to move cursor to specified location (%d)",__func__,where); 141 position = list->head; // since we no list->size != 0, this must be non-NULL 142 } 143 138 psError(__func__, "%s failed to move cursor to specified location (%d)", __func__, where); 139 position = list->head; // since we no list->size != 0, this must be non-NULL 140 } 144 141 // insert our new element in front of the given position 145 142 elem->prev = position->prev; … … 147 144 position->prev = elem; 148 145 149 if (elem->prev == NULL) { // must be front of list146 if (elem->prev == NULL) { // must be front of list 150 147 list->head = elem; 151 148 } else { … … 167 164 168 165 /*****************************************************************************/ 166 169 167 /* 170 168 * Remove an element from a list 171 169 */ 172 bool psListRemove(psList * list, void *data,int which)173 { 174 psListElem *elem = NULL; // element to remove170 bool psListRemove(psList * list, void *data, int which) 171 { 172 psListElem *elem = NULL; // element to remove 175 173 int cursorIndex = 0; 176 174 177 175 if (list == NULL) { 178 psError(__func__, "list parameter found to be NULL in %s",__func__);176 psError(__func__, "list parameter found to be NULL in %s", __func__); 179 177 return false; 180 178 } 181 182 179 // get exclusive access to list so that other threads will not get in the way. 183 180 pthread_mutex_lock(&list->lock) … … 187 184 // search list for the data item. 188 185 189 int i = 0; // index 190 for (psListElem *ptr = list->head; ptr != NULL; ptr = ptr->next) { 186 int i = 0; // index 187 188 for (psListElem * ptr = list->head; ptr != NULL; ptr = ptr->next) { 191 189 if (ptr->data == data) { 192 190 which = i; … … 201 199 } 202 200 } 203 204 201 // position the list's cursor to the desired location 205 listSetIterator(list, which,false);202 listSetIterator(list, which, false); 206 203 elem = listGetIterator(list); 207 204 cursorIndex = listGetIteratorIndex(list); 208 205 209 206 if (elem == NULL) { 210 psError(__func__, "Couldn't position to given index (%d) to remove element from list.", which);207 psError(__func__, "Couldn't position to given index (%d) to remove element from list.", which); 211 208 return false; 212 209 } … … 214 211 list->size--; 215 212 216 if (elem->prev == NULL) { // head of list?213 if (elem->prev == NULL) { // head of list? 217 214 list->head = elem->next; 218 215 } else { … … 220 217 } 221 218 222 if (elem->next == NULL) { // tail of list?219 if (elem->next == NULL) { // tail of list? 223 220 list->tail = elem->prev; 224 221 … … 246 243 } 247 244 248 void psListSetIterator(psList * list, int where)249 { 250 listSetIterator(list, where,true);251 } 252 253 void listSetIterator(psList * list, int where, bool lockList)254 { 255 psListElem *cursor;245 void psListSetIterator(psList * list, int where) 246 { 247 listSetIterator(list, where, true); 248 } 249 250 void listSetIterator(psList * list, int where, bool lockList) 251 { 252 psListElem *cursor; 256 253 int position; 257 254 258 255 if (list == NULL) { 259 psError(__func__, "Unexpected null pointer for psList parameter (%s:%d).",__FILE__,__LINE__);256 psError(__func__, "Unexpected null pointer for psList parameter (%s:%d).", __FILE__, __LINE__); 260 257 return; 261 258 } … … 291 288 if (cursor != NULL) { 292 289 list->iter = cursor->prev; 293 list->iterIndex = position -1;290 list->iterIndex = position - 1; 294 291 } 295 292 break; … … 301 298 if (cursor != NULL) { 302 299 list->iter = cursor->next; 303 list->iterIndex = position +1;300 list->iterIndex = position + 1; 304 301 } 305 302 break; … … 309 306 310 307 default: 311 if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above312 psError(__func__, "Can't move to an unknown position. Not moving the iterator position.");308 if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above 309 psError(__func__, "Can't move to an unknown position. Not moving the iterator position."); 313 310 } else { 314 311 cursor = listGetIterator(list); 315 if (cursor == NULL) { // reset the iterator if it is invalid312 if (cursor == NULL) { // reset the iterator if it is invalid 316 313 list->iter = ITER_INIT_HEAD; 317 314 list->iterIndex = 0; … … 321 318 322 319 if (where < position) { 323 int diff = position-where; 324 for (int count=0;count < diff; count++) { 325 listSetIterator(list,PS_LIST_PREVIOUS,false); 320 int diff = position - where; 321 322 for (int count = 0; count < diff; count++) { 323 listSetIterator(list, PS_LIST_PREVIOUS, false); 326 324 } 327 325 } else { 328 int diff = where-position; 329 for (int count=0;count < diff; count++) { 330 listSetIterator(list,PS_LIST_NEXT,false); 326 int diff = where - position; 327 328 for (int count = 0; count < diff; count++) { 329 listSetIterator(list, PS_LIST_NEXT, false); 331 330 } 332 331 } … … 341 340 } 342 341 343 psListElem * listGetIterator(psList* list)342 psListElem *listGetIterator(psList * list) 344 343 { 345 344 if (list == NULL) { … … 349 348 if (list->iter == ITER_INIT_HEAD) { 350 349 return list->head; 351 } else 352 if (list->iter == ITER_INIT_TAIL) { 353 return list->tail; 354 } else { 355 return list->iter; 356 } 357 } 358 359 int listGetIteratorIndex(psList* list) 350 } else if (list->iter == ITER_INIT_TAIL) { 351 return list->tail; 352 } else { 353 return list->iter; 354 } 355 } 356 357 int listGetIteratorIndex(psList * list) 360 358 { 361 359 if (list->iter == ITER_INIT_HEAD) { 362 360 return 0; 363 } else 364 if (list->iter == ITER_INIT_TAIL) { 365 return list->size-1; 366 } else { 367 return list->iterIndex; 368 } 369 } 370 371 void* psListGet(psList* list,int which) 372 { 373 psListElem* element; 374 375 psListSetIterator(list,which); 361 } else if (list->iter == ITER_INIT_TAIL) { 362 return list->size - 1; 363 } else { 364 return list->iterIndex; 365 } 366 } 367 368 void *psListGet(psList * list, int which) 369 { 370 psListElem *element; 371 372 psListSetIterator(list, which); 376 373 element = listGetIterator(list); 377 374 … … 382 379 } 383 380 } 381 384 382 /* 385 383 * and now return the previous/next element of the list 386 384 */ 387 void *psListGetNext(psList * list)385 void *psListGetNext(psList * list) 388 386 { 389 387 return psListGet(list, PS_LIST_NEXT); 390 388 } 391 389 392 void *psListGetPrevious(psList * list)390 void *psListGetPrevious(psList * list) 393 391 { 394 392 return psListGet(list, PS_LIST_PREVIOUS); 395 393 } 396 394 397 void *psListGetCurrent(psList * list)395 void *psListGetCurrent(psList * list) 398 396 { 399 397 return psListGet(list, PS_LIST_CURRENT); … … 403 401 * Convert a psList to/from a psVoidPtrArray 404 402 */ 405 psArray * psListToArray(psList* restrict list)406 { 407 psListElem *ptr;403 psArray *psListToArray(psList * restrict list) 404 { 405 psListElem *ptr; 408 406 unsigned int n; 409 psArray *restrict arr;407 psArray *restrict arr; 410 408 411 409 if (list == NULL) { … … 431 429 } 432 430 433 psList * psArrayToList(psArray* arr)431 psList *psArrayToList(psArray * arr) 434 432 { 435 433 unsigned int n; 436 psList * list;// list of elements434 psList *list; // list of elements 437 435 438 436 if (arr == NULL) { … … 443 441 n = arr->n; 444 442 for (int i = 0; i < n; i++) { 445 psListAdd(list, arr->data[i],PS_LIST_TAIL);443 psListAdd(list, arr->data[i], PS_LIST_TAIL); 446 444 } 447 445 … … 449 447 } 450 448 451 452 psList* psListSort(psList* list, psComparePtrFcn compare) 453 { 454 psArray* arr; 449 psList *psListSort(psList * list, psComparePtrFcn compare) 450 { 451 psArray *arr; 452 455 453 if (list == NULL) { 456 454 return NULL; 457 455 } 458 459 456 // convert to indexable vector for use by qsort. 460 457 arr = psListToArray(list); 461 458 psFree(list); 462 459 463 arr = psArraySort(arr, compare);460 arr = psArraySort(arr, compare); 464 461 465 462 // convert back to linked list -
trunk/psLib/src/types/psList.h
r1228 r1407 1 1 #if !defined(PS_LIST_H) 2 # define PS_LIST_H2 # define PS_LIST_H 3 3 4 4 /** @file psList.h … … 10 10 * @ingroup LinkedList 11 11 * 12 * @version $Revision: 1. 9$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-0 7-15 22:18:02$12 * @version $Revision: 1.10 $ $Name: not supported by cvs2svn $ 13 * @date $Date: 2004-08-07 00:06:06 $ 14 14 * 15 15 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 16 */ 17 17 18 # include <pthread.h> // we need a mutex to make this stuff thread safe.19 # include <stdbool.h> // we use the bool type.18 # include <pthread.h> // we need a mutex to make this stuff thread safe. 19 # include <stdbool.h> // we use the bool type. 20 20 21 # include "psCompare.h"22 # include "psArray.h"21 # include "psCompare.h" 22 # include "psArray.h" 23 23 24 24 /** @addtogroup LinkedList … … 33 33 */ 34 34 enum { 35 PS_LIST_HEAD = 0, ///< at head36 PS_LIST_TAIL = -1, ///< at tail37 PS_LIST_PREVIOUS = -2, ///< previous element38 PS_LIST_CURRENT = -3, ///< current element39 PS_LIST_NEXT = -4, ///< next element40 PS_LIST_UNKNOWN = -5 ///< unknown position (should be last in enum list)35 PS_LIST_HEAD = 0, // /< at head 36 PS_LIST_TAIL = -1, // /< at tail 37 PS_LIST_PREVIOUS = -2, // /< previous element 38 PS_LIST_CURRENT = -3, // /< current element 39 PS_LIST_NEXT = -4, // /< next element 40 PS_LIST_UNKNOWN = -5 // /< unknown position (should be last in enum list) 41 41 }; 42 42 … … 44 44 typedef struct psListElem 45 45 { 46 struct psListElem *prev; ///< previous link in list47 struct psListElem *next; ///< next link in list48 void *data; ///< real data item46 struct psListElem *prev; // /< previous link in list 47 struct psListElem *next; // /< next link in list 48 void *data; // /< real data item 49 49 } 50 50 psListElem; … … 57 57 typedef struct 58 58 { 59 unsigned int size; ///< number of elements on list60 psListElem * head; ///< first element on list (may be NULL)61 psListElem * tail; ///< last element on list (may be NULL)62 psListElem * iter; ///< iteration cursor63 unsigned int iterIndex; ///< the numeric position of the iteration cursor in the list64 pthread_mutex_t lock; ///< mutex to lock a node during changes59 unsigned int size; // /< number of elements on list 60 psListElem *head; // /< first element on list (may be NULL) 61 psListElem *tail; // /< last element on list (may be NULL) 62 psListElem *iter; // /< iteration cursor 63 unsigned int iterIndex; // /< the numeric position of the iteration cursor in the list 64 pthread_mutex_t lock; // /< mutex to lock a node during changes 65 65 } 66 66 psList; … … 70 70 * @return psList* A new psList object. 71 71 */ 72 psList* psListAlloc( 73 void *data 74 ///< initial data item; may be NULL if no an empty psList is desired 75 ) 72 psList *psListAlloc(void *data 73 // /< initial data item; may be NULL if no an empty psList is desired 74 ) 76 75 ; 77 76 … … 81 80 * NULL, the return value will also be NULL. 82 81 */ 83 bool psListAdd( 84 psList* restrict list, ///< list to add to (if NULL, nothing is done) 85 void* data, ///< data item to add. If NULL, list is not modified. 86 int where ///< index, PS_LIST_HEAD, PS_LIST_TAIL, or numbered location. 87 ); 82 bool psListAdd(psList * restrict list, // /< list to add to (if NULL, nothing is done) 83 void *data, // /< data item to add. If NULL, list is not modified. 84 int where // /< index, PS_LIST_HEAD, PS_LIST_TAIL, or numbered location. 85 ); 88 86 89 87 /** Remove an item from a list. If which parameter is PS_LIST_UNKNOWN, … … 91 89 * @return bool TRUE if element is successfully removed, otherwise FALSE. 92 90 */ 93 bool psListRemove( 94 psList* restrict list, 95 ///< list to remove element from 96 void *data, 97 ///< if which is PS_LIST_UNKNOWN, data item to find and remove, otherwise this is ignored. 98 int which 99 ///< index of item, or PS_LIST_UNKNOWN, PS_LIST_NEXT, PS_LIST_PREV, or numbered location. 100 ); 91 bool psListRemove(psList * restrict list, 92 // /< list to remove element from 93 void *data, 94 // /< if which is PS_LIST_UNKNOWN, data item to find and remove, otherwise this is ignored. 95 int which 96 // /< index of item, or PS_LIST_UNKNOWN, PS_LIST_NEXT, PS_LIST_PREV, or numbered location. 97 ); 101 98 102 99 /** Retrieve an item from a list. … … 107 104 * NULL is returned. 108 105 */ 109 void* psListGet( 110 psList* restrict list, ///< list to retrieve element from 111 int which ///< index number, or PS_LIST_NEXT, PS_LIST_PREV, PS_LIST_UNKNOWN 112 ); 106 void *psListGet(psList * restrict list, // /< list to retrieve element from 107 int which // /< index number, or PS_LIST_NEXT, PS_LIST_PREV, PS_LIST_UNKNOWN 108 ); 113 109 114 110 /** Set the iterator of the list to a given position. If where is invalid the … … 116 112 * 117 113 */ 118 void psListSetIterator( 119 psList* restrict list, ///< list to retrieve element from 120 int where ///< index number, PS_LIST_HEAD, or PS_LIST_TAIL 121 ); 114 void psListSetIterator(psList * restrict list, // /< list to retrieve element from 115 int where // /< index number, PS_LIST_HEAD, or PS_LIST_TAIL 116 ); 122 117 123 118 /** Get next element relative to the iterator. This also moves the iterator to … … 128 123 * parameter was NULL. 129 124 */ 130 void* psListGetNext( 131 psList* restrict list ///< list to retrieve element from 132 ); 125 void *psListGetNext(psList * restrict list // /< list to retrieve element from 126 ); 133 127 134 128 /** Get current element according to the psList's iterator cursor. This does … … 139 133 * iterator is not valid or list parameter was NULL. 140 134 */ 141 void* psListGetCurrent( 142 psList* restrict list ///< list to retrieve element from 143 ); 135 void *psListGetCurrent(psList * restrict list // /< list to retrieve element from 136 ); 144 137 145 138 /** Get previous element relative to list's iterator. This also moves the … … 150 143 * parameter was NULL. 151 144 */ 152 void* psListGetPrevious( 153 psList* restrict list ///< list to retrieve element from 154 ); 145 void *psListGetPrevious(psList * restrict list // /< list to retrieve element from 146 ); 155 147 156 148 /** Convert a linked list to an array … … 159 151 * or NULL if the given dlist parameter is NULL. 160 152 */ 161 psArray* psListToArray( 162 psList *dlist ///< List to convert 163 ); 153 psArray *psListToArray(psList * dlist // /< List to convert 154 ); 164 155 165 156 /** Convert array to a doubly-linked list … … 168 159 * or NULL is the given arr parameter is NULL. 169 160 */ 170 psList* psArrayToList( 171 psArray* arr ///< vector to convert 172 ); 161 psList *psArrayToList(psArray * arr // /< vector to convert 162 ); 173 163 174 psList * psListSort(psList* list, psComparePtrFcn compare);164 psList *psListSort(psList * list, psComparePtrFcn compare); 175 165 176 166 /// @} End of DataGroup Functions 177 167 178 168 #endif 179 -
trunk/psLib/src/types/psMetadata.c
r1406 r1407 1 1 2 /** @file psMetadata.c 2 3 * … … 11 12 * @author Ross Harman, MHPCC 12 13 * 13 * @version $Revision: 1.1 4$ $Name: not supported by cvs2svn $14 * @date $Date: 2004-08-0 6 22:34:05$14 * @version $Revision: 1.15 $ $Name: not supported by cvs2svn $ 15 * @date $Date: 2004-08-07 00:06:06 $ 15 16 * 16 17 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii … … 18 19 19 20 /******************************************************************************/ 21 20 22 /* INCLUDE FILES */ 23 21 24 /******************************************************************************/ 22 25 #include<stdio.h> … … 34 37 #include "psString.h" 35 38 36 37 39 /******************************************************************************/ 40 38 41 /* DEFINE STATEMENTS */ 42 39 43 /******************************************************************************/ 40 44 … … 56 60 57 61 /******************************************************************************/ 62 58 63 /* TYPE DEFINITIONS */ 64 59 65 /******************************************************************************/ 60 66 … … 62 68 63 69 /*****************************************************************************/ 70 64 71 /* GLOBAL VARIABLES */ 72 65 73 /*****************************************************************************/ 66 74 … … 68 76 69 77 /*****************************************************************************/ 78 70 79 /* FILE STATIC VARIABLES */ 80 71 81 /*****************************************************************************/ 72 82 … … 74 84 75 85 /*****************************************************************************/ 86 76 87 /* FUNCTION IMPLEMENTATION - LOCAL */ 77 /*****************************************************************************/ 78 static void metadataItemFree( psMetadataItem *metadataItem ) 88 89 /*****************************************************************************/ 90 static void metadataItemFree(psMetadataItem * metadataItem) 79 91 { 80 92 psMetadataType type; … … 82 94 type = metadataItem->type; 83 95 84 if (metadataItem == NULL) {85 return ;86 } 87 88 psFree( metadataItem->name);89 psFree( metadataItem->comment);90 psFree( metadataItem->items);91 92 if (type == PS_META_STR ||96 if (metadataItem == NULL) { 97 return; 98 } 99 100 psFree(metadataItem->name); 101 psFree(metadataItem->comment); 102 psFree(metadataItem->items); 103 104 if (type == PS_META_STR || 93 105 type == PS_META_IMG || 94 type == PS_META_JPEG || 95 type == PS_META_PNG || 96 type == PS_META_ASTROM || 97 type == PS_META_UNKNOWN) { 98 psFree( metadataItem->data.V ); 99 } 100 } 101 102 static void metadataFree( psMetadata *metadata ) 103 { 104 if(metadata == NULL) { 105 return ; 106 } 107 psFree( metadata->list ); 108 psFree( metadata->table ); 109 } 110 111 /*****************************************************************************/ 106 type == PS_META_JPEG || type == PS_META_PNG || type == PS_META_ASTROM || type == PS_META_UNKNOWN) { 107 psFree(metadataItem->data.V); 108 } 109 } 110 111 static void metadataFree(psMetadata * metadata) 112 { 113 if (metadata == NULL) { 114 return; 115 } 116 psFree(metadata->list); 117 psFree(metadata->table); 118 } 119 120 /*****************************************************************************/ 121 112 122 /* FUNCTION IMPLEMENTATION - PUBLIC */ 113 /*****************************************************************************/ 114 115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... ) 123 124 /*****************************************************************************/ 125 126 psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...) 116 127 { 117 128 va_list argPtr; … … 119 130 120 131 // Get the variable list parameters to pass to allocation function 121 va_start( argPtr, comment);132 va_start(argPtr, comment); 122 133 123 134 // Call metadata item allocation 124 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);135 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 125 136 126 137 // Clean up stack after variable arguement has been used 127 va_end( argPtr);138 va_end(argPtr); 128 139 129 140 return metadataItem; 130 141 } 131 142 132 psMetadataItem *psMetadataItemAllocV( const char *name, psMetadataType type, const char *comment, va_list argPtr )133 { 134 psMetadataItem * metadataItem = NULL; 135 136 if(name == NULL) { 137 psError( __func__, "Null value for name not allowed" );138 return NULL;139 }140 143 psMetadataItem *psMetadataItemAllocV(const char *name, psMetadataType type, const char *comment, 144 va_list argPtr) 145 { 146 psMetadataItem *metadataItem = NULL; 147 148 if (name == NULL) { 149 psError(__func__, "Null value for name not allowed"); 150 return NULL; 151 } 141 152 // Allocate metadata item 142 metadataItem = ( psMetadataItem * ) psAlloc( sizeof( psMetadataItem ) ); 143 if(metadataItem == NULL) { 144 psAbort( __func__, "Failed to allocate memory" ); 145 } 146 153 metadataItem = (psMetadataItem *) psAlloc(sizeof(psMetadataItem)); 154 if (metadataItem == NULL) { 155 psAbort(__func__, "Failed to allocate memory"); 156 } 147 157 // Set deallocator 148 p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree);158 p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree); 149 159 150 160 // Allocate and set metadata item comment 151 metadataItem->comment = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);152 if (comment == NULL) {161 metadataItem->comment = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 162 if (comment == NULL) { 153 163 // Per SDRS, null isn't allowed, must use "" instead 154 strncpy( metadataItem->comment, "", MAX_STRING_LENGTH);164 strncpy(metadataItem->comment, "", MAX_STRING_LENGTH); 155 165 } else { 156 strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH);166 strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH); 157 167 } 158 168 159 169 // Set metadata item unique id 160 *( int* ) ( &metadataItem->id) = ++metadataId;170 *(int *)(&metadataItem->id) = ++metadataId; 161 171 162 172 // Set metadata item type … … 164 174 165 175 // Set metadata item value 166 switch (type) {176 switch (type) { 167 177 case PS_META_BOOL: 168 metadataItem->data.B = ( bool ) va_arg( argPtr, int ); 178 metadataItem->data.B = (bool) va_arg(argPtr, int); 179 169 180 break; 170 181 case PS_META_S32: 171 metadataItem->data.S32 = va_arg( argPtr, psS32);182 metadataItem->data.S32 = va_arg(argPtr, psS32); 172 183 break; 173 184 case PS_META_F32: 174 metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64);185 metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64); 175 186 break; 176 187 case PS_META_F64: 177 metadataItem->data.F64 = va_arg( argPtr, psF64);188 metadataItem->data.F64 = va_arg(argPtr, psF64); 178 189 break; 179 190 case PS_META_STR: 180 metadataItem->data.V = psStringNCopy( va_arg( argPtr, char* ), MAX_STRING_LENGTH ); 191 metadataItem->data.V = psStringNCopy(va_arg(argPtr, char *), MAX_STRING_LENGTH); 192 181 193 break; 182 194 case PS_META_IMG: … … 186 198 case PS_META_UNKNOWN: 187 199 default: 188 psError( __func__, "Invalid psMetadataType: %d", type);200 psError(__func__, "Invalid psMetadataType: %d", type); 189 201 } 190 202 191 203 // Allocate and set metadata item name 192 metadataItem->name = ( char * ) psAlloc( sizeof( char ) * MAX_STRING_LENGTH);193 vsprintf( metadataItem->name, name, argPtr);204 metadataItem->name = (char *)psAlloc(sizeof(char) * MAX_STRING_LENGTH); 205 vsprintf(metadataItem->name, name, argPtr); 194 206 195 207 // Allocate metadata items with same name. 196 metadataItem->items = psListAlloc( NULL);208 metadataItem->items = psListAlloc(NULL); 197 209 198 210 return metadataItem; 199 211 } 200 212 201 psMetadata *psMetadataAlloc( void)202 { 203 psList * list = NULL;213 psMetadata *psMetadataAlloc(void) 214 { 215 psList *list = NULL; 204 216 psHash *table = NULL; 205 217 psMetadata *metadata = NULL; 206 218 207 219 // Allocate metadata 208 metadata = ( psMetadata * ) psAlloc( sizeof( psMetadata ) ); 209 if(metadata == NULL) { 210 psAbort( __func__, "Failed to allocate metadata" ); 211 } 212 220 metadata = (psMetadata *) psAlloc(sizeof(psMetadata)); 221 if (metadata == NULL) { 222 psAbort(__func__, "Failed to allocate metadata"); 223 } 213 224 // Set deallocator 214 p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree);225 p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree); 215 226 216 227 // Allocate metadata's internal containers 217 list = ( psList * ) psListAlloc( NULL);218 if (list == NULL) {219 psAbort( __func__, "Failed to allocate list");220 } 221 222 table = ( psHash * ) psHashAlloc( 10);223 if (table == NULL) {224 psAbort( __func__, "Failed to allocate table");228 list = (psList *) psListAlloc(NULL); 229 if (list == NULL) { 230 psAbort(__func__, "Failed to allocate list"); 231 } 232 233 table = (psHash *) psHashAlloc(10); 234 if (table == NULL) { 235 psAbort(__func__, "Failed to allocate table"); 225 236 } 226 237 … … 231 242 } 232 243 233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem)234 { 235 char * key = NULL;244 bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem) 245 { 246 char *key = NULL; 236 247 psHash *mdTable = NULL; 237 248 psList *mdList = NULL; … … 239 250 psMetadataType type = PS_META_ITEM_SET; 240 251 241 if (md == NULL) {242 psError( __func__, "Null metadata collection not allowed");243 return false; 244 } 245 246 if (metadataItem == NULL) {247 psError( __func__, "Null metadata item not allowed");252 if (md == NULL) { 253 psError(__func__, "Null metadata collection not allowed"); 254 return false; 255 } 256 257 if (metadataItem == NULL) { 258 psError(__func__, "Null metadata item not allowed"); 248 259 return false; 249 260 } … … 252 263 253 264 mdTable = md->table; 254 if (mdTable == NULL) {255 psError( __func__, "Null metadata table not allowed");256 return false; 257 } 258 259 mdList = md->list; 260 if (mdList == NULL) {261 psError( __func__, "Null metadata list not allowed");265 if (mdTable == NULL) { 266 psError(__func__, "Null metadata table not allowed"); 267 return false; 268 } 269 270 mdList = md->list; 271 if (mdList == NULL) { 272 psError(__func__, "Null metadata list not allowed"); 262 273 return false; 263 274 } 264 275 265 276 key = metadataItem->name; 266 if(key == NULL) { 267 psError( __func__, "Null key item not allowed" ); 268 return false; 269 } 270 277 if (key == NULL) { 278 psError(__func__, "Null key item not allowed"); 279 return false; 280 } 271 281 // Check if key is already in table 272 value = ( psMetadataItem* ) psHashLookup( mdTable, key);273 if (value != NULL && type != PS_META_ITEM_SET) {282 value = (psMetadataItem *) psHashLookup(mdTable, key); 283 if (value != NULL && type != PS_META_ITEM_SET) { 274 284 275 285 // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so 276 286 // add the new metadata item to hash as a child of the existing metadata item folder node. 277 if(!psListAdd( value->items, metadataItem, where )) { 278 psError( __func__, "Couldn't add metadata item to items list. Name: %s", 279 metadataItem->name ); 287 if (!psListAdd(value->items, metadataItem, where)) { 288 psError(__func__, "Couldn't add metadata item to items list. Name: %s", metadataItem->name); 280 289 return false; 281 290 } 282 } else 283 if(value != NULL) { 284 285 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 286 // it will wipe out existing node. 287 psError( __func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 288 metadataItem->name ); 291 } else if (value != NULL) { 292 293 // The key was found and the new metadata item is a folder node. Don't add new metadata item, since 294 // it will wipe out existing node. 295 psError(__func__, "Metadata already exists in metadata collection. Item not added. Name: %s", 296 metadataItem->name); 297 return false; 298 } else { 299 300 // Duplicate key not found. Add new metadata item to metadata collection's hash 301 if (!psHashAdd(mdTable, key, metadataItem)) { 302 psError(__func__, "Couldn't add metadata item to metadata collection table. Name: %s", 303 metadataItem->name); 289 304 return false; 290 } else { 291 292 // Duplicate key not found. Add new metadata item to metadata collection's hash 293 if(!psHashAdd( mdTable, key, metadataItem )) { 294 psError( __func__, "Couldn't add metadata item to metadata collection table. Name: %s", 295 metadataItem->name ); 296 return false; 297 } 298 } 305 } 306 } 299 307 300 308 // Add all items to metadata collection's list, even if they have the same metadata item names 301 if (!psListAdd( md->list, metadataItem, where)) {302 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",303 metadataItem->name);309 if (!psListAdd(md->list, metadataItem, where)) { 310 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 311 metadataItem->name); 304 312 return false; 305 313 } … … 308 316 } 309 317 310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,311 const char *comment, ...)318 bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type, 319 const char *comment, ...) 312 320 { 313 321 va_list argPtr; 314 322 psMetadataItem *metadataItem = NULL; 315 323 316 va_start( argPtr, comment);317 metadataItem = psMetadataItemAllocV( name, type, comment, argPtr);318 va_end( argPtr);319 320 if (!psMetadataAddItem( md, where, metadataItem)) {321 psError( __func__, "Couldn't add metadata item to metadata collection list. Name: %s",322 metadataItem->name);323 psFree( metadataItem);324 return false; 325 } 326 327 // Decrement reference count, since the metadata item is now in metadata collection and no longer neededhere328 psMemDecrRefCounter( metadataItem);324 va_start(argPtr, comment); 325 metadataItem = psMetadataItemAllocV(name, type, comment, argPtr); 326 va_end(argPtr); 327 328 if (!psMetadataAddItem(md, where, metadataItem)) { 329 psError(__func__, "Couldn't add metadata item to metadata collection list. Name: %s", 330 metadataItem->name); 331 psFree(metadataItem); 332 return false; 333 } 334 // Decrement reference count, since the metadata item is now in metadata collection and no longer needed 335 // here 336 psMemDecrRefCounter(metadataItem); 329 337 330 338 return true; 331 339 } 332 340 333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key)341 bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key) 334 342 { 335 343 int numChildren = 0; … … 340 348 341 349 mdList = md->list; 342 if (mdList == NULL) {343 psError( __func__, "Null metadata list not allowed");350 if (mdList == NULL) { 351 psError(__func__, "Null metadata list not allowed"); 344 352 return false; 345 353 } 346 354 347 355 mdTable = md->table; 348 if(mdTable == NULL) { 349 psError( __func__, "Null metadata table not allowed" ); 350 return false; 351 } 352 356 if (mdTable == NULL) { 357 psError(__func__, "Null metadata table not allowed"); 358 return false; 359 } 353 360 // Select removal by key or index 354 if (key != NULL) {361 if (key != NULL) { 355 362 356 363 // Remove by key name 357 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);358 if (entry == NULL) {359 psError( __func__, "Couldn't find metadata item remove. Name: %s", key);364 entry = (psMetadataItem *) psHashLookup(mdTable, key); 365 if (entry == NULL) { 366 psError(__func__, "Couldn't find metadata item remove. Name: %s", key); 360 367 return false; 361 368 } 362 369 363 370 numChildren = entry->items->size; 364 if (entry->type == PS_META_ITEM_SET && numChildren > 0) {371 if (entry->type == PS_META_ITEM_SET && numChildren > 0) { 365 372 366 373 // Table entry has children. Entry and children must be removed from metadata collection's list 367 psListSetIterator( mdList, PS_LIST_HEAD);368 entryChild = psListGetCurrent( mdList);369 while (entryChild != NULL) {370 if (!psListRemove( entry->items, entryChild, PS_LIST_UNKNOWN)) {371 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);374 psListSetIterator(mdList, PS_LIST_HEAD); 375 entryChild = psListGetCurrent(mdList); 376 while (entryChild != NULL) { 377 if (!psListRemove(entry->items, entryChild, PS_LIST_UNKNOWN)) { 378 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 372 379 return false; 373 380 } 374 entryChild = psListGetNext( entry->items);381 entryChild = psListGetNext(entry->items); 375 382 } 376 383 } 377 378 384 // Remove entry from metadata collection's list 379 if (!psListRemove( mdList, entry, PS_LIST_UNKNOWN)) {380 psError( __func__, "Couldn't remove metadata item from list. Name: %s", key);385 if (!psListRemove(mdList, entry, PS_LIST_UNKNOWN)) { 386 psError(__func__, "Couldn't remove metadata item from list. Name: %s", key); 381 387 return false; 382 388 } 383 384 389 // Remove entry from metadata collection's table 385 if (!psHashRemove( mdTable, key)) {386 psError( __func__, "Couldn't remove metadata item from table. Name: %s", key);390 if (!psHashRemove(mdTable, key)) { 391 psError(__func__, "Couldn't remove metadata item from table. Name: %s", key); 387 392 return false; 388 393 } … … 390 395 391 396 // Remove by index 392 entry = psListGet( mdList, where);393 if (entry == NULL) {394 psError( __func__, "Couldn't find metadata item from list. Index: %d", where);397 entry = psListGet(mdList, where); 398 if (entry == NULL) { 399 psError(__func__, "Couldn't find metadata item from list. Index: %d", where); 395 400 return false; 396 401 } 397 402 398 403 key = entry->name; 399 if (key == NULL) {400 psError( __func__, "Null key name not allowed. Index: %d", where);404 if (key == NULL) { 405 psError(__func__, "Null key name not allowed. Index: %d", where); 401 406 return false; 402 407 } 403 404 408 // Use recursive remove, now that key is known 405 psMetadataRemove( md, PS_LIST_UNKNOWN, key);409 psMetadataRemove(md, PS_LIST_UNKNOWN, key); 406 410 } 407 411 … … 409 413 } 410 414 411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key)412 { 413 psHash * mdTable = NULL;415 psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key) 416 { 417 psHash *mdTable = NULL; 414 418 psMetadataItem *entry = NULL; 415 419 416 420 mdTable = md->table; 417 if (mdTable == NULL) {418 psError( __func__, "Null metadata table not allowed");419 return NULL; 420 } 421 422 if (key == NULL) {423 psError( __func__, "Null key name not allowed");424 return NULL; 425 } 426 427 entry = ( psMetadataItem* ) psHashLookup( mdTable, key);428 if (entry == NULL) {429 psError( __func__, "Could not find metadata item with given key. Key: %s", key);421 if (mdTable == NULL) { 422 psError(__func__, "Null metadata table not allowed"); 423 return NULL; 424 } 425 426 if (key == NULL) { 427 psError(__func__, "Null key name not allowed"); 428 return NULL; 429 } 430 431 entry = (psMetadataItem *) psHashLookup(mdTable, key); 432 if (entry == NULL) { 433 psError(__func__, "Could not find metadata item with given key. Key: %s", key); 430 434 return NULL; 431 435 } … … 434 438 } 435 439 436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where)437 { 438 psList * mdList = NULL;440 psMetadataItem *psMetadataGet(psMetadata * restrict md, int where) 441 { 442 psList *mdList = NULL; 439 443 psMetadataItem *entry = NULL; 440 444 441 445 mdList = md->list; 442 if (mdList == NULL) {443 psError( __func__, "Null metadata list not allowed");444 return NULL; 445 } 446 447 entry = ( psMetadataItem* ) psListGet( mdList, where);448 if (entry == NULL) {449 psError( __func__, "Couldn't find metadata item with given index. Index: %d", where);446 if (mdList == NULL) { 447 psError(__func__, "Null metadata list not allowed"); 448 return NULL; 449 } 450 451 entry = (psMetadataItem *) psListGet(mdList, where); 452 if (entry == NULL) { 453 psError(__func__, "Couldn't find metadata item with given index. Index: %d", where); 450 454 return NULL; 451 455 } … … 454 458 } 455 459 456 bool psMetadataSetIterator( psMetadata *restrict md, int where)457 { 458 psList * mdList = NULL;459 460 mdList = md->list; 461 if (mdList == NULL) {462 psError( __func__, "Null metadata list not allowed");463 return false; 464 } 465 466 psListSetIterator( mdList, where);460 bool psMetadataSetIterator(psMetadata * restrict md, int where) 461 { 462 psList *mdList = NULL; 463 464 mdList = md->list; 465 if (mdList == NULL) { 466 psError(__func__, "Null metadata list not allowed"); 467 return false; 468 } 469 470 psListSetIterator(mdList, where); 467 471 468 472 return true; 469 473 } 470 474 471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which)472 { 473 psList * mdList = NULL;475 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which) 476 { 477 psList *mdList = NULL; 474 478 psMetadataItem *entry = NULL; 475 479 476 480 mdList = md->list; 477 if (mdList == NULL) {478 psError( __func__, "Null metadata list not allowed");479 return NULL; 480 } 481 482 mdList = md->list; 483 if (mdList == NULL) {484 psError( __func__, "Null metadata list not allowed");485 return NULL; 486 } 487 488 psListSetIterator( mdList, which);489 entry = psListGetCurrent( mdList);490 while (entry != NULL) {491 if (!strncmp( match, entry->name, strlen( match ))) {481 if (mdList == NULL) { 482 psError(__func__, "Null metadata list not allowed"); 483 return NULL; 484 } 485 486 mdList = md->list; 487 if (mdList == NULL) { 488 psError(__func__, "Null metadata list not allowed"); 489 return NULL; 490 } 491 492 psListSetIterator(mdList, which); 493 entry = psListGetCurrent(mdList); 494 while (entry != NULL) { 495 if (!strncmp(match, entry->name, strlen(match))) { 492 496 493 497 // Match found 494 498 return entry; 495 499 } 496 entry = psListGetNext( mdList);500 entry = psListGetNext(mdList); 497 501 } 498 502 499 503 // Match not found 500 if (entry == NULL) {501 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);504 if (entry == NULL) { 505 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 502 506 } 503 507 … … 505 509 } 506 510 507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which)508 { 509 psList * mdList = NULL;511 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which) 512 { 513 psList *mdList = NULL; 510 514 psMetadataItem *entry = NULL; 511 515 512 516 mdList = md->list; 513 if (mdList == NULL) {514 psError( __func__, "Null metadata list not allowed");515 return NULL; 516 } 517 518 mdList = md->list; 519 if (mdList == NULL) {520 psError( __func__, "Null metadata list not allowed");521 return NULL; 522 } 523 524 psListSetIterator( mdList, which);525 entry = psListGetCurrent( mdList);526 while (entry != NULL) {527 if (!strncmp( match, entry->name, strlen( match ))) {517 if (mdList == NULL) { 518 psError(__func__, "Null metadata list not allowed"); 519 return NULL; 520 } 521 522 mdList = md->list; 523 if (mdList == NULL) { 524 psError(__func__, "Null metadata list not allowed"); 525 return NULL; 526 } 527 528 psListSetIterator(mdList, which); 529 entry = psListGetCurrent(mdList); 530 while (entry != NULL) { 531 if (!strncmp(match, entry->name, strlen(match))) { 528 532 529 533 // Match found 530 534 return entry; 531 535 } 532 entry = psListGetPrevious( mdList);536 entry = psListGetPrevious(mdList); 533 537 } 534 538 535 539 // Match not found 536 if (entry == NULL) {537 psError( __func__, "Couldn't find metadata item with given match. Match: %s", match);540 if (entry == NULL) { 541 psError(__func__, "Couldn't find metadata item with given match. Match: %s", match); 538 542 } 539 543 … … 541 545 } 542 546 543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem)547 void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem) 544 548 { 545 549 psMetadataType type; 546 550 547 if (fd == NULL) {548 psError( __func__, "Null file descriptor not allowed");549 return ;550 } 551 552 if (format == NULL) {553 psError( __func__, "Null format not allowed");554 return ;555 } 556 557 if (metadataItem == NULL) {558 psError( __func__, "Null metadata not allowed");559 return ;551 if (fd == NULL) { 552 psError(__func__, "Null file descriptor not allowed"); 553 return; 554 } 555 556 if (format == NULL) { 557 psError(__func__, "Null format not allowed"); 558 return; 559 } 560 561 if (metadataItem == NULL) { 562 psError(__func__, "Null metadata not allowed"); 563 return; 560 564 } 561 565 562 566 type = metadataItem->type; 563 567 564 switch (type) {568 switch (type) { 565 569 case PS_META_BOOL: 566 fprintf( fd, format, metadataItem->data.B);570 fprintf(fd, format, metadataItem->data.B); 567 571 break; 568 572 case PS_META_S32: 569 fprintf( fd, format, metadataItem->data.S32);573 fprintf(fd, format, metadataItem->data.S32); 570 574 break; 571 575 case PS_META_F32: 572 fprintf( fd, format, metadataItem->data.F32);576 fprintf(fd, format, metadataItem->data.F32); 573 577 break; 574 578 case PS_META_F64: 575 fprintf( fd, format, metadataItem->data.F64);579 fprintf(fd, format, metadataItem->data.F64); 576 580 break; 577 581 case PS_META_STR: 578 fprintf( fd, format, metadataItem->data.V);582 fprintf(fd, format, metadataItem->data.V); 579 583 break; 580 584 case PS_META_ITEM_SET: … … 585 589 case PS_META_UNKNOWN: 586 590 default: 587 psError( __func__, " Invalid psMetadataType to print: %d", type);588 } 589 } 590 591 psMetadata *psMetadataFReadHeader( psMetadata *output, char *extName, int extNum, fitsfile *fd)591 psError(__func__, " Invalid psMetadataType to print: %d", type); 592 } 593 } 594 595 psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd) 592 596 { 593 597 bool tempBool; 594 598 bool success; 595 599 char keyType; 596 char keyName[ FITS_LINE_SIZE];597 char keyValue[ FITS_LINE_SIZE];598 char keyComment[ FITS_LINE_SIZE];599 char fitsErr[ MAX_STRING_LENGTH];600 char keyName[FITS_LINE_SIZE]; 601 char keyValue[FITS_LINE_SIZE]; 602 char keyComment[FITS_LINE_SIZE]; 603 char fitsErr[MAX_STRING_LENGTH]; 600 604 int i; 601 605 int hduType = 0; … … 605 609 psMetadataType metadataItemType; 606 610 607 if(fd == NULL) { 608 psError( __func__, "Null FITS file descriptor not allowed" ); 609 return NULL; 610 } 611 612 if(extName == NULL && extNum == 0) { 613 psError( __func__, "Null extName and extNum = 0 not allowed" ); 614 return NULL; 615 } else 616 if(extName && extNum) { 617 psError( __func__, "Both extName and extNum arguments should not have non zero values." ); 618 return NULL; 619 } 620 611 if (fd == NULL) { 612 psError(__func__, "Null FITS file descriptor not allowed"); 613 return NULL; 614 } 615 616 if (extName == NULL && extNum == 0) { 617 psError(__func__, "Null extName and extNum = 0 not allowed"); 618 return NULL; 619 } else if (extName && extNum) { 620 psError(__func__, "Both extName and extNum arguments should not have non zero values."); 621 return NULL; 622 } 621 623 // Allocate metadata if user didn't 622 if (output == NULL) {624 if (output == NULL) { 623 625 output = psMetadataAlloc(); 624 626 } 625 626 627 // Move to user designated HDU number or HDU name in FITS file. HDU numbers starts at one. 627 if (extName != NULL) {628 if (fits_movnam_hdu( fd, ANY_HDU, extName, 0, &status) != 0) {628 if (extName != NULL) { 629 if (fits_movnam_hdu(fd, ANY_HDU, extName, 0, &status) != 0) { 629 630 FITS_ERROR("FITS error while locating header %s: %s", extName); 630 631 } 631 632 } else { 632 if (fits_movabs_hdu( fd, extNum, &hduType, &status) != 0) {633 if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) { 633 634 FITS_ERROR("FITS error while locating header %d: %s", extNum); 634 635 } … … 636 637 637 638 // Get number of key names 638 if (fits_get_hdrpos( fd, &numKeys, &keyNum, &status) != 0) {639 if (fits_get_hdrpos(fd, &numKeys, &keyNum, &status) != 0) { 639 640 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 640 641 } 641 642 642 // Get each key name. Keywords start at one. 643 for (i = 1; i <= numKeys; i++) {644 if (fits_read_keyn( fd, i, keyName, keyValue, keyComment, &status) != 0) {643 for (i = 1; i <= numKeys; i++) { 644 if (fits_read_keyn(fd, i, keyName, keyValue, keyComment, &status) != 0) { 645 645 FITS_ERROR("FITS error while reading key %d: %s", keyNum); 646 646 } 647 if (fits_get_keytype( keyValue, &keyType, &status) != 0) {648 fits_get_errstatus( status, fitsErr);649 if (status != VALUE_UNDEFINED) {647 if (fits_get_keytype(keyValue, &keyType, &status) != 0) { 648 fits_get_errstatus(status, fitsErr); 649 if (status != VALUE_UNDEFINED) { 650 650 FITS_ERROR("FITS error while determining key %d type: %s", keyNum); 651 651 } else { 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and HISTORY 652 // Some keywords are still valid even though they don't have a type, like COMMENTS and 653 // HISTORY 653 654 keyType = 'C'; 654 655 status = 0; … … 656 657 } 657 658 658 switch (keyType) {659 switch (keyType) { 659 660 case 'I': 660 661 metadataItemType = PS_META_S32; 661 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atoi( keyValue ) ); 662 success = 663 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 664 atoi(keyValue)); 662 665 break; 663 666 case 'F': 664 667 metadataItemType = PS_META_F64; 665 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, atof( keyValue ) ); 668 success = 669 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, 670 atof(keyValue)); 666 671 break; 667 672 case 'C': 668 673 metadataItemType = PS_META_STR; 669 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue ); 674 success = 675 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, keyValue); 670 676 break; 671 677 case 'L': 672 678 metadataItemType = PS_META_BOOL; 673 tempBool = ( keyValue[ 0 ] == 'T' ) ? 1 : 0; 674 success = psMetadataAdd( output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool ); 679 tempBool = (keyValue[0] == 'T') ? 1 : 0; 680 success = 681 psMetadataAdd(output, PS_LIST_TAIL, keyName, metadataItemType, keyComment, tempBool); 675 682 break; 676 683 case 'U': 677 684 case 'X': 678 685 default: 679 psError( __func__, "Invalid psMetadataType: %c", keyType);686 psError(__func__, "Invalid psMetadataType: %c", keyType); 680 687 return output; 681 688 } 682 689 683 if (!success) {684 psError( __func__, "Failed to add metadata item. Name: %s", keyName);690 if (!success) { 691 psError(__func__, "Failed to add metadata item. Name: %s", keyName); 685 692 return output; 686 693 } -
trunk/psLib/src/types/psMetadata.h
r1394 r1407 1 1 2 /** @file psMetadata.h 2 3 * … … 10 11 * @author Ross Harman, MHPCC 11 12 * 12 * @version $Revision: 1.1 5$ $Name: not supported by cvs2svn $13 * @date $Date: 2004-08-0 5 20:55:22$13 * @version $Revision: 1.16 $ $Name: not supported by cvs2svn $ 14 * @date $Date: 2004-08-07 00:06:06 $ 14 15 * 15 16 * Copyright 2004 Maui High Performance Computing Center, University of Hawaii 16 17 */ 17 18 #ifndef PS_METADATA_H 18 # define PS_METADATA_H19 20 # include <stdarg.h>21 # include <stdio.h>22 # include <fitsio.h>23 24 # include "psHash.h"25 # include "psList.h"19 # define PS_METADATA_H 20 21 # include <stdarg.h> 22 # include <stdio.h> 23 # include <fitsio.h> 24 25 # include "psHash.h" 26 # include "psList.h" 26 27 27 28 /// @addtogroup Metadata … … 33 34 */ 34 35 typedef enum { 35 PS_META_ITEM_SET = 0, ///< Null. Metadata is in psMetadataItem.items36 PS_META_BOOL, ///< Boolean data.37 PS_META_S32, ///< Signed 32-bit integer data.38 PS_META_F32, ///< Single-precision float data.39 PS_META_F64, ///< Double-precision float data.40 PS_META_STR, ///< String data (Stored in as void *).41 PS_META_IMG, ///< Image data (Stored in as void *).42 PS_META_JPEG, ///< JPEG data (Stored in as void .43 PS_META_PNG, ///< PNG data (Stored in as void *).44 PS_META_ASTROM, ///< Astrometric coefficients (Stored in as void *).45 PS_META_UNKNOWN, ///< Other data (Stored in as void *).46 PS_META_NTYPE ///< Number of types. Must be last.36 PS_META_ITEM_SET = 0, // /< Null. Metadata is in psMetadataItem.items 37 PS_META_BOOL, // /< Boolean data. 38 PS_META_S32, // /< Signed 32-bit integer data. 39 PS_META_F32, // /< Single-precision float data. 40 PS_META_F64, // /< Double-precision float data. 41 PS_META_STR, // /< String data (Stored in as void *). 42 PS_META_IMG, // /< Image data (Stored in as void *). 43 PS_META_JPEG, // /< JPEG data (Stored in as void . 44 PS_META_PNG, // /< PNG data (Stored in as void *). 45 PS_META_ASTROM, // /< Astrometric coefficients (Stored in as void *). 46 PS_META_UNKNOWN, // /< Other data (Stored in as void *). 47 PS_META_NTYPE // /< Number of types. Must be last. 47 48 } psMetadataType; 48 49 … … 54 55 typedef struct psMetadataItem 55 56 { 56 const int id; ///< Unique ID for metadata item. 57 char *restrict name; ///< Name of metadata item. 58 psMetadataType type; ///< Type of metadata item. 59 union 60 { 57 const int id; // /< Unique ID for metadata item. 58 char *restrict name; // /< Name of metadata item. 59 psMetadataType type; // /< Type of metadata item. 60 union { 61 61 bool B; 62 psS32 S32; ///< Signed 32-bit integer data.63 psF32 F32; ///< Single-precision float data.64 psF64 F64; ///< Double-precision float data.65 psPTR V; ///< Pointer to other type of data.66 } data; ///< Union for data types.67 char *comment; ///< Optional comment ("", not NULL).68 psList *restrict items; ///< List of psMetadataItems with same name.62 psS32 S32; // /< Signed 32-bit integer data. 63 psF32 F32; // /< Single-precision float data. 64 psF64 F64; // /< Double-precision float data. 65 psPTR V; // /< Pointer to other type of data. 66 } data; // /< Union for data types. 67 char *comment; // /< Optional comment ("", not NULL). 68 psList *restrict items; // /< List of psMetadataItems with same name. 69 69 } 70 70 psMetadataItem; … … 78 78 typedef struct psMetadata 79 79 { 80 psList *restrict list;81 psHash *restrict table;80 psList *restrict list; 81 psHash *restrict table; 82 82 } 83 83 psMetadata; 84 84 85 86 85 /*****************************************************************************/ 86 87 87 /* FUNCTION PROTOTYPES */ 88 88 89 /*****************************************************************************/ 89 90 … … 101 102 * @return psMetadataItem*: Pointer metadata item. 102 103 */ 103 psMetadataItem *psMetadataItemAlloc( 104 const char *name, ///< Name of metadata item. 105 psMetadataType type, ///< Type of metadata item. 106 const char *comment, ///< Comment for metadata item. 107 ... ///< Arguments for name formatting and metadata item data. 108 ); 104 psMetadataItem *psMetadataItemAlloc(const char *name, // /< Name of metadata item. 105 psMetadataType type, // /< Type of metadata item. 106 const char *comment, // /< Comment for metadata item. 107 ... // /< Arguments for name formatting and metadata item data. 108 ); 109 109 110 110 /** Create a metadata item with va_list. … … 121 121 * @return psMetadataItem*: Pointer metadata item. 122 122 */ 123 psMetadataItem *psMetadataItemAllocV( 124 const char *name, ///< Name of metadata item.125 psMetadataType type, ///< Type ofmetadata item.126 const char *comment, ///< Comment for metadata item.127 va_list list ///< Arguments for name formatting and metadata itemdata.128 );123 psMetadataItem *psMetadataItemAllocV(const char *name, // /< Name of metadata item. 124 psMetadataType type, // /< Type of metadata item. 125 const char *comment, // /< Comment for metadata item. 126 va_list list // /< Arguments for name formatting and metadata item 127 // data. 128 ); 129 129 130 130 /** Create a metadata collection. … … 134 134 * @return psMetadata*: Pointer metadata. 135 135 */ 136 psMetadata *psMetadataAlloc( 137 void ///< Void. 138 ); 136 psMetadata *psMetadataAlloc(void // /< Void. 137 ); 139 138 140 139 /** Add existing metadata item to metadata collection. … … 144 143 * @return bool: True for success, false for failure. 145 144 */ 146 bool psMetadataAddItem( 147 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 148 int where, ///< Location to be added. 149 psMetadataItem *restrict item ///< Metadata item to be added. 150 ); 145 bool psMetadataAddItem(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 146 int where, // /< Location to be added. 147 psMetadataItem * restrict item // /< Metadata item to be added. 148 ); 151 149 152 150 /** Create and add a metadata item to metadata collection. … … 156 154 * @return bool: True for success, false for failure. 157 155 */ 158 bool psMetadataAdd( 159 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 160 int where, ///< Location to be added. 161 const char *name, ///< Name of metadata item. 162 psMetadataType type, ///< Type of metadata item. 163 const char *comment, ///< Comment for metadata item. 164 ... ///< Arguments for name formatting and metadata item data. 165 ); 156 bool psMetadataAdd(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 157 int where, // /< Location to be added. 158 const char *name, // /< Name of metadata item. 159 psMetadataType type, // /< Type of metadata item. 160 const char *comment, // /< Comment for metadata item. 161 ... // /< Arguments for name formatting and metadata item data. 162 ); 166 163 167 164 /** Remove an item from metadata collection. … … 174 171 * @return bool: True for success, false for failure. 175 172 */ 176 bool psMetadataRemove( 177 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 178 int where, ///< Location to be removed. 179 const char *restrict key ///< Name of metadata key. 180 ); 173 bool psMetadataRemove(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 174 int where, // /< Location to be removed. 175 const char *restrict key // /< Name of metadata key. 176 ); 181 177 182 178 /** Find an item in the metadata collection based on key name. … … 187 183 * @return psMetadataItem*: Pointer metadata item. 188 184 */ 189 psMetadataItem *psMetadataLookup( 190 psMetadata *restrict md, ///< Metadata collection to insert metadatitem.191 const char *restrict key ///< Name of metadata key.192 );185 psMetadataItem *psMetadataLookup(psMetadata * restrict md, // /< Metadata collection to insert metadat 186 // item. 187 const char *restrict key // /< Name of metadata key. 188 ); 193 189 194 190 /** Find an item in the metadata collection based on list index. … … 198 194 * @return psMetadataItem*: Pointer metadata item. 199 195 */ 200 psMetadataItem *psMetadataGet( 201 psMetadata *restrict md, ///< Metadata collection to insert metadat item. 202 int where ///< Location to be retrieved. 203 ); 196 psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item. 197 int where // /< Location to be retrieved. 198 ); 204 199 205 200 /** Set or reset metadata iterator. … … 209 204 * @return void: void. 210 205 */ 211 bool psMetadataSetIterator( 212 psMetadata *restrict md, ///< Metadata collection to iterate. 213 int where ///< Location of iterator. 214 ); 206 bool psMetadataSetIterator(psMetadata * restrict md, // /< Metadata collection to iterate. 207 int where // /< Location of iterator. 208 ); 215 209 216 210 /** Get next metadata item. … … 220 214 * @return psMetadataItem*: Pointer metadata item. 221 215 */ 222 psMetadataItem *psMetadataGetNext( 223 psMetadata *restrict md, ///< Metadata collection to iterate. 224 const char *restrict match, ///< Beginning of key name. 225 int which ///< Iterator to be used. 226 ); 216 psMetadataItem *psMetadataGetNext(psMetadata * restrict md, // /< Metadata collection to iterate. 217 const char *restrict match, // /< Beginning of key name. 218 int which // /< Iterator to be used. 219 ); 227 220 228 221 /** Get previous metadata item. … … 232 225 * @return psMetadataItem*: Pointer metadata item. 233 226 */ 234 psMetadataItem *psMetadataGetPrevious( 235 psMetadata *restrict md, ///< Metadata collection to iterate. 236 const char *restrict match, ///< Beginning of key name. 237 int which ///< Iterator to be used. 238 ); 227 psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, // /< Metadata collection to iterate. 228 const char *restrict match, // /< Beginning of key name. 229 int which // /< Iterator to be used. 230 ); 239 231 240 232 /** Print metadata item to file. … … 248 240 * @return psMetadataItem*: Pointer metadata item. 249 241 */ 250 void psMetadataItemPrint( 251 FILE *fd, ///< Pointer to file to write metadata item. 252 const char *format, ///< Format to print metadata item. 253 const psMetadataItem *restrict metadataItem ///< Metadata item to print. 254 ); 242 void psMetadataItemPrint(FILE * fd, // /< Pointer to file to write metadata item. 243 const char *format, // /< Format to print metadata item. 244 const psMetadataItem * restrict metadataItem // /< Metadata item to print. 245 ); 255 246 256 247 /** Read metadata header. … … 261 252 * @return psMetadata*: Pointer metadata. 262 253 */ 263 psMetadata *psMetadataReadHeader( 264 psMetadata *output, ///< Resulting metadata from read. 265 char *extname, ///< File name extension string. 266 int extnum, ///< File name extension number. Starts at 1. 267 char *filename ///< Name of file to read. 268 ); 254 psMetadata *psMetadataReadHeader(psMetadata * output, // /< Resulting metadata from read. 255 char *extname, // /< File name extension string. 256 int extnum, // /< File name extension number. Starts at 1. 257 char *filename // /< Name of file to read. 258 ); 269 259 270 260 /** Read metadata header. … … 274 264 * @return psMetadata*: Pointer metadata. 275 265 */ 276 psMetadata *psMetadataFReadHeader( 277 psMetadata *output, ///< Resulting metadata from read.278 char *extName, ///< File name extension string.279 int extNum, ///< File name extension number.280 fitsfile *fd ///< Pointer to file to read.281 ); 266 psMetadata *psMetadataFReadHeader(psMetadata * output, // /< Resulting metadata from read. 267 char *extName, // /< File name extension string. 268 int extNum, // /< File name extension number. 269 fitsfile * fd // /< Pointer to file to read. 270 ); 271 282 272 /// @} 283 273
Note:
See TracChangeset
for help on using the changeset viewer.
