IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 1407


Ignore:
Timestamp:
Aug 6, 2004, 2:06:06 PM (22 years ago)
Author:
desonia
Message:

another attempt to get astyle to get it right.

Location:
trunk/psLib/src
Files:
110 edited

Legend:

Unmodified
Added
Removed
  • trunk/psLib/src/astro/psCoord.c

    r1406 r1407  
     1
    12/** @file  psCoord.c
    23*
     
    1011*  @author George Gusciora, MHPCC
    1112*
    12 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-06 22:34:05 $
     13*  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728#include <float.h>
    2829
    29 static float cot( float x );
    30 static float arg( float x, float y );
     30static float cot(float x);
     31static float arg(float x, float y);
    3132
    3233// 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 
     34psPlane *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}
    5147
    5248// This transformation takes into account parameters beyond an objects
    5349// 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 
     50psPlane *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}
    7970
    8071// 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 );
     72psSphereTransform *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);
    8978    tmp->Xo = Xo;
    9079    tmp->xo = xo;
    9180
    92     return ( tmp );
     81    return (tmp);
    9382}
    9483
     
    10089// there are no typo's.
    10190
    102 psSphere *psSphereTransformApply( psSphere *out,
    103                                   const psSphereTransform *transform,
    104                                   const psSphere *coord )
     91psSphere *psSphereTransformApply(psSphere * out, const psSphereTransform * transform, const psSphere * coord)
    10592{
    10693    double sinY = 0.0;
     
    11299    double dx = 0.0;
    113100
    114     if ( out == NULL ) {
    115         out = ( psSphere * ) psAlloc( sizeof( psSphere ) );
     101    if (out == NULL) {
     102        out = (psSphere *) psAlloc(sizeof(psSphere));
    116103    }
    117104
     
    119106    y = coord->d;
    120107    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
     119psSphereTransform *psSphereTransformICRStoEcliptic(psTime time)
     120{
     121    struct tm *tmTime = psTimeToTM(time);
     122    double year = (double)(1900 + tmTime->tm_year);
    137123    double T = year / 100.0;
    138124    double phi = -23.452294 + 0.013013 * T + 0.000001639 * T * T - 0.000000503 * T * T * T;
     
    140126    double xo = 0.0;
    141127
    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
     131psSphereTransform *psSphereTransformEcliptictoICRS(psTime time)
     132{
     133    struct tm *tmTime = psTimeToTM(time);
     134    double year = (double)(1900 + tmTime->tm_year);
    149135    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;
    151137    double Xo = 0.0;
    152138    double xo = 0.0;
    153139
    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
     143psSphereTransform *psSphereTransformICRStoGalatic(void)
     144{
     145    return (psSphereTransformAlloc(62.6, 282.25, 33.0));
     146}
     147
     148psSphereTransform *psSphereTransformGalatictoICRS(void)
     149{
     150    return (psSphereTransformAlloc(-62.6, 33.0, 282.25));
    165151}
    166152
    167153// XXX: Is this the correct way to calculate this?
    168 float cot( float x )
    169 {
    170     return ( 1.0 / atan( x ) );
     154float cot(float x)
     155{
     156    return (1.0 / atan(x));
    171157}
    172158
    173159// 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 );
     160float 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);
    194176}
    195177
    196178// XXX: Waiting for the definition of the PS_PROJ_PAR projection.
    197179// XXX: Waiting for the definition of the PS_PROJ_GLS projection.
    198 psPlane *psProject( const psSphere *coord,
    199                     const psProjection *projection )
     180psPlane *psProject(const psSphere * coord, const psProjection * projection)
    200181{
    201182    float R = 0.0;
    202183    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);
    244218}
    245219
    246220// XXX: Waiting for the definition of the PS_PROJ_PAR projection.
    247221// XXX: Waiting for the definition of the PS_PROJ_GLS projection.
    248 psSphere *psDeproject( const psPlane *coord,
    249                        const psProjection *projection )
     222psSphere *psDeproject(const psPlane * coord, const psProjection * projection)
    250223{
    251224    float R = 0.0;
     
    253226    float chu1 = 0.0;
    254227    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);
    299265}
    300266
    301267// XXX: Do I need to check for unacceptable transformation parameters?
    302268// 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;
     269psSphere *psSphereGetOffset(const psSphere * restrict position1,
     270                            const psSphere * restrict position2,
     271                            psSphereOffsetMode mode, psSphereOffsetUnit unit)
     272{
     273    // psPlane *lin;
    309274    psProjection proj;
    310275    psSphere *tmp;
     
    312277    double tmpD = 0.0;
    313278
    314     if ( mode == PS_LINEAR ) {
     279    if (mode == PS_LINEAR) {
    315280        // XXX: I have no idea how to construct this.  Maybe project both
    316281        // sperical positions onto the plane, set the origin at one of the
     
    318283
    319284        // 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)?
    321286        proj.R = position1->r;
    322287        proj.D = position1->d;
     
    325290        proj.type = PS_PROJ_TAN;
    326291
    327         //        lin = psProject(position2, proj);
    328         //        tmp = psDeproject(lin, proj);
     292        // lin = psProject(position2, proj);
     293        // tmp = psDeproject(lin, proj);
    329294
    330295        // 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);
    361313        }
    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}
    366326
    367327// XXX: Do I need to check for unacceptable transformation parameters?
    368328// Maybe, if the points are on the North/South Pole, etc?
    369329// 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 )
     330psSphere *psSphereSetOffset(const psSphere * restrict position,
     331                            const psSphere * restrict offset,
     332                            psSphereOffsetMode mode, psSphereOffsetUnit unit)
    374333{
    375334    psPlane lin;
     
    379338    double tmpD = 0.0;
    380339
    381     if ( mode == PS_LINEAR ) {
     340    if (mode == PS_LINEAR) {
    382341        proj.R = position->r;
    383342        proj.D = position->d;
     
    389348        lin.y = offset->d;
    390349
    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);
    424368        }
    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
    12/** @file  psCoord.h
    23*
     
    1011*  @author George Gusciora, MHPCC
    1112*
    12 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-05 19:38:51 $
     13*  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617*/
    1718
    18 # ifndef PS_COORD_H
    19 # define PS_COORD_H
    20 
    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"
    2728
    2829/// @addtogroup CoordinateTransform
     
    3839typedef struct
    3940{
    40     double x;      ///< x position
    41     double y;      ///< y position
    42     double xErr;   ///< Error in x position
    43     double yErr;   ///< Error in y position
     41    double x;                   // /< x position
     42    double y;                   // /< y position
     43    double xErr;                // /< Error in x position
     44    double yErr;                // /< Error in y position
    4445}
    4546psPlane;
     
    5455typedef struct
    5556{
    56     double r;      ///< RA
    57     double d;      ///< Dec
    58     double rErr;   ///< Error in RA
    59     double dErr;   ///< Error in Dec
     57    double r;                   // /< RA
     58    double d;                   // /< Dec
     59    double rErr;                // /< Error in RA
     60    double dErr;                // /< Error in Dec
    6061}
    6162psSphere;
     
    7172typedef struct
    7273{
    73     psDPolynomial2D *x;                ///< 2D polynomial transform of X coordinates
    74     psDPolynomial2D *y;                ///< 2D polynomial transform of Y coordinates
     74    psDPolynomial2D *x;         // /< 2D polynomial transform of X coordinates
     75    psDPolynomial2D *y;         // /< 2D polynomial transform of Y coordinates
    7576}
    7677psPlaneTransform;
     
    9091typedef struct
    9192{
    92     psDPolynomial4D *x;                ///< 4D polynomial transform of X coordinates
    93     psDPolynomial4D *y;                ///< 4D polynomial transform of Y coordinates
     93    psDPolynomial4D *x;         // /< 4D polynomial transform of X coordinates
     94    psDPolynomial4D *y;         // /< 4D polynomial transform of Y coordinates
    9495}
    9596psPlaneDistort;
     
    107108typedef struct
    108109{
    109     double sinPhi;                    ///< sin of North Pole lattitude
    110     double cosPhi;                    ///< cos of North Pole lattitude
    111     double Xo;                        ///< First PT of Ares lon
    112     double xo;                        ///< First PT of Ares equiv lon
     110    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
    113114}
    114115psSphereTransform;
     
    120121 */
    121122typedef enum {
    122     PS_PROJ_TAN,        ///< Tangent projection
    123     PS_PROJ_SIN,        ///< Sine projection
    124     PS_PROJ_AIT,        ///< Aitoff projection
    125     PS_PROJ_PAR,        ///< Par projection
    126     PS_PROJ_GLS,        ///< GLS projection
    127     PS_PROJ_CAR,        ///< CAR projection
    128     PS_PROJ_MER,        ///< MER projection
    129     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.
    130131} psProjectionType;
    131132
     
    137138typedef struct
    138139{
    139     double R;     ///< Coordinates of projection center
    140     double D;     ///< Coordinates of projection center
    141     double Xs;    ///< plate-scale in X direction
    142     double Ys;    ///< plate-scale in Y direction
    143     psProjectionType type;  ///< Projection type
     140    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
    144145}
    145146psProjection;
     
    151152 */
    152153typedef enum {
    153     PS_SPHERICAL,                      ///< offset corresponds to an angular offset
    154     PS_LINEAR                          ///< offset corresponds to a linear offset
     154    PS_SPHERICAL,               // /< offset corresponds to an angular offset
     155    PS_LINEAR                   // /< offset corresponds to a linear offset
    155156} psSphereOffsetMode;
    156157
     
    161162 */
    162163typedef enum {
    163     PS_ARCSEC,                         ///< Arcseconds
    164     PS_ARCMIN,                         ///< Arcminutes
    165     PS_DEGREE,                         ///< Degrees
    166     PS_RADIAN                          ///< Radians
     164    PS_ARCSEC,                  // /< Arcseconds
     165    PS_ARCMIN,                  // /< Arcminutes
     166    PS_DEGREE,                  // /< Degrees
     167    PS_RADIAN                   // /< Radians
    167168} psSphereOffsetUnit;
    168169
     
    170171 *
    171172 */
    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 );
     173psPlane *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                              );
    177177
    178178/** Applies the psPlaneDistort transform to a specified coordinate
    179179 *
    180180 */
    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 );
     181psPlane *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                            );
    188187
    189188/** Allocator for psSphereTransform
    190189 *
    191190 */
    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 
     191psSphereTransform *psSphereTransformAlloc(double NPlat, // /< north pole latitude
     192        double Xo,    // /< First PT of Ares lon
     193        double xo     // /< First PT of Ares equiv lon
     194                                         );
    198195
    199196/** Applies the psSphereTransform transform for a specified coordinate
    200197 *
    201198 */
    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 );
     199psSphere *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
     205psSphereTransform *psSphereTransformICRStoEcliptic(psTime time);
     206
     207psSphereTransform *psSphereTransformEcliptictoICRS(psTime time);
     208
     209psSphereTransform *psSphereTransformICRStoGalatic(void);
     210
     211psSphereTransform *psSphereTransformGalatictoICRS(void);
     212
     213psPlane *psProject(const psSphere * coord, const psProjection * projection);
     214
     215psSphere *psDeproject(const psPlane * coord, const psProjection * projection);
     216
     217psSphere *psSphereGetOffset(const psSphere * restrict position1,
     218                            const psSphere * restrict position2,
     219                            psSphereOffsetMode mode, psSphereOffsetUnit unit);
     220
     221psSphere *psSphereSetOffset(const psSphere * restrict position,
     222                            const psSphere * restrict offset,
     223                            psSphereOffsetMode mode, psSphereOffsetUnit unit);
    243224
    244225/// @}
  • trunk/psLib/src/astro/psTime.c

    r1406 r1407  
     1
    12/** @file  psTime.c
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-08-06 22:34:05 $
     15 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1819 */
    1920
    20 
    2121/******************************************************************************/
     22
    2223/*  INCLUDE FILES                                                             */
     24
    2325/******************************************************************************/
    2426
     
    3234
    3335/******************************************************************************/
     36
    3437/*  DEFINE STATEMENTS                                                         */
     38
    3539/******************************************************************************/
    3640
     
    7377}                                                                                                            \
    7478
     79
    7580/******************************************************************************/
     81
    7682/*  TYPE DEFINITIONS                                                          */
     83
    7784/******************************************************************************/
    7885
     
    8087
    8188/*****************************************************************************/
     89
    8290/*  GLOBAL VARIABLES                                                         */
     91
    8392/*****************************************************************************/
    8493
     
    8695
    8796/*****************************************************************************/
     97
    8898/*  FILE STATIC VARIABLES                                                    */
     99
    89100/*****************************************************************************/
    90101
     
    119130
    120131// 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 /*****************************************************************************/
     132static 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
    195183/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     184
    196185/*****************************************************************************/
    197186
     
    199188
    200189/*****************************************************************************/
     190
    201191/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     192
    202193/*****************************************************************************/
    203194
     
    210201    time.tv_usec = 0;
    211202
    212     if(gettimeofday(&now,(struct timezone *) 0) == -1) {
     203    if (gettimeofday(&now, (struct timezone *)0) == -1) {
    213204        psError(__func__, " : Line %d - Failed to get time", __LINE__);
    214205        return time;
    215206    }
    216 
    217207    // Convert timeval time to psTime
    218208    time.tv_sec = now.tv_sec;
     
    220210
    221211    // 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];
    223213
    224214    return time;
    225215}
    226216
    227 char* psTimeToISO(psTime time)
     217char *psTimeToISO(psTime time)
    228218{
    229219    int ms = 0;
     
    232222    struct tm *tmTime = NULL;
    233223
    234     CHECK_NEGATIVE_TIME_STRUCT(time,NULL);
     224    CHECK_NEGATIVE_TIME_STRUCT(time, NULL);
    235225
    236226    tempString = psAlloc(MAX_TIME_STRING_LENGTH);
     
    238228
    239229    // 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;
    241231
    242232    // tmTime variable is statically allocated, no need to free
    243233    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)) {
    245235        psError(__func__, " : Line %d - Failed strftime conversion", __LINE__);
    246236    }
    247237
    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) {
    249239        psError(__func__, " : Line %d - Failed snprintf conversion", __LINE__);
    250240    }
     
    262252    psTime outTime;
    263253
    264     CHECK_NEGATIVE_TIME_STRUCT(time,outTime);
     254    CHECK_NEGATIVE_TIME_STRUCT(time, outTime);
    265255
    266256    // Find leapseconds to subtract from psTime to get UTC time
    267257    jd = psTimeToJD(time);
    268258    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) {
    271261            ls = *(jdTable + 1);
    272262        }
     
    276266    outTime.tv_usec = time.tv_usec;
    277267
    278     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     268    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    279269
    280270    return outTime;
     
    285275    double mjd = 0.0;
    286276
    287     CHECK_NEGATIVE_TIME_STRUCT(time,mjd);
     277    CHECK_NEGATIVE_TIME_STRUCT(time, mjd);
    288278
    289279    // 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;
    291281
    292282    return mjd;
     
    297287    double jd = 0.0;
    298288
    299     CHECK_NEGATIVE_TIME_STRUCT(time,jd);
     289    CHECK_NEGATIVE_TIME_STRUCT(time, jd);
    300290
    301291    // 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;
    303293
    304294    return jd;
     
    309299    struct timeval timevalTime;
    310300
    311     CHECK_NEGATIVE_TIME_STRUCT(time,timevalTime);
     301    CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime);
    312302    timevalTime.tv_sec = time.tv_sec;
    313303    timevalTime.tv_usec = time.tv_usec;
     
    316306}
    317307
    318 struct tm* psTimeToTM(psTime time)
     308struct tm *psTimeToTM(psTime time)
    319309{
    320310    struct tm *tmTime = NULL;
    321311
    322     CHECK_NEGATIVE_TIME_STRUCT(time,tmTime);
     312    CHECK_NEGATIVE_TIME_STRUCT(time, tmTime);
    323313    tmTime = gmtime(&time.tv_sec);
    324314
     
    343333    // Convert YYYY/MM/DD,HH:MM:SS.SSS in string form to tm time
    344334    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);
    347337        return outTime;
    348338    }
    349339
    350340    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);
    353343        return outTime;
    354344    }
    355345
    356346    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);
    359349        return outTime;
    360350    }
    361351
    362352    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);
    365355        return outTime;
    366356    }
    367357
    368358    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);
    371361        return outTime;
    372362    }
    373363
    374364    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);
    377367        return outTime;
    378368    }
    379369
    380370    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);
    383373        return outTime;
    384374    }
     
    394384    // Convert tm time to psTime
    395385    outTime = psTMToTime(&tmTime);
    396     outTime.tv_usec = millisecond*1000;
     386    outTime.tv_usec = millisecond * 1000;
    397387
    398388    return outTime;
     
    403393    psTime outTime;
    404394
    405     CHECK_NEGATIVE_TIME_STRUCT(time,outTime);
     395    CHECK_NEGATIVE_TIME_STRUCT(time, outTime);
    406396
    407397    // 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];
    409399    outTime.tv_usec = time.tv_usec;
    410     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     400    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    411401
    412402    return outTime;
     
    419409    double seconds = 0.0;
    420410
    421     CHECK_NEGATIVE_TIME(time,outTime);
     411    CHECK_NEGATIVE_TIME(time, outTime);
    422412
    423413    // Modified Julian date conversion courtesy of Eugene Magnier
     
    425415
    426416    // 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;
    429419    outTime.tv_sec = seconds;
    430420
    431     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     421    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    432422
    433423    return outTime;
     
    440430    psTime outTime;
    441431
    442     CHECK_NEGATIVE_TIME(time,outTime);
     432    CHECK_NEGATIVE_TIME(time, outTime);
    443433
    444434    // Julian date conversion courtesy of Eugene Magnier
     
    446436
    447437    // Convert to psTime/TAI
    448     seconds = days*SEC_PER_DAY;
     438    seconds = days * SEC_PER_DAY;
    449439    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
     447psTime 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    }
    476464    // Convert to psTime/TAI
    477465    outTime.tv_sec = time->tv_sec;
    478466    outTime.tv_usec = time->tv_usec;
    479467
    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
     473psTime psTMToTime(struct tm * time)
    487474{
    488475    int i;
    489476    int n;
    490477    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                };
    495481    long epoch;
    496482    psTime outTime;
    497483
    498     i= 0;
     484    i = 0;
    499485    n = 0;
    500486    y = 0;
    501487    epoch = 0;
    502488
    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    }
    538518
    539519    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;
    542522
    543523    y = time->tm_year + 1900;
    544524
    545525    // 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)) {
    550530            epoch += SEC_PER_DAY;
    551531        }
     
    554534    // Add everything
    555535    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;
    557537
    558538    // Create psTime
     
    560540    outTime.tv_sec = epoch;
    561541
    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
    12/** @file  psTime.h
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-08-06 22:34:05 $
     15 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PSTIME_H
    21 #define PSTIME_H
    22 
    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"
    2829
    2930/// @addtogroup Time
     
    3132
    3233/******************************************************************************/
     34
    3335/*  TYPE DEFINITIONS                                                          */
     36
    3437/******************************************************************************/
    3538
     
    4245typedef struct
    4346{
    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. */
    4651}
    4752psTime;
    4853
    4954/*****************************************************************************/
     55
    5056/* FUNCTION PROTOTYPES                                                       */
     57
    5158/*****************************************************************************/
    5259
     
    5764 *  @return  psTime: Struct with current time.
    5865 */
    59 psTime psTimeGetTime(
    60     void   /** No argument. */
    61 );
     66
     67psTime psTimeGetTime(void
     68                     /** No argument. */
     69                    );
    6270
    6371/** Convert psTime to ISO time in TAI units.
     
    6876 *  @return  char*: Pointer null terminated array of chars in ISO time.
    6977 */
    70 char* psTimeToISO(
    71     psTime time     /** Input time to be converted. */
    72 );
     78
     79char *psTimeToISO(psTime time
     80                  /** Input time to be converted. */
     81                 );
    7382
    7483/** Convert psTime to UTC time.
     
    8089 *  @return  psTime: UTC time psTime format.
    8190 */
    82 psTime psTimeToUTC(
    83     psTime time    /** Input time to be converted. */
    84 );
     91
     92psTime psTimeToUTC(psTime time
     93                   /** Input time to be converted. */
     94                  );
    8595
    8696/** Convert psTime to modified Julian date time.
     
    91101 *  @return  double: Modified Julian Days (MJD) time.
    92102 */
    93 double psTimeToMJD(
    94     psTime time    /** Input time to be converted. */
    95 );
     103
     104double psTimeToMJD(psTime time
     105                   /** Input time to be converted. */
     106                  );
    96107
    97108/** Convert psTime to Julian date time.
     
    102113 *  @return  double: Julian Date (JD) time.
    103114 */
    104 double psTimeToJD(
    105     psTime time    /** Input time to be converted. */
    106 );
     115
     116double psTimeToJD(psTime time
     117                  /** Input time to be converted. */
     118                 );
    107119
    108120/** Convert psTime to timeval time.
     
    113125 *  @return  timeval: timeval struct time.
    114126 */
    115 struct timeval psTimeToTimeval(
    116                 psTime time    /** Input time to be converted. */
    117             );
     127
     128struct timeval psTimeToTimeval(psTime time
     129                                           /** Input time to be converted. */
     130                                          );
    118131
    119132/** Convert psTime to tm time.
     
    124137 *  @return  tm: tm struct time.
    125138 */
    126 struct tm* psTimeToTM(
    127                 psTime time    /** Input time to be converted. */
    128             );
     139
     140struct tm *psTimeToTM(psTime time
     141                                  /** Input time to be converted. */
     142                                 );
    129143
    130144/** Convert ISO to psTime.
     
    135149 *  @return  psTime: time
    136150 */
    137 psTime psISOToTime(
    138     char *time  /** Input time to be converted. */
    139 );
     151
     152psTime psISOToTime(char *time
     153                   /** Input time to be converted. */
     154                  );
    140155
    141156/** Convert UTC to psTime.
     
    146161 *  @return  psTime: time in TAI units.
    147162 */
    148 psTime psUTCToTime(
    149     psTime time /** Input time to be converted. */
    150 );
     163
     164psTime psUTCToTime(psTime time
     165                   /** Input time to be converted. */
     166                  );
    151167
    152168/** Convert MJD to psTime.
     
    157173 *  @return  psTime: time.
    158174 */
    159 psTime psMJDToTime(
    160     double time /** Input time to be converted. */
    161 );
     175
     176psTime psMJDToTime(double time
     177                   /** Input time to be converted. */
     178                  );
    162179
    163180/** Convert JD to psTime.
     
    168185 *  @return  psTime: time.
    169186 */
    170 psTime psJDToTime(
    171     double time /** Input time to be converted. */
    172 );
     187
     188psTime psJDToTime(double time
     189                  /** Input time to be converted. */
     190                 );
    173191
    174192/** Convert timeval to psTime.
     
    179197 *  @return  psTime: time.
    180198 */
    181 psTime psTimevalToTime(
    182     struct timeval *time    /** Input time to be converted. */
    183 );
     199
     200psTime psTimevalToTime(struct timeval *time
     201                       /** Input time to be converted. */
     202                      );
    184203
    185204/** Convert tm time to psTime.
     
    190209 *  @return  psTime: time.
    191210 */
    192 psTime psTMToTime(
    193     struct tm *time /** Input time to be converted. */
    194 );
     211
     212psTime psTMToTime(struct tm *time
     213                  /** Input time to be converted. */
     214                 );
     215
    195216/// @}
    196217
  • trunk/psLib/src/astronomy/psAstrometry.c

    r1406 r1407  
     1
    12/** @file  psAstrometry.c
    23*
     
    89*  @author George Gusciora, MHPCC
    910*
    10 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2021#include "psMemory.h"
    2122
    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;
     23static void grommitFree(psGrommit * grommit);
     24static int checkValidChipCoords(double x, double y, psChip * tmpChip);
     25static int checkValidImageCoords(double x, double y, psImage * tmpImage);
     26
     27psExposure *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;
    4546
    4647    return exp;
     
    4849}
    4950
    50 psGrommit* psGrommitAlloc( const psExposure *exp )
    51 {
    52     double * slaGrommit = ( double * ) psAlloc( 14 * sizeof( double ) );
    53     psGrommit *grommit = ( psGrommit * ) psAlloc( sizeof( psGrommit ) );
     51psGrommit *psGrommitAlloc(const psExposure * exp)
     52{
     53    double *slaGrommit = (double *)psAlloc(14 * sizeof(double));
     54    psGrommit *grommit = (psGrommit *) psAlloc(sizeof(psGrommit));
     55
    5456    /*
    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
     81void p_psGrommitFree(psGrommit * grommit)
     82{
     83    psFree(grommit);
     84}
     85
     86psCell *psCellinFPA(psCell * out, const psPlane * coord, const psFPA * FPA)
     87{
     88    psChip *tmpChip = NULL;
    10289    psCell *tmpCell = NULL;
    10390
    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
     96int checkValidChipCoords(double x, double y, psChip * tmpChip)
     97{
     98    return (0);
     99}
     100
     101psChip *psChipinFPA(psChip * out, const psPlane * coord, const psFPA * FPA)
     102{
     103    psArray *chips = FPA->chips;
    120104    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);
    129113            // XXX: George, you didn't use the out parameter!
    130             return ( tmpChip );
     114            return (tmpChip);
    131115        }
    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
     122int 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}
    149129
    150130/*****************************************************************************
     
    160140XXX: must deallocate memory.
    161141 *****************************************************************************/
    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 ) {
     142psCell *psCellinChip(psCell * out, const psPlane * coord, const psChip * chip)
     143{
     144    psPlane *tmpCoord = NULL;
     145    psArray *cells;
     146
     147    if (chip == NULL) {
    170148        return NULL;
    171149    }
     
    173151    cells = chip->cells;
    174152
    175     if ( cells == NULL ) {
     153    if (cells == NULL) {
    176154        return NULL;
    177155    }
    178156
    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);
    189168                }
    190169            }
    191170        }
    192171    }
    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
     175psPlane *psCoordCelltoChip(psPlane * out, const psPlane * in, const psCell * cell)
     176{
     177    return (psPlaneTransformApply(out, cell->toChip, in));
     178}
     179
     180psPlane *psCoordChipToFPA(psPlane * out, const psPlane * in, const psChip * chip)
     181{
     182    return (psPlaneTransformApply(out, chip->toFPA, in));
     183}
     184
     185psPlane *psCoordFPAtoTP(psPlane * out, const psPlane * in, const psFPA * fpa)
    213186{
    214187    // XXX: This code doesn't work; fpa->toTangentPlane is of the wrong type.
    215188    // return(psPlaneTransformApply(out, fpa->toTangentPlane, in));
    216     return ( NULL );
     189    return (NULL);
    217190}
    218191
    219192// XXX: must wrap SLA_QAPQK here.
    220 psSphere *psCoordTPtoSky( psSphere *out,
    221                           const psPlane *in,
    222                           const psGrommit *grommit )
     193psSphere *psCoordTPtoSky(psSphere * out, const psPlane * in, const psGrommit * grommit)
    223194{
    224195    /*
    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
     204psPlane *psCoordCellToFPA(psPlane * out, const psPlane * in, const psCell * cell)
     205{
     206    return (psPlaneTransformApply(out, cell->toFPA, in));
     207}
    243208
    244209// XXX: This implementation requires a new psGrommit be created for each
    245210// transformation, as well as a few psPlane structs.  Can this be implemented
    246211// better?
    247 psSphere *psCoordCelltoSky( psSphere *out,
    248                             const psPlane *in,
    249                             const psCell *cell )
    250 {
    251     psPlane * tmp1 = NULL;
     212psSphere *psCoordCelltoSky(psSphere * out, const psPlane * in, const psCell * cell)
     213{
     214    psPlane *tmp1 = NULL;
    252215    psPlane *tmp2 = NULL;
    253     psFPA *parFPA = ( cell->parent ) ->parent;
     216    psFPA *parFPA = (cell->parent)->parent;
    254217    psGrommit *tmpGrommit = NULL;
    255218
    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
     232psSphere *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
    278239    // coords in out.
    279240
    280     psFree( tmp1 );
    281 
    282     return ( out );
     241    psFree(tmp1);
     242
     243    return (out);
    283244}
    284245
    285246// 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 );
     247psPlane *psCoordSkytoTP(psPlane * out, const psSphere * in, const psGrommit * grommit)
     248{
     249    extern void sla_AOPQK(RAP, DAP, AOPRMS, AOB, ZOB, HOB, DOB, ROB);
    291250    double AOB;
    292251    double ZOB;
     
    295254    double ROB;
    296255
    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);
    302261    out->x = XXX;
    303262    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
     266psPlane *psCoordTPtoFPA(psPlane * out, const psPlane * in, const psFPA * fpa)
     267{
     268    return (psPlaneTransformApply(out, fpa->fromTangentPlane, in));
     269}
     270
     271psPlane *psCoordFPAtoChip(psPlane * out, const psPlane * in, const psChip * chip)
     272{
     273    return (psPlaneTransformApply(out, chip->fromFPA, in));
     274}
     275
     276psPlane *psCoordChiptoCell(psPlane * out, const psPlane * in, const psCell * cell)
     277{
     278    return (psPlaneTransformApply(out, cell->fromChip, in));
     279}
     280
     281psPlane *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
     291psPlane *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
    12/** @file  psAstrometry.h
    23*
     
    89*  @author George Gusciora, MHPCC
    910*
    10 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1415*/
    1516
    16 # ifndef PS_ASTROMETRY_H
    17 # define PS_ASTROMETRY_H
    18 
    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"
    2728
    2829struct psCell;
     
    4445typedef struct
    4546{
    46     const double latitude;             ///< geodetic latitude (radians)
    47     const double sinLat;               ///< sine of geodetic latitude
    48     const double cosLat;               ///< cosine of geodetic latitude
    49     const double abberationMag;        ///< magnitude of diurnal aberration vector
    50     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)
    6061}
    6162psGrommit;
     
    7273typedef struct
    7374{
    74     int nX;                            ///< Number of elements in x direction
    75     int nY;                            ///< Number of elements in y direction
    76     double x0;                         ///< X Position of 0,0 corner on focal plane
    77     double y0;                         ///< Y Position of 0,0 corner on focal plane
    78     double xScale;                     ///< Scale of the grid in x direction
    79     double yScale;                     ///< Scale of the grid in x direction
    80     double **x;                        ///< The grid of offsets in x
    81     double **y;                        ///< The grid of offsets in y
     75    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
    8283}
    8384psFixedPattern;
     
    9495typedef struct
    9596{
    96     const unsigned int colBins;        ///< Amount of binning in x-dimension
    97     const unsigned int rowBins;        ///< Amount of binning in y-dimension
    98     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 Readout
    102     psList* objects;                   ///< objects derived from Readout
    103     psMetadata* metadata;              ///< readout-level metadata
     97    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
    104105}
    105106psReadout;
     
    116117typedef struct psCell
    117118{
    118     psArray* readouts;                 ///< readouts from the cell
    119     psMetadata* metadata;              ///< cell-level metadata
    120 
    121     psPlaneTransform* toChip;          ///< transformations from cell to chip coordinates
    122     psPlaneTransform* fromChip;        ///< transformations from chip to cell coordinates
    123     psPlaneTransform* toFPA;           ///< transformations from cell to FPA coordinates
    124     psPlaneTransform* toSky;           ///< transformations from cell to sky coordinates
    125 
    126     struct psChip* parent;             ///< chip in which contains this cell
     119    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
    127128}
    128129psCell;
     
    138139typedef struct psChip
    139140{
    140     psArray* cells;                    ///< cells in the chip
    141     psMetadata* metadata;              ///< chip-level metadata
    142 
    143     psPlaneTransform* toFPA;           ///< transformation from chip to FPA coordinates
    144     psPlaneTransform* fromFPA;         ///< transformation from FPA to chip coordinates
    145 
    146     struct psFPA* parent;              ///< FPA which contains this chip
     141    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
    147148}
    148149psChip;
     
    163164typedef struct psFPA
    164165{
    165     psArray* chips;                    ///< chips in the focal plane array
    166     psMetadata* metadata;              ///< focal-plane's metadata
    167 
    168     psPlaneDistort* fromTangentPlane;  ///< transformation from tangent plane to focal plane
    169     psPlaneDistort* toTangentPlane;    ///< transformation from focal plane to tangent plane
    170     psFixedPattern* pattern;           ///< fixed pattern residual offsets
    171 
    172     const struct psExposure* exposure; ///< information about this exposure
    173 
    174     psPhotSystem* colorPlus;           ///< Color reference
    175     psPhotSystem* colorMinus;          ///< Color reference
    176 
    177     float rmsX;                        ///< RMS for x transformation fits
    178     float rmsY;                        ///< RMS for y transformation fits
    179     float chi2;                        ///< chi^2 of astrometric solution
     166    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
    180181}
    181182psFPA;
     
    190191typedef struct psExposure
    191192{
    192     const double ra;                  ///< Telescope boresight, right ascention
    193     const double dec;                 ///< Telescope boresight, declination
    194     const double hourAngle;           ///< Hour angle
    195     const double zenith;              ///< Zenith distance
    196     const double azimuth;             ///< Azimuth
    197     const double localTime;           ///< Local Sidereal Time
    198     const float date;                 ///< Modified Jullian Date of observation
    199     const float rotAngle;             ///< Rotator position angle
    200     const float temperature;          ///< Air temperature, for estimating refraction
    201     const float pressure;             ///< Air pressure, for calculating refraction
    202     const float humidity;             ///< Relative humidity, for refraction
    203     const float exposureTime;         ///< Exposure time
     193    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
    204205
    205206    /* Derived quantities */
    206     const float positionAngle;        ///< Position angle
    207     const float parallacticAngle;     ///< Parallactic angle
    208     const float airmass;              ///< Airmass, calculated from zenith distance
    209     const float parallacticFactor;    ///< Parallactic factor
    210     const char *cameraName;           ///< name of camera which provided exposure
    211     const char *telescopeName;        ///< name of telescope which provided exposure
     207    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
    212213}
    213214psExposure;
    214215
    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 );
     216psExposure *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                           );
    229229
    230230/** Allocates a Wallace's Grommit structure.
     
    235235 *  @return psGrommit*     New grommit structure.
    236236 */
    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 );
     237psGrommit *psGrommitAlloc(const psExposure * exp        // /< the cooresponding exposure structure.
     238                         );
     239
     240psCell *psCellinFPA(psCell * out, const psPlane * coord, const psFPA * FPA);
     241
     242psChip *psChipinFPA(psChip * out, const psPlane * coord, const psFPA * FPA);
     243
     244psCell *psCellinChip(psCell * out, const psPlane * coord, const psChip * chip);
     245
     246psPlane *psCoordCelltoChip(psPlane * out, const psPlane * in, const psCell * cell);
     247
     248psPlane *psCoordChipToFPA(psPlane * out, const psPlane * in, const psChip * chip);
     249
     250psPlane *psCoordFPAtoTP(psPlane * out, const psPlane * in, const psFPA * fpa);
     251
     252psSphere *psCoordTPtoSky(psSphere * out, const psPlane * in, const psGrommit * grommit);
     253
     254psPlane *psCoordCellToFPA(psPlane * out, const psPlane * in, const psCell * cell);
     255
     256psSphere *psCoordCelltoSky(psSphere * out, const psPlane * in, const psCell * cell);
     257
     258psSphere *psCoordCelltoSkyQuick(psSphere * out, const psPlane * in, const psCell * cell);
     259
     260psPlane *psCoordSkytoTP(psPlane * out, const psSphere * in, const psGrommit * grommit);
     261
     262psPlane *psCoordTPtoFPA(psPlane * out, const psPlane * in, const psFPA * fpa);
     263
     264psPlane *psCoordFPAtoChip(psPlane * out, const psPlane * in, const psChip * chip);
     265
     266psPlane *psCoordChiptoCell(psPlane * out, const psPlane * in, const psCell * cell);
     267
     268psPlane *psCoordSkytoCell(psPlane * out, const psSphere * in, const psCell * cell);
     269
     270psPlane *psCoordSkytoCellQuick(psPlane * out, const psSphere * in, const psCell * cell);
    336271
    337272#endif
  • trunk/psLib/src/astronomy/psCoord.c

    r1406 r1407  
     1
    12/** @file  psCoord.c
    23*
     
    1011*  @author George Gusciora, MHPCC
    1112*
    12 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-06 22:34:05 $
     13*  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728#include <float.h>
    2829
    29 static float cot( float x );
    30 static float arg( float x, float y );
     30static float cot(float x);
     31static float arg(float x, float y);
    3132
    3233// 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 
     34psPlane *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}
    5147
    5248// This transformation takes into account parameters beyond an objects
    5349// 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 
     50psPlane *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}
    7970
    8071// 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 );
     72psSphereTransform *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);
    8978    tmp->Xo = Xo;
    9079    tmp->xo = xo;
    9180
    92     return ( tmp );
     81    return (tmp);
    9382}
    9483
     
    10089// there are no typo's.
    10190
    102 psSphere *psSphereTransformApply( psSphere *out,
    103                                   const psSphereTransform *transform,
    104                                   const psSphere *coord )
     91psSphere *psSphereTransformApply(psSphere * out, const psSphereTransform * transform, const psSphere * coord)
    10592{
    10693    double sinY = 0.0;
     
    11299    double dx = 0.0;
    113100
    114     if ( out == NULL ) {
    115         out = ( psSphere * ) psAlloc( sizeof( psSphere ) );
     101    if (out == NULL) {
     102        out = (psSphere *) psAlloc(sizeof(psSphere));
    116103    }
    117104
     
    119106    y = coord->d;
    120107    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
     119psSphereTransform *psSphereTransformICRStoEcliptic(psTime time)
     120{
     121    struct tm *tmTime = psTimeToTM(time);
     122    double year = (double)(1900 + tmTime->tm_year);
    137123    double T = year / 100.0;
    138124    double phi = -23.452294 + 0.013013 * T + 0.000001639 * T * T - 0.000000503 * T * T * T;
     
    140126    double xo = 0.0;
    141127
    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
     131psSphereTransform *psSphereTransformEcliptictoICRS(psTime time)
     132{
     133    struct tm *tmTime = psTimeToTM(time);
     134    double year = (double)(1900 + tmTime->tm_year);
    149135    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;
    151137    double Xo = 0.0;
    152138    double xo = 0.0;
    153139
    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
     143psSphereTransform *psSphereTransformICRStoGalatic(void)
     144{
     145    return (psSphereTransformAlloc(62.6, 282.25, 33.0));
     146}
     147
     148psSphereTransform *psSphereTransformGalatictoICRS(void)
     149{
     150    return (psSphereTransformAlloc(-62.6, 33.0, 282.25));
    165151}
    166152
    167153// XXX: Is this the correct way to calculate this?
    168 float cot( float x )
    169 {
    170     return ( 1.0 / atan( x ) );
     154float cot(float x)
     155{
     156    return (1.0 / atan(x));
    171157}
    172158
    173159// 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 );
     160float 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);
    194176}
    195177
    196178// XXX: Waiting for the definition of the PS_PROJ_PAR projection.
    197179// XXX: Waiting for the definition of the PS_PROJ_GLS projection.
    198 psPlane *psProject( const psSphere *coord,
    199                     const psProjection *projection )
     180psPlane *psProject(const psSphere * coord, const psProjection * projection)
    200181{
    201182    float R = 0.0;
    202183    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);
    244218}
    245219
    246220// XXX: Waiting for the definition of the PS_PROJ_PAR projection.
    247221// XXX: Waiting for the definition of the PS_PROJ_GLS projection.
    248 psSphere *psDeproject( const psPlane *coord,
    249                        const psProjection *projection )
     222psSphere *psDeproject(const psPlane * coord, const psProjection * projection)
    250223{
    251224    float R = 0.0;
     
    253226    float chu1 = 0.0;
    254227    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);
    299265}
    300266
    301267// XXX: Do I need to check for unacceptable transformation parameters?
    302268// 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;
     269psSphere *psSphereGetOffset(const psSphere * restrict position1,
     270                            const psSphere * restrict position2,
     271                            psSphereOffsetMode mode, psSphereOffsetUnit unit)
     272{
     273    // psPlane *lin;
    309274    psProjection proj;
    310275    psSphere *tmp;
     
    312277    double tmpD = 0.0;
    313278
    314     if ( mode == PS_LINEAR ) {
     279    if (mode == PS_LINEAR) {
    315280        // XXX: I have no idea how to construct this.  Maybe project both
    316281        // sperical positions onto the plane, set the origin at one of the
     
    318283
    319284        // 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)?
    321286        proj.R = position1->r;
    322287        proj.D = position1->d;
     
    325290        proj.type = PS_PROJ_TAN;
    326291
    327         //        lin = psProject(position2, proj);
    328         //        tmp = psDeproject(lin, proj);
     292        // lin = psProject(position2, proj);
     293        // tmp = psDeproject(lin, proj);
    329294
    330295        // 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);
    361313        }
    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}
    366326
    367327// XXX: Do I need to check for unacceptable transformation parameters?
    368328// Maybe, if the points are on the North/South Pole, etc?
    369329// 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 )
     330psSphere *psSphereSetOffset(const psSphere * restrict position,
     331                            const psSphere * restrict offset,
     332                            psSphereOffsetMode mode, psSphereOffsetUnit unit)
    374333{
    375334    psPlane lin;
     
    379338    double tmpD = 0.0;
    380339
    381     if ( mode == PS_LINEAR ) {
     340    if (mode == PS_LINEAR) {
    382341        proj.R = position->r;
    383342        proj.D = position->d;
     
    389348        lin.y = offset->d;
    390349
    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);
    424368        }
    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
    12/** @file  psCoord.h
    23*
     
    1011*  @author George Gusciora, MHPCC
    1112*
    12 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-05 19:38:51 $
     13*  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617*/
    1718
    18 # ifndef PS_COORD_H
    19 # define PS_COORD_H
    20 
    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"
    2728
    2829/// @addtogroup CoordinateTransform
     
    3839typedef struct
    3940{
    40     double x;      ///< x position
    41     double y;      ///< y position
    42     double xErr;   ///< Error in x position
    43     double yErr;   ///< Error in y position
     41    double x;                   // /< x position
     42    double y;                   // /< y position
     43    double xErr;                // /< Error in x position
     44    double yErr;                // /< Error in y position
    4445}
    4546psPlane;
     
    5455typedef struct
    5556{
    56     double r;      ///< RA
    57     double d;      ///< Dec
    58     double rErr;   ///< Error in RA
    59     double dErr;   ///< Error in Dec
     57    double r;                   // /< RA
     58    double d;                   // /< Dec
     59    double rErr;                // /< Error in RA
     60    double dErr;                // /< Error in Dec
    6061}
    6162psSphere;
     
    7172typedef struct
    7273{
    73     psDPolynomial2D *x;                ///< 2D polynomial transform of X coordinates
    74     psDPolynomial2D *y;                ///< 2D polynomial transform of Y coordinates
     74    psDPolynomial2D *x;         // /< 2D polynomial transform of X coordinates
     75    psDPolynomial2D *y;         // /< 2D polynomial transform of Y coordinates
    7576}
    7677psPlaneTransform;
     
    9091typedef struct
    9192{
    92     psDPolynomial4D *x;                ///< 4D polynomial transform of X coordinates
    93     psDPolynomial4D *y;                ///< 4D polynomial transform of Y coordinates
     93    psDPolynomial4D *x;         // /< 4D polynomial transform of X coordinates
     94    psDPolynomial4D *y;         // /< 4D polynomial transform of Y coordinates
    9495}
    9596psPlaneDistort;
     
    107108typedef struct
    108109{
    109     double sinPhi;                    ///< sin of North Pole lattitude
    110     double cosPhi;                    ///< cos of North Pole lattitude
    111     double Xo;                        ///< First PT of Ares lon
    112     double xo;                        ///< First PT of Ares equiv lon
     110    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
    113114}
    114115psSphereTransform;
     
    120121 */
    121122typedef enum {
    122     PS_PROJ_TAN,        ///< Tangent projection
    123     PS_PROJ_SIN,        ///< Sine projection
    124     PS_PROJ_AIT,        ///< Aitoff projection
    125     PS_PROJ_PAR,        ///< Par projection
    126     PS_PROJ_GLS,        ///< GLS projection
    127     PS_PROJ_CAR,        ///< CAR projection
    128     PS_PROJ_MER,        ///< MER projection
    129     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.
    130131} psProjectionType;
    131132
     
    137138typedef struct
    138139{
    139     double R;     ///< Coordinates of projection center
    140     double D;     ///< Coordinates of projection center
    141     double Xs;    ///< plate-scale in X direction
    142     double Ys;    ///< plate-scale in Y direction
    143     psProjectionType type;  ///< Projection type
     140    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
    144145}
    145146psProjection;
     
    151152 */
    152153typedef enum {
    153     PS_SPHERICAL,                      ///< offset corresponds to an angular offset
    154     PS_LINEAR                          ///< offset corresponds to a linear offset
     154    PS_SPHERICAL,               // /< offset corresponds to an angular offset
     155    PS_LINEAR                   // /< offset corresponds to a linear offset
    155156} psSphereOffsetMode;
    156157
     
    161162 */
    162163typedef enum {
    163     PS_ARCSEC,                         ///< Arcseconds
    164     PS_ARCMIN,                         ///< Arcminutes
    165     PS_DEGREE,                         ///< Degrees
    166     PS_RADIAN                          ///< Radians
     164    PS_ARCSEC,                  // /< Arcseconds
     165    PS_ARCMIN,                  // /< Arcminutes
     166    PS_DEGREE,                  // /< Degrees
     167    PS_RADIAN                   // /< Radians
    167168} psSphereOffsetUnit;
    168169
     
    170171 *
    171172 */
    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 );
     173psPlane *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                              );
    177177
    178178/** Applies the psPlaneDistort transform to a specified coordinate
    179179 *
    180180 */
    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 );
     181psPlane *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                            );
    188187
    189188/** Allocator for psSphereTransform
    190189 *
    191190 */
    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 
     191psSphereTransform *psSphereTransformAlloc(double NPlat, // /< north pole latitude
     192        double Xo,    // /< First PT of Ares lon
     193        double xo     // /< First PT of Ares equiv lon
     194                                         );
    198195
    199196/** Applies the psSphereTransform transform for a specified coordinate
    200197 *
    201198 */
    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 );
     199psSphere *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
     205psSphereTransform *psSphereTransformICRStoEcliptic(psTime time);
     206
     207psSphereTransform *psSphereTransformEcliptictoICRS(psTime time);
     208
     209psSphereTransform *psSphereTransformICRStoGalatic(void);
     210
     211psSphereTransform *psSphereTransformGalatictoICRS(void);
     212
     213psPlane *psProject(const psSphere * coord, const psProjection * projection);
     214
     215psSphere *psDeproject(const psPlane * coord, const psProjection * projection);
     216
     217psSphere *psSphereGetOffset(const psSphere * restrict position1,
     218                            const psSphere * restrict position2,
     219                            psSphereOffsetMode mode, psSphereOffsetUnit unit);
     220
     221psSphere *psSphereSetOffset(const psSphere * restrict position,
     222                            const psSphere * restrict offset,
     223                            psSphereOffsetMode mode, psSphereOffsetUnit unit);
    243224
    244225/// @}
  • trunk/psLib/src/astronomy/psMetadata.c

    r1406 r1407  
     1
    12/** @file  psMetadata.c
    23*
     
    1112*  @author Ross Harman, MHPCC
    1213*
    13 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    14 *  @date $Date: 2004-08-06 22:34:05 $
     14*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     15*  @date $Date: 2004-08-07 00:06:06 $
    1516*
    1617*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225#include<stdio.h>
     
    3437#include "psString.h"
    3538
    36 
    3739/******************************************************************************/
     40
    3841/*  DEFINE STATEMENTS                                                         */
     42
    3943/******************************************************************************/
    4044
     
    5660
    5761/******************************************************************************/
     62
    5863/*  TYPE DEFINITIONS                                                          */
     64
    5965/******************************************************************************/
    6066
     
    6268
    6369/*****************************************************************************/
     70
    6471/*  GLOBAL VARIABLES                                                         */
     72
    6573/*****************************************************************************/
    6674
     
    6876
    6977/*****************************************************************************/
     78
    7079/*  FILE STATIC VARIABLES                                                    */
     80
    7181/*****************************************************************************/
    7282
     
    7484
    7585/*****************************************************************************/
     86
    7687/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    77 /*****************************************************************************/
    78 static void metadataItemFree( psMetadataItem *metadataItem )
     88
     89/*****************************************************************************/
     90static void metadataItemFree(psMetadataItem * metadataItem)
    7991{
    8092    psMetadataType type;
     
    8294    type = metadataItem->type;
    8395
    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 ||
    93105            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
     111static void metadataFree(psMetadata * metadata)
     112{
     113    if (metadata == NULL) {
     114        return;
     115    }
     116    psFree(metadata->list);
     117    psFree(metadata->table);
     118}
     119
     120/*****************************************************************************/
     121
    112122/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    113 /*****************************************************************************/
    114 
    115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... )
     123
     124/*****************************************************************************/
     125
     126psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...)
    116127{
    117128    va_list argPtr;
     
    119130
    120131    // Get the variable list parameters to pass to allocation function
    121     va_start( argPtr, comment );
     132    va_start(argPtr, comment);
    122133
    123134    // Call metadata item allocation
    124     metadataItem = psMetadataItemAllocV( name, type, comment, argPtr );
     135    metadataItem = psMetadataItemAllocV(name, type, comment, argPtr);
    125136
    126137    // Clean up stack after variable arguement has been used
    127     va_end( argPtr );
     138    va_end(argPtr);
    128139
    129140    return metadataItem;
    130141}
    131142
    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 
     143psMetadataItem *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    }
    141152    // 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    }
    147157    // Set deallocator
    148     p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree );
     158    p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree);
    149159
    150160    // 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) {
    153163        // Per SDRS, null isn't allowed, must use "" instead
    154         strncpy( metadataItem->comment, "", MAX_STRING_LENGTH );
     164        strncpy(metadataItem->comment, "", MAX_STRING_LENGTH);
    155165    } else {
    156         strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH );
     166        strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH);
    157167    }
    158168
    159169    // Set metadata item unique id
    160     *( int* ) ( &metadataItem->id ) = ++metadataId;
     170    *(int *)(&metadataItem->id) = ++metadataId;
    161171
    162172    // Set metadata item type
     
    164174
    165175    // Set metadata item value
    166     switch(type) {
     176    switch (type) {
    167177    case PS_META_BOOL:
    168         metadataItem->data.B = ( bool ) va_arg( argPtr, int );
     178        metadataItem->data.B = (bool) va_arg(argPtr, int);
     179
    169180        break;
    170181    case PS_META_S32:
    171         metadataItem->data.S32 = va_arg( argPtr, psS32 );
     182        metadataItem->data.S32 = va_arg(argPtr, psS32);
    172183        break;
    173184    case PS_META_F32:
    174         metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64 );
     185        metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64);
    175186        break;
    176187    case PS_META_F64:
    177         metadataItem->data.F64 = va_arg( argPtr, psF64 );
     188        metadataItem->data.F64 = va_arg(argPtr, psF64);
    178189        break;
    179190    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
    181193        break;
    182194    case PS_META_IMG:
     
    186198    case PS_META_UNKNOWN:
    187199    default:
    188         psError( __func__, "Invalid psMetadataType: %d", type );
     200        psError(__func__, "Invalid psMetadataType: %d", type);
    189201    }
    190202
    191203    // 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);
    194206
    195207    // Allocate metadata items with same name.
    196     metadataItem->items = psListAlloc( NULL );
     208    metadataItem->items = psListAlloc(NULL);
    197209
    198210    return metadataItem;
    199211}
    200212
    201 psMetadata *psMetadataAlloc( void )
    202 {
    203     psList * list = NULL;
     213psMetadata *psMetadataAlloc(void)
     214{
     215    psList *list = NULL;
    204216    psHash *table = NULL;
    205217    psMetadata *metadata = NULL;
    206218
    207219    // 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    }
    213224    // Set deallocator
    214     p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree );
     225    p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree);
    215226
    216227    // 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");
    225236    }
    226237
     
    231242}
    232243
    233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem )
    234 {
    235     char * key = NULL;
     244bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem)
     245{
     246    char *key = NULL;
    236247    psHash *mdTable = NULL;
    237248    psList *mdList = NULL;
     
    239250    psMetadataType type = PS_META_ITEM_SET;
    240251
    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");
    248259        return false;
    249260    }
     
    252263
    253264    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");
    262273        return false;
    263274    }
    264275
    265276    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    }
    271281    // 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) {
    274284
    275285        // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so
    276286        // 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);
    280289            return false;
    281290        }
    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);
    289304            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    }
    299307
    300308    // 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);
    304312        return false;
    305313    }
     
    308316}
    309317
    310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,
    311                     const char *comment, ... )
     318bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type,
     319                   const char *comment, ...)
    312320{
    313321    va_list argPtr;
    314322    psMetadataItem *metadataItem = NULL;
    315323
    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 needed here
    328     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);
    329337
    330338    return true;
    331339}
    332340
    333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key )
     341bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key)
    334342{
    335343    int numChildren = 0;
     
    340348
    341349    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");
    344352        return false;
    345353    }
    346354
    347355    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    }
    353360    // Select removal by key or index
    354     if(key != NULL) {
     361    if (key != NULL) {
    355362
    356363        // 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);
    360367            return false;
    361368        }
    362369
    363370        numChildren = entry->items->size;
    364         if(entry->type == PS_META_ITEM_SET && numChildren > 0) {
     371        if (entry->type == PS_META_ITEM_SET && numChildren > 0) {
    365372
    366373            // 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);
    372379                    return false;
    373380                }
    374                 entryChild = psListGetNext( entry->items );
     381                entryChild = psListGetNext(entry->items);
    375382            }
    376383        }
    377 
    378384        // 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);
    381387            return false;
    382388        }
    383 
    384389        // 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);
    387392            return false;
    388393        }
     
    390395
    391396        // 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);
    395400            return false;
    396401        }
    397402
    398403        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);
    401406            return false;
    402407        }
    403 
    404408        // Use recursive remove, now that key is known
    405         psMetadataRemove( md, PS_LIST_UNKNOWN, key );
     409        psMetadataRemove(md, PS_LIST_UNKNOWN, key);
    406410    }
    407411
     
    409413}
    410414
    411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key )
    412 {
    413     psHash * mdTable = NULL;
     415psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key)
     416{
     417    psHash *mdTable = NULL;
    414418    psMetadataItem *entry = NULL;
    415419
    416420    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);
    430434        return NULL;
    431435    }
     
    434438}
    435439
    436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where )
    437 {
    438     psList * mdList = NULL;
     440psMetadataItem *psMetadataGet(psMetadata * restrict md, int where)
     441{
     442    psList *mdList = NULL;
    439443    psMetadataItem *entry = NULL;
    440444
    441445    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);
    450454        return NULL;
    451455    }
     
    454458}
    455459
    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 );
     460bool 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);
    467471
    468472    return true;
    469473}
    470474
    471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which )
    472 {
    473     psList * mdList = NULL;
     475psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which)
     476{
     477    psList *mdList = NULL;
    474478    psMetadataItem *entry = NULL;
    475479
    476480    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))) {
    492496
    493497            // Match found
    494498            return entry;
    495499        }
    496         entry = psListGetNext( mdList );
     500        entry = psListGetNext(mdList);
    497501    }
    498502
    499503    // 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);
    502506    }
    503507
     
    505509}
    506510
    507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which )
    508 {
    509     psList * mdList = NULL;
     511psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which)
     512{
     513    psList *mdList = NULL;
    510514    psMetadataItem *entry = NULL;
    511515
    512516    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))) {
    528532
    529533            // Match found
    530534            return entry;
    531535        }
    532         entry = psListGetPrevious( mdList );
     536        entry = psListGetPrevious(mdList);
    533537    }
    534538
    535539    // 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);
    538542    }
    539543
     
    541545}
    542546
    543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem )
     547void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem)
    544548{
    545549    psMetadataType type;
    546550
    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;
    560564    }
    561565
    562566    type = metadataItem->type;
    563567
    564     switch(type) {
     568    switch (type) {
    565569    case PS_META_BOOL:
    566         fprintf( fd, format, metadataItem->data.B );
     570        fprintf(fd, format, metadataItem->data.B);
    567571        break;
    568572    case PS_META_S32:
    569         fprintf( fd, format, metadataItem->data.S32 );
     573        fprintf(fd, format, metadataItem->data.S32);
    570574        break;
    571575    case PS_META_F32:
    572         fprintf( fd, format, metadataItem->data.F32 );
     576        fprintf(fd, format, metadataItem->data.F32);
    573577        break;
    574578    case PS_META_F64:
    575         fprintf( fd, format, metadataItem->data.F64 );
     579        fprintf(fd, format, metadataItem->data.F64);
    576580        break;
    577581    case PS_META_STR:
    578         fprintf( fd, format, metadataItem->data.V );
     582        fprintf(fd, format, metadataItem->data.V);
    579583        break;
    580584    case PS_META_ITEM_SET:
     
    585589    case PS_META_UNKNOWN:
    586590    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
     595psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd)
    592596{
    593597    bool tempBool;
    594598    bool success;
    595599    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];
    600604    int i;
    601605    int hduType = 0;
     
    605609    psMetadataType metadataItemType;
    606610
    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    }
    621623    // Allocate metadata if user didn't
    622     if(output == NULL) {
     624    if (output == NULL) {
    623625        output = psMetadataAlloc();
    624626    }
    625 
    626627    // 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) {
    629630            FITS_ERROR("FITS error while locating header %s: %s", extName);
    630631        }
    631632    } else {
    632         if(fits_movabs_hdu( fd, extNum, &hduType, &status ) != 0) {
     633        if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) {
    633634            FITS_ERROR("FITS error while locating header %d: %s", extNum);
    634635        }
     
    636637
    637638    // 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) {
    639640        FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    640641    }
    641 
    642642    // 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) {
    645645            FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    646646        }
    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) {
    650650                FITS_ERROR("FITS error while determining key %d type: %s", keyNum);
    651651            } 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
    653654                keyType = 'C';
    654655                status = 0;
     
    656657        }
    657658
    658         switch(keyType) {
     659        switch (keyType) {
    659660        case 'I':
    660661            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));
    662665            break;
    663666        case 'F':
    664667            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));
    666671            break;
    667672        case 'C':
    668673            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);
    670676            break;
    671677        case 'L':
    672678            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);
    675682            break;
    676683        case 'U':
    677684        case 'X':
    678685        default:
    679             psError( __func__, "Invalid psMetadataType: %c", keyType );
     686            psError(__func__, "Invalid psMetadataType: %c", keyType);
    680687            return output;
    681688        }
    682689
    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);
    685692            return output;
    686693        }
  • trunk/psLib/src/astronomy/psMetadata.h

    r1394 r1407  
     1
    12/** @file  psMetadata.h
    23*
     
    1011*  @author Ross Harman, MHPCC
    1112*
    12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-05 20:55:22 $
     13*  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617*/
    1718#ifndef PS_METADATA_H
    18 #define PS_METADATA_H
    19 
    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"
    2627
    2728/// @addtogroup Metadata
     
    3334 */
    3435typedef enum {
    35     PS_META_ITEM_SET = 0,                   ///< Null. Metadata is in psMetadataItem.items
    36     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.
    4748} psMetadataType;
    4849
     
    5455typedef struct psMetadataItem
    5556{
    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 {
    6161        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.
    6969}
    7070psMetadataItem;
     
    7878typedef struct psMetadata
    7979{
    80     psList* restrict list;
    81     psHash* restrict table;
     80    psList *restrict list;
     81    psHash *restrict table;
    8282}
    8383psMetadata;
    8484
    85 
    8685/*****************************************************************************/
     86
    8787/* FUNCTION PROTOTYPES                                                       */
     88
    8889/*****************************************************************************/
    8990
     
    101102 * @return psMetadataItem*: Pointer metadata item.
    102103 */
    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 );
     104psMetadataItem *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                                   );
    109109
    110110/** Create a metadata item with va_list.
     
    121121 * @return psMetadataItem*: Pointer metadata item.
    122122 */
    123 psMetadataItem *psMetadataItemAllocV(
    124     const char *name,                       ///< Name of metadata item.
    125     psMetadataType type,                    ///< Type of metadata item.
    126     const char *comment,                    ///< Comment for metadata item.
    127     va_list list                        ///< Arguments for name formatting and metadata item data.
    128 );
     123psMetadataItem *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                                    );
    129129
    130130/** Create a metadata collection.
     
    134134 * @return psMetadata*: Pointer metadata.
    135135 */
    136 psMetadata *psMetadataAlloc(
    137     void                                ///< Void.
    138 );
     136psMetadata *psMetadataAlloc(void        // /< Void.
     137                           );
    139138
    140139/** Add existing metadata item to metadata collection.
     
    144143 * @return bool: True for success, false for failure.
    145144 */
    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 );
     145bool 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                      );
    151149
    152150/** Create and add a metadata item to metadata collection.
     
    156154 * @return bool: True for success, false for failure.
    157155 */
    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 );
     156bool 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                  );
    166163
    167164/** Remove an item from metadata collection.
     
    174171 * @return bool: True for success, false for failure.
    175172 */
    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 );
     173bool 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                     );
    181177
    182178/** Find an item in the metadata collection based on key name.
     
    187183 * @return psMetadataItem*: Pointer metadata item.
    188184 */
    189 psMetadataItem *psMetadataLookup(
    190     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    191     const char *restrict key            ///< Name of metadata key.
    192 );
     185psMetadataItem *psMetadataLookup(psMetadata * restrict md,      // /< Metadata collection to insert metadat
     186                                 // item.
     187                                 const char *restrict key       // /< Name of metadata key.
     188                                );
    193189
    194190/** Find an item in the metadata collection based on list index.
     
    198194 * @return psMetadataItem*: Pointer metadata item.
    199195 */
    200 psMetadataItem *psMetadataGet(
    201     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    202     int where                           ///< Location to be retrieved.
    203 );
     196psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item.
     197                              int where // /< Location to be retrieved.
     198                             );
    204199
    205200/** Set or reset metadata iterator.
     
    209204 * @return void: void.
    210205 */
    211 bool psMetadataSetIterator(
    212     psMetadata *restrict md,                ///< Metadata collection to iterate.
    213     int where                           ///< Location of iterator.
    214 );
     206bool psMetadataSetIterator(psMetadata * restrict md,    // /< Metadata collection to iterate.
     207                           int where    // /< Location of iterator.
     208                          );
    215209
    216210/** Get next metadata item.
     
    220214 * @return psMetadataItem*: Pointer metadata item.
    221215 */
    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 );
     216psMetadataItem *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                                 );
    227220
    228221/** Get previous metadata item.
     
    232225 * @return psMetadataItem*: Pointer metadata item.
    233226 */
    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 );
     227psMetadataItem *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                                     );
    239231
    240232/** Print metadata item to file.
     
    248240 * @return psMetadataItem*: Pointer metadata item.
    249241 */
    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 );
     242void 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                        );
    255246
    256247/** Read metadata header.
     
    261252 * @return psMetadata*: Pointer metadata.
    262253 */
    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 );
     254psMetadata *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                                );
    269259
    270260/** Read metadata header.
     
    274264 * @return psMetadata*: Pointer metadata.
    275265 */
    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 );
     266psMetadata *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
    282272/// @}
    283273
  • trunk/psLib/src/astronomy/psPhotometry.h

    r1385 r1407  
     1
    12/** @file  psPhotometry.h
    23*
     
    910*  @author George Gusciora, MHPCC
    1011*
    11 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-04 23:37:39 $
     12*  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516*/
    1617
    17 # ifndef PS_PHOTOMETRIC_H
    18 # define PS_PHOTOMETRIC_H
     18#ifndef PS_PHOTOMETRIC_H
     19#    define PS_PHOTOMETRIC_H
    1920
    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"
    2526
    2627/// @addtogroup Photometry
     
    4243typedef struct
    4344{
    44     const int ID;                  ///< ID number for this photometric system
    45     const char *name;              ///< Name of photometric system
    46     const char *camera;            ///< Camera for photometric system
    47     const char *filter;            ///< Filter used for photometric system
    48     const char *detector;          ///< Detector used for photometric system
     45    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
    4950}
    5051psPhotSystem;
     
    5859typedef struct
    5960{
    60     psPhotSystem src;                  ///< Source photometric system
    61     psPhotSystem dst;                  ///< Destination photometric system
    62     psPhotSystem pP;                   ///< Primary color reference
    63     psPhotSystem pM;                   ///< Primary color reference
    64     psPhotSystem sP;                   ///< Secondary color reference
    65     psPhotSystem sM;                   ///< Secondary color reference
    66     float pA;                          ///< Color offset for references
    67     float sA;                          ///< Color offset for references
    68     psPolynomial3D transform;          ///< Transformation from source to destination
     61    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
    6970}
    7071psPhotTransform;
  • trunk/psLib/src/astronomy/psTime.c

    r1406 r1407  
     1
    12/** @file  psTime.c
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-08-06 22:34:05 $
     15 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1819 */
    1920
    20 
    2121/******************************************************************************/
     22
    2223/*  INCLUDE FILES                                                             */
     24
    2325/******************************************************************************/
    2426
     
    3234
    3335/******************************************************************************/
     36
    3437/*  DEFINE STATEMENTS                                                         */
     38
    3539/******************************************************************************/
    3640
     
    7377}                                                                                                            \
    7478
     79
    7580/******************************************************************************/
     81
    7682/*  TYPE DEFINITIONS                                                          */
     83
    7784/******************************************************************************/
    7885
     
    8087
    8188/*****************************************************************************/
     89
    8290/*  GLOBAL VARIABLES                                                         */
     91
    8392/*****************************************************************************/
    8493
     
    8695
    8796/*****************************************************************************/
     97
    8898/*  FILE STATIC VARIABLES                                                    */
     99
    89100/*****************************************************************************/
    90101
     
    119130
    120131// 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 /*****************************************************************************/
     132static 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
    195183/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     184
    196185/*****************************************************************************/
    197186
     
    199188
    200189/*****************************************************************************/
     190
    201191/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     192
    202193/*****************************************************************************/
    203194
     
    210201    time.tv_usec = 0;
    211202
    212     if(gettimeofday(&now,(struct timezone *) 0) == -1) {
     203    if (gettimeofday(&now, (struct timezone *)0) == -1) {
    213204        psError(__func__, " : Line %d - Failed to get time", __LINE__);
    214205        return time;
    215206    }
    216 
    217207    // Convert timeval time to psTime
    218208    time.tv_sec = now.tv_sec;
     
    220210
    221211    // 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];
    223213
    224214    return time;
    225215}
    226216
    227 char* psTimeToISO(psTime time)
     217char *psTimeToISO(psTime time)
    228218{
    229219    int ms = 0;
     
    232222    struct tm *tmTime = NULL;
    233223
    234     CHECK_NEGATIVE_TIME_STRUCT(time,NULL);
     224    CHECK_NEGATIVE_TIME_STRUCT(time, NULL);
    235225
    236226    tempString = psAlloc(MAX_TIME_STRING_LENGTH);
     
    238228
    239229    // 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;
    241231
    242232    // tmTime variable is statically allocated, no need to free
    243233    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)) {
    245235        psError(__func__, " : Line %d - Failed strftime conversion", __LINE__);
    246236    }
    247237
    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) {
    249239        psError(__func__, " : Line %d - Failed snprintf conversion", __LINE__);
    250240    }
     
    262252    psTime outTime;
    263253
    264     CHECK_NEGATIVE_TIME_STRUCT(time,outTime);
     254    CHECK_NEGATIVE_TIME_STRUCT(time, outTime);
    265255
    266256    // Find leapseconds to subtract from psTime to get UTC time
    267257    jd = psTimeToJD(time);
    268258    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) {
    271261            ls = *(jdTable + 1);
    272262        }
     
    276266    outTime.tv_usec = time.tv_usec;
    277267
    278     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     268    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    279269
    280270    return outTime;
     
    285275    double mjd = 0.0;
    286276
    287     CHECK_NEGATIVE_TIME_STRUCT(time,mjd);
     277    CHECK_NEGATIVE_TIME_STRUCT(time, mjd);
    288278
    289279    // 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;
    291281
    292282    return mjd;
     
    297287    double jd = 0.0;
    298288
    299     CHECK_NEGATIVE_TIME_STRUCT(time,jd);
     289    CHECK_NEGATIVE_TIME_STRUCT(time, jd);
    300290
    301291    // 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;
    303293
    304294    return jd;
     
    309299    struct timeval timevalTime;
    310300
    311     CHECK_NEGATIVE_TIME_STRUCT(time,timevalTime);
     301    CHECK_NEGATIVE_TIME_STRUCT(time, timevalTime);
    312302    timevalTime.tv_sec = time.tv_sec;
    313303    timevalTime.tv_usec = time.tv_usec;
     
    316306}
    317307
    318 struct tm* psTimeToTM(psTime time)
     308struct tm *psTimeToTM(psTime time)
    319309{
    320310    struct tm *tmTime = NULL;
    321311
    322     CHECK_NEGATIVE_TIME_STRUCT(time,tmTime);
     312    CHECK_NEGATIVE_TIME_STRUCT(time, tmTime);
    323313    tmTime = gmtime(&time.tv_sec);
    324314
     
    343333    // Convert YYYY/MM/DD,HH:MM:SS.SSS in string form to tm time
    344334    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);
    347337        return outTime;
    348338    }
    349339
    350340    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);
    353343        return outTime;
    354344    }
    355345
    356346    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);
    359349        return outTime;
    360350    }
    361351
    362352    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);
    365355        return outTime;
    366356    }
    367357
    368358    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);
    371361        return outTime;
    372362    }
    373363
    374364    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);
    377367        return outTime;
    378368    }
    379369
    380370    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);
    383373        return outTime;
    384374    }
     
    394384    // Convert tm time to psTime
    395385    outTime = psTMToTime(&tmTime);
    396     outTime.tv_usec = millisecond*1000;
     386    outTime.tv_usec = millisecond * 1000;
    397387
    398388    return outTime;
     
    403393    psTime outTime;
    404394
    405     CHECK_NEGATIVE_TIME_STRUCT(time,outTime);
     395    CHECK_NEGATIVE_TIME_STRUCT(time, outTime);
    406396
    407397    // 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];
    409399    outTime.tv_usec = time.tv_usec;
    410     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     400    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    411401
    412402    return outTime;
     
    419409    double seconds = 0.0;
    420410
    421     CHECK_NEGATIVE_TIME(time,outTime);
     411    CHECK_NEGATIVE_TIME(time, outTime);
    422412
    423413    // Modified Julian date conversion courtesy of Eugene Magnier
     
    425415
    426416    // 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;
    429419    outTime.tv_sec = seconds;
    430420
    431     CHECK_NEGATIVE_TIME_STRUCT(outTime,outTime);
     421    CHECK_NEGATIVE_TIME_STRUCT(outTime, outTime);
    432422
    433423    return outTime;
     
    440430    psTime outTime;
    441431
    442     CHECK_NEGATIVE_TIME(time,outTime);
     432    CHECK_NEGATIVE_TIME(time, outTime);
    443433
    444434    // Julian date conversion courtesy of Eugene Magnier
     
    446436
    447437    // Convert to psTime/TAI
    448     seconds = days*SEC_PER_DAY;
     438    seconds = days * SEC_PER_DAY;
    449439    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
     447psTime 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    }
    476464    // Convert to psTime/TAI
    477465    outTime.tv_sec = time->tv_sec;
    478466    outTime.tv_usec = time->tv_usec;
    479467
    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
     473psTime psTMToTime(struct tm * time)
    487474{
    488475    int i;
    489476    int n;
    490477    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                };
    495481    long epoch;
    496482    psTime outTime;
    497483
    498     i= 0;
     484    i = 0;
    499485    n = 0;
    500486    y = 0;
    501487    epoch = 0;
    502488
    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    }
    538518
    539519    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;
    542522
    543523    y = time->tm_year + 1900;
    544524
    545525    // 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)) {
    550530            epoch += SEC_PER_DAY;
    551531        }
     
    554534    // Add everything
    555535    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;
    557537
    558538    // Create psTime
     
    560540    outTime.tv_sec = epoch;
    561541
    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
    12/** @file  psTime.h
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-08-06 22:34:05 $
     15 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PSTIME_H
    21 #define PSTIME_H
    22 
    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"
    2829
    2930/// @addtogroup Time
     
    3132
    3233/******************************************************************************/
     34
    3335/*  TYPE DEFINITIONS                                                          */
     36
    3437/******************************************************************************/
    3538
     
    4245typedef struct
    4346{
    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. */
    4651}
    4752psTime;
    4853
    4954/*****************************************************************************/
     55
    5056/* FUNCTION PROTOTYPES                                                       */
     57
    5158/*****************************************************************************/
    5259
     
    5764 *  @return  psTime: Struct with current time.
    5865 */
    59 psTime psTimeGetTime(
    60     void   /** No argument. */
    61 );
     66
     67psTime psTimeGetTime(void
     68                     /** No argument. */
     69                    );
    6270
    6371/** Convert psTime to ISO time in TAI units.
     
    6876 *  @return  char*: Pointer null terminated array of chars in ISO time.
    6977 */
    70 char* psTimeToISO(
    71     psTime time     /** Input time to be converted. */
    72 );
     78
     79char *psTimeToISO(psTime time
     80                  /** Input time to be converted. */
     81                 );
    7382
    7483/** Convert psTime to UTC time.
     
    8089 *  @return  psTime: UTC time psTime format.
    8190 */
    82 psTime psTimeToUTC(
    83     psTime time    /** Input time to be converted. */
    84 );
     91
     92psTime psTimeToUTC(psTime time
     93                   /** Input time to be converted. */
     94                  );
    8595
    8696/** Convert psTime to modified Julian date time.
     
    91101 *  @return  double: Modified Julian Days (MJD) time.
    92102 */
    93 double psTimeToMJD(
    94     psTime time    /** Input time to be converted. */
    95 );
     103
     104double psTimeToMJD(psTime time
     105                   /** Input time to be converted. */
     106                  );
    96107
    97108/** Convert psTime to Julian date time.
     
    102113 *  @return  double: Julian Date (JD) time.
    103114 */
    104 double psTimeToJD(
    105     psTime time    /** Input time to be converted. */
    106 );
     115
     116double psTimeToJD(psTime time
     117                  /** Input time to be converted. */
     118                 );
    107119
    108120/** Convert psTime to timeval time.
     
    113125 *  @return  timeval: timeval struct time.
    114126 */
    115 struct timeval psTimeToTimeval(
    116                 psTime time    /** Input time to be converted. */
    117             );
     127
     128struct timeval psTimeToTimeval(psTime time
     129                                           /** Input time to be converted. */
     130                                          );
    118131
    119132/** Convert psTime to tm time.
     
    124137 *  @return  tm: tm struct time.
    125138 */
    126 struct tm* psTimeToTM(
    127                 psTime time    /** Input time to be converted. */
    128             );
     139
     140struct tm *psTimeToTM(psTime time
     141                                  /** Input time to be converted. */
     142                                 );
    129143
    130144/** Convert ISO to psTime.
     
    135149 *  @return  psTime: time
    136150 */
    137 psTime psISOToTime(
    138     char *time  /** Input time to be converted. */
    139 );
     151
     152psTime psISOToTime(char *time
     153                   /** Input time to be converted. */
     154                  );
    140155
    141156/** Convert UTC to psTime.
     
    146161 *  @return  psTime: time in TAI units.
    147162 */
    148 psTime psUTCToTime(
    149     psTime time /** Input time to be converted. */
    150 );
     163
     164psTime psUTCToTime(psTime time
     165                   /** Input time to be converted. */
     166                  );
    151167
    152168/** Convert MJD to psTime.
     
    157173 *  @return  psTime: time.
    158174 */
    159 psTime psMJDToTime(
    160     double time /** Input time to be converted. */
    161 );
     175
     176psTime psMJDToTime(double time
     177                   /** Input time to be converted. */
     178                  );
    162179
    163180/** Convert JD to psTime.
     
    168185 *  @return  psTime: time.
    169186 */
    170 psTime psJDToTime(
    171     double time /** Input time to be converted. */
    172 );
     187
     188psTime psJDToTime(double time
     189                  /** Input time to be converted. */
     190                 );
    173191
    174192/** Convert timeval to psTime.
     
    179197 *  @return  psTime: time.
    180198 */
    181 psTime psTimevalToTime(
    182     struct timeval *time    /** Input time to be converted. */
    183 );
     199
     200psTime psTimevalToTime(struct timeval *time
     201                       /** Input time to be converted. */
     202                      );
    184203
    185204/** Convert tm time to psTime.
     
    190209 *  @return  psTime: time.
    191210 */
    192 psTime psTMToTime(
    193     struct tm *time /** Input time to be converted. */
    194 );
     211
     212psTime psTMToTime(struct tm *time
     213                  /** Input time to be converted. */
     214                 );
     215
    195216/// @}
    196217
  • trunk/psLib/src/collections/psArray.c

    r1406 r1407  
     1
    12/** @file  psArray.c
    23 *
     
    89 *  @author Ross Harman, MHPCC
    910 *
    10  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    19 #include<stdlib.h>            // for qsort, etc.
     22#include<stdlib.h>                         // for qsort, etc.
    2023
    2124#include "psMemory.h"
     
    2427#include "psLogMsg.h"
    2528
     29/*****************************************************************************/
     30
     31/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    2632
    2733/*****************************************************************************/
    28 /*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    29 /*****************************************************************************/
    30 static void arrayFree(psArray *restrict psArr);
     34static void arrayFree(psArray * restrict psArr);
    3135
    3236/*****************************************************************************/
     37
    3338/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     39
    3440/*****************************************************************************/
    35 psArray* psArrayAlloc(unsigned int nalloc)
     41psArray *psArrayAlloc(unsigned int nalloc)
    3642{
    3743    psArray *psArr = NULL;
    3844
    3945    // Invalid nalloc
    40     if(nalloc < 1) {
     46    if (nalloc < 1) {
    4147        psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc);
    4248        return NULL;
    4349    }
    44 
    4550    // 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);
    4853
    4954    psArr->nalloc = nalloc;
     
    5156
    5257    // Create vector data array
    53     psArr->data = psAlloc(nalloc*sizeof(psPTR));
     58    psArr->data = psAlloc(nalloc * sizeof(psPTR));
    5459
    5560    return psArr;
    5661}
    5762
    58 psArray *psArrayRealloc(unsigned int nalloc, psArray *restrict in)
     63psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in)
    5964{
    6065    // Invalid nalloc
    61     if(nalloc < 1) {
     66    if (nalloc < 1) {
    6267        psError(__func__, "Invalid value for realloc (%d)\n", nalloc);
    6368        return NULL;
    6469    }
    6570
    66     if(in == NULL) {
     71    if (in == NULL) {
    6772        psError(__func__, "Null input vector\n");
    6873        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]);
    7678            }
    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;
    8180        }
     81        // Realloc after decrementation to avoid accessing freed array elements
     82        in->data = psRealloc(in->data, nalloc * sizeof(psPTR));
     83        in->nalloc = nalloc;
     84    }
    8285
    8386    return in;
    8487}
    8588
    86 static void arrayFree(psArray *restrict psArr)
     89static void arrayFree(psArray * restrict psArr)
    8790{
    8891    if (psArr == NULL) {
     
    9598}
    9699
    97 void psArrayElementFree(psArray *restrict psArr)
     100void psArrayElementFree(psArray * restrict psArr)
    98101{
    99102
    100     if(psArr == NULL) {
     103    if (psArr == NULL) {
    101104        return;
    102105    }
    103106
    104     for(int i = 0; i < psArr->n; i++) {
     107    for (int i = 0; i < psArr->n; i++) {
    105108        psFree(psArr->data[i]);
    106109        psArr->data[i] = NULL;
     
    108111}
    109112
    110 psArray* psArraySort(psArray* in, psComparePtrFcn compare)
     113psArray *psArraySort(psArray * in, psComparePtrFcn compare)
    111114{
    112115    if (in == NULL) {
     
    114117    }
    115118
    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);
    119120
    120121    return in;
  • trunk/psLib/src/collections/psArray.h

    r1228 r1407  
     1
    12/** @file  psArray.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-07-15 22:18:02 $
     14 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_ARRAY_H
    20 #define PS_ARRAY_H
     21#    define PS_ARRAY_H
    2122
    22 #include "psType.h"
    23 #include "psCompare.h"
     23#    include "psType.h"
     24#    include "psCompare.h"
    2425
    2526/// @addtogroup Array
     
    3334typedef struct
    3435{
    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 elements
     36    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
    3839}
    3940psArray;
    4041
    4142/*****************************************************************************/
     43
    4244/* FUNCTION PROTOTYPES                                                       */
     45
    4346/*****************************************************************************/
    4447
     
    5154 *
    5255 */
    53 psArray *psArrayAlloc(
    54     unsigned int nalloc                 ///< Total number of elements to make available.
    55 );
     56psArray *psArrayAlloc(unsigned int nalloc       // /< Total number of elements to make available.
     57                     );
    5658
    5759/** Reallocate an array.
     
    6365 *
    6466 */
    65 psArray *psArrayRealloc(
    66     unsigned int nalloc,                ///< Total number of elements to make available.
    67     psArray *restrict psArr            ///< array to reallocate.
    68 );
     67psArray *psArrayRealloc(unsigned int nalloc,    // /< Total number of elements to make available.
     68                        psArray * restrict psArr        // /< array to reallocate.
     69                       );
    6970
    7071/** Deallocate/Dereference elements of an array.
     
    7576 *
    7677 */
    77 void psArrayElementFree(
    78     psArray *restrict psArr    ///< Void pointer array to destroy.
    79 );
     78void psArrayElementFree(psArray * restrict psArr        // /< Void pointer array to destroy.
     79                       );
    8080
    8181/** Sort the array according to an external compare function.
     
    8686 *  @return psArray*       The sorted array.
    8787 */
    88 psArray* psArraySort(psArray* in, psComparePtrFcn compare);
     88psArray *psArraySort(psArray * in, psComparePtrFcn compare);
    8989
    9090/// @}
  • trunk/psLib/src/collections/psBitSet.c

    r1406 r1407  
     1
    12/** @file  psBitSet.c
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819/******************************************************************************/
     20
    1921/*  INCLUDE FILES                                                             */
     22
    2023/******************************************************************************/
    2124#include <string.h>
     
    3134
    3235/******************************************************************************/
     36
    3337/*  DEFINE STATEMENTS                                                         */
    34 /******************************************************************************/
    35 
    36 // None
    37 
    38 /******************************************************************************/
     38
     39/******************************************************************************/
     40
     41// None
     42
     43/******************************************************************************/
     44
    3945/*  TYPE DEFINITIONS                                                          */
    40 /******************************************************************************/
    41 
    42 // None
    43 
    44 /*****************************************************************************/
     46
     47/******************************************************************************/
     48
     49// None
     50
     51/*****************************************************************************/
     52
    4553/*  GLOBAL VARIABLES                                                         */
    46 /*****************************************************************************/
    47 
    48 // None
    49 
    50 /*****************************************************************************/
     54
     55/*****************************************************************************/
     56
     57// None
     58
     59/*****************************************************************************/
     60
    5161/*  FILE STATIC VARIABLES                                                    */
    52 /*****************************************************************************/
    53 
    54 // None
    55 
    56 /*****************************************************************************/
     62
     63/*****************************************************************************/
     64
     65// None
     66
     67/*****************************************************************************/
     68
    5769/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    58 /*****************************************************************************/
    59 static void psBitSetFree(psBitSet *restrict inBitSet);
    60 
     70
     71/*****************************************************************************/
     72static void psBitSetFree(psBitSet * restrict inBitSet);
    6173
    6274/** Private function to create a mask.
     
    7082{
    7183    char mask = (char)0x01;
     84
    7285    // Ignore splint warning about negative bit shifts
    73     /*@i@*/
    74     mask = mask << (bit%8);
     86    /* @i@ */
     87    mask = mask << (bit % 8);
    7588
    7689    return mask;
     
    7891
    7992/*****************************************************************************/
     93
    8094/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    81 /*****************************************************************************/
    82 psBitSet* psBitSetAlloc(int n)
     95
     96/*****************************************************************************/
     97psBitSet *psBitSetAlloc(int n)
    8398{
    8499    int numBytes = 0;
    85100    psBitSet *newObj = NULL;
    86101
    87     if(n <= 0) {
     102    if (n <= 0) {
    88103        psError(__func__, " : Line %d - Allocation size must be > 0: size = %d", __LINE__, n);
    89104        return 0;
    90105    }
    91106
    92     numBytes = ceil(n/8.0);
     107    numBytes = ceil(n / 8.0);
    93108    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);
    98113    newObj->n = numBytes;
    99114
    100115    // 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__);
    105120    }
    106121
     
    110125}
    111126
    112 static void psBitSetFree(psBitSet *restrict inBitSet)
    113 {
    114     if(inBitSet == NULL) {
     127static void psBitSetFree(psBitSet * restrict inBitSet)
     128{
     129    if (inBitSet == NULL) {
    115130        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    116131        return;
     
    119134}
    120135
    121 psBitSet* psBitSetSet(psBitSet *inBitSet, int bit)
    122 {
    123     char* byte = NULL;
    124 
    125     if(inBitSet == NULL) {
     136psBitSet *psBitSetSet(psBitSet * inBitSet, int bit)
     137{
     138    char *byte = NULL;
     139
     140    if (inBitSet == NULL) {
    126141        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    127142        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    }
    138150    // 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;
    140152    *byte |= mask(bit);
    141153
     
    143155}
    144156
    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 
     157bool 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    }
    162171    // 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) {
    165174        return 0;
    166175    }
     
    169178}
    170179
    171 psBitSet* psBitSetOp(psBitSet *outBitSet, const psBitSet *restrict inBitSet1, char *operator,
    172                      const psBitSet *restrict inBitSet2)
     180psBitSet *psBitSetOp(psBitSet * outBitSet, const psBitSet * restrict inBitSet1, char *operator,
     181                     const psBitSet * restrict inBitSet2)
    173182{
    174183    int i = 0;
     
    179188    char *inBits2 = NULL;
    180189
    181     if(inBitSet1 == NULL) {
     190    if (inBitSet1 == NULL) {
    182191        psError(__func__, " : Line %d - Null psBitSet for inBitSet1 argument", __LINE__);
    183192        return outBitSet;
    184193    }
    185194
    186     if(operator == NULL) {
     195    if (operator == NULL) {
    187196        psError(__func__, " : Line %d - Null input operator\n", __LINE__);
    188197        return outBitSet;
    189198    }
    190199
    191     if(inBitSet2 == NULL) {
     200    if (inBitSet2 == NULL) {
    192201        psError(__func__, " : Line %d - Null psBitSet for inBitSet2 argument", __LINE__);
    193202        return outBitSet;
    194203    }
    195204
    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) {
    201210        psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__);
    202211        return outBitSet;
     
    209218
    210219    tempChar = toupper(operator[0]);
    211     switch(tempChar) {
     220    switch (tempChar) {
    212221    case 'A':
    213         for(i=0; i<n; i++) {
     222        for (i = 0; i < n; i++) {
    214223            outBits[i] = inBits1[i] & inBits2[i];
    215224        }
    216225        break;
    217226    case 'O':
    218         for(i=0; i<n; i++) {
     227        for (i = 0; i < n; i++) {
    219228            outBits[i] = inBits1[i] | inBits2[i];
    220229        }
    221230        break;
    222231    case 'X':
    223         for(i=0; i<n; i++) {
     232        for (i = 0; i < n; i++) {
    224233            outBits[i] = inBits1[i] ^ inBits2[i];
    225234        }
     
    232241}
    233242
    234 psBitSet* psBitSetNot(psBitSet *outBitSet, const psBitSet *restrict inBitSet)
     243psBitSet *psBitSetNot(psBitSet * outBitSet, const psBitSet * restrict inBitSet)
    235244{
    236245    int i = 0;
     
    239248    char *inBits = NULL;
    240249
    241     if(inBitSet == NULL) {
     250    if (inBitSet == NULL) {
    242251        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    243252        return outBitSet;
     
    245254
    246255    n = inBitSet->n;
    247     if(n == 0) {
     256    if (n == 0) {
    248257        psError(__func__, " : Line %d - No elements in inBitSet", __LINE__);
    249258        return outBitSet;
    250259    }
    251260
    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) {
    257266        psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__);
    258267        return outBitSet;
     
    262271    inBits = inBitSet->bits;
    263272
    264     for(i=0; i<n; i++) {
     273    for (i = 0; i < n; i++) {
    265274        outBits[i] = ~inBits[i];
    266275    }
     
    269278}
    270279
    271 char *psBitSetToString(const psBitSet *restrict inBitSet)
     280char *psBitSetToString(const psBitSet * restrict inBitSet)
    272281{
    273282    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';
    282292    }
    283293
  • trunk/psLib/src/collections/psBitSet.h

    r1172 r1407  
     1
    12/** @file  psBitSet.h
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-07-01 21:48:11 $
     15 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PSBITSET_H
    21 #define PSBITSET_H
     22#    define PSBITSET_H
    2223
    2324/// @addtogroup BitSet
     
    2526
    2627/******************************************************************************/
     28
    2729/*  TYPE DEFINITIONS                                                          */
     30
    2831/******************************************************************************/
    2932
     
    3538typedef struct
    3639{
     40
    3741    int n;      /**< Number of bytes in the array */
     42
    3843    char *bits; /**< Aray of bytes holding bits */
    3944}
     
    4146
    4247/*****************************************************************************/
     48
    4349/* FUNCTION PROTOTYPES                                                       */
     50
    4451/*****************************************************************************/
    4552
     
    5158 *  @return  psBitSet*: Pointer to struct containing array of bits and size of array.
    5259 */
     60
    5361/*@null@*/
    54 psBitSet* psBitSetAlloc(
    55     int n   /**< Number of bits in psBitSet array */
    56 );
     62
     63psBitSet *psBitSetAlloc(int n
     64                        /**< Number of bits in psBitSet array */
     65                       );
    5766
    5867/** Set a bit.
     
    6473 *  @return  psBitSet*: Pointer to struct containing psBitSet.
    6574 */
    66 psBitSet* psBitSetSet(
    67     /*@returned@*/psBitSet *restrict inMask,  /**< Pointer to psBitSet to be set. */
    68     int bit                     /**< Bit to be set. */
     75psBitSet *psBitSetSet(
     76
     77    /* @returned@ */ psBitSet * restrict inMask,
     78    /**< Pointer to psBitSet to be set. */
     79
     80    int bit/**< Bit to be set. */
    6981);
    7082
     
    7890 *  @return  int: Value of bit, either one or zero.
    7991 */
    80 bool psBitSetTest(
    81     const psBitSet *restrict inMask,    /**< Pointer psBitSet to be tested. */
    82     int bit                             /**< Bit to be tested. */
    83 );
     92
     93bool psBitSetTest(const psBitSet * restrict inMask,
     94                  /**< Pointer psBitSet to be tested. */
     95
     96                  int bit               /**< Bit to be tested. */
     97                 );
    8498
    8599/** Perform a binary operation on two psBitSets
     
    90104 *  @return  psBitSet*: Pointer to struct containing result of binary operation.
    91105 */
    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 */
     106psBitSet *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 */
    97118);
    98119
     
    103124 *  @return  psBitSet*: Pointer to struct containing result of operation.
    104125 */
    105 psBitSet* psBitSetNot(
    106     psBitSet *outBitSet,                /**< Resulting psBitSet from operation */
    107     const psBitSet *restrict inBitSet   /**< Input psBitSet */
    108 );
     126
     127psBitSet *psBitSetNot(psBitSet * outBitSet,
     128                      /**< Resulting psBitSet from operation */
     129
     130                      const psBitSet * restrict inBitSet
     131                      /**< Input psBitSet */
     132                     );
    109133
    110134/** Convert the psBitSet to a string of ones and zeros.
     
    115139 *  @return  char*: Pointer to character array containing string data.
    116140 */
    117 char *psBitSetToString(
    118     const psBitSet *restrict inMask /**< psBitSet to convert */
    119 );
     141
     142char *psBitSetToString(const psBitSet * restrict inMask
     143                       /**< psBitSet to convert */
     144                      );
    120145
    121146/// @}
  • trunk/psLib/src/collections/psCompare.c

    r1393 r1407  
     1
    12/** @file psCompare.c
    23 *  @brief Comparison functions for sorting routines
     
    67 *  @author Robert Daniel DeSonia, MHPCC
    78 *
    8  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2004-08-05 19:38:52 $
     9 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
     10 *  @date $Date: 2004-08-07 00:06:06 $
    1011 *
    1112 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
  • trunk/psLib/src/collections/psCompare.h

    r1111 r1407  
    11#if !defined(PS_COMPARE_H)
    2 #define PS_COMPARE_H
     2#    define PS_COMPARE_H
    33
    44/** @file psCompare.h
     
    99 *  @ingroup Compare
    1010 *
    11  *  @version $Revision: 1.1 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-06-28 20:36:37 $
     11 *  @version $Revision: 1.2 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1313 *
    1414 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2626 *                   than, equal to, or greater than the second.
    2727 */
    28 typedef int (*psComparePtrFcn)(const void** a, const void** b);
     28typedef int (*psComparePtrFcn) (const void **a, const void **b);
    2929
    3030/** A comparison function for sorting.
     
    3434 *                   than, equal to, or greater than the second.
    3535 */
    36 typedef int (*psCompareFcn)(const void* a, const void* b);
     36typedef int (*psCompareFcn) (const void *a, const void *b);
    3737
    3838/** Compare function of psS8 data.  For use with psListSort.
     
    4242 *                   than, equal to, or greater than the second.
    4343 */
    44 int psCompareS8Ptr(const void** a, const void** b);
     44int psCompareS8Ptr(const void **a, const void **b);
    4545
    4646/** Compare function of psS16 data.  For use with psListSort.
     
    5050 *                   than, equal to, or greater than the second.
    5151 */
    52 int psCompareS16Ptr(const void** a, const void** b);
     52int psCompareS16Ptr(const void **a, const void **b);
    5353
    5454/** Compare function of psS32 data.  For use with psListSort.
     
    5858 *                   than, equal to, or greater than the second.
    5959 */
    60 int psCompareS32Ptr(const void** a, const void** b);
     60int psCompareS32Ptr(const void **a, const void **b);
    6161
    6262/** Compare function of psS64 data.  For use with psListSort.
     
    6666 *                   than, equal to, or greater than the second.
    6767 */
    68 int psCompareS64Ptr(const void** a, const void** b);
     68int psCompareS64Ptr(const void **a, const void **b);
    6969
    7070/** Compare function of psU8 data.  For use with psListSort.
     
    7474 *                   than, equal to, or greater than the second.
    7575 */
    76 int psCompareU8Ptr(const void** a, const void** b);
     76int psCompareU8Ptr(const void **a, const void **b);
    7777
    7878/** Compare function of psU16 data.  For use with psListSort.
     
    8282 *                   than, equal to, or greater than the second.
    8383 */
    84 int psCompareU16Ptr(const void** a, const void** b);
     84int psCompareU16Ptr(const void **a, const void **b);
    8585
    8686/** Compare function of psU32 data.  For use with psListSort.
     
    9090 *                   than, equal to, or greater than the second.
    9191 */
    92 int psCompareU32Ptr(const void** a, const void** b);
     92int psCompareU32Ptr(const void **a, const void **b);
    9393
    9494/** Compare function of psU64 data.  For use with psListSort.
     
    9898 *                   than, equal to, or greater than the second.
    9999 */
    100 int psCompareU64Ptr(const void** a, const void** b);
     100int psCompareU64Ptr(const void **a, const void **b);
    101101
    102102/** Compare function of psF32 data.  For use with psListSort.
     
    106106 *                   than, equal to, or greater than the second.
    107107 */
    108 int psCompareF32Ptr(const void** a, const void** b);
     108int psCompareF32Ptr(const void **a, const void **b);
    109109
    110110/** Compare function of psF64 data.  For use with psListSort.
     
    114114 *                   than, equal to, or greater than the second.
    115115 */
    116 int psCompareF64Ptr(const void** a, const void** b);
     116int psCompareF64Ptr(const void **a, const void **b);
    117117
    118118/** Compare function of psS8 data.  For use with psListSort for descending ordering.
     
    122122 *                   than, equal to, or less than the second.
    123123 */
    124 int psCompareDescendingS8Ptr(const void** a, const void** b);
     124int psCompareDescendingS8Ptr(const void **a, const void **b);
    125125
    126126/** Compare function of psS16 data.  For use with psListSort for descending ordering.
     
    130130 *                   than, equal to, or less than the second.
    131131 */
    132 int psCompareDescendingS16Ptr(const void** a, const void** b);
     132int psCompareDescendingS16Ptr(const void **a, const void **b);
    133133
    134134/** Compare function of psS32 data.  For use with psListSort for descending ordering.
     
    138138 *                   than, equal to, or less than the second.
    139139 */
    140 int psCompareDescendingS32Ptr(const void** a, const void** b);
     140int psCompareDescendingS32Ptr(const void **a, const void **b);
    141141
    142142/** Compare function of psS64 data.  For use with psListSort for descending ordering.
     
    146146 *                   than, equal to, or less than the second.
    147147 */
    148 int psCompareDescendingS64Ptr(const void** a, const void** b);
     148int psCompareDescendingS64Ptr(const void **a, const void **b);
    149149
    150150/** Compare function of psU8 data.  For use with psListSort for descending ordering.
     
    154154 *                   than, equal to, or less than the second.
    155155 */
    156 int psCompareDescendingU8Ptr(const void** a, const void** b);
     156int psCompareDescendingU8Ptr(const void **a, const void **b);
    157157
    158158/** Compare function of psU16 data.  For use with psListSort for descending ordering.
     
    162162 *                   than, equal to, or less than the second.
    163163 */
    164 int psCompareDescendingU16Ptr(const void** a, const void** b);
     164int psCompareDescendingU16Ptr(const void **a, const void **b);
    165165
    166166/** Compare function of psU32 data.  For use with psListSort for descending ordering.
     
    170170 *                   than, equal to, or lessg than the second.
    171171 */
    172 int psCompareDescendingU32Ptr(const void** a, const void** b);
     172int psCompareDescendingU32Ptr(const void **a, const void **b);
    173173
    174174/** Compare function of psU64 data.  For use with psListSort for descending ordering.
     
    178178 *                   than, equal to, or lessg than the second.
    179179 */
    180 int psCompareDescendingU64Ptr(const void** a, const void** b);
     180int psCompareDescendingU64Ptr(const void **a, const void **b);
    181181
    182182/** Compare function of psF32 data.  For use with psListSort for descending ordering.
     
    186186 *                   than, equal to, or lessg than the second.
    187187 */
    188 int psCompareDescendingF32Ptr(const void** a, const void** b);
     188int psCompareDescendingF32Ptr(const void **a, const void **b);
    189189
    190190/** Compare function of psF64 data.  For use with psListSort for descending ordering.
     
    194194 *                   than, equal to, or lessg than the second.
    195195 */
    196 int psCompareDescendingF64Ptr(const void** a, const void** b);
     196int psCompareDescendingF64Ptr(const void **a, const void **b);
    197197
    198198/** Compare function of psS8 data.
     
    202202 *                   than, equal to, or greater than the second.
    203203 */
    204 int psCompareS8(const void* a, const void* b);
     204int psCompareS8(const void *a, const void *b);
    205205
    206206/** Compare function of psS16 data.
     
    210210 *                   than, equal to, or greater than the second.
    211211 */
    212 int psCompareS16(const void* a, const void* b);
     212int psCompareS16(const void *a, const void *b);
    213213
    214214/** Compare function of psS32 data.
     
    218218 *                   than, equal to, or greater than the second.
    219219 */
    220 int psCompareS32(const void* a, const void* b);
     220int psCompareS32(const void *a, const void *b);
    221221
    222222/** Compare function of psS64 data.
     
    226226 *                   than, equal to, or greater than the second.
    227227 */
    228 int psCompareS64(const void* a, const void* b);
     228int psCompareS64(const void *a, const void *b);
    229229
    230230/** Compare function of psU8 data.
     
    234234 *                   than, equal to, or greater than the second.
    235235 */
    236 int psCompareU8(const void* a, const void* b);
     236int psCompareU8(const void *a, const void *b);
    237237
    238238/** Compare function of psU16 data.
     
    242242 *                   than, equal to, or greater than the second.
    243243 */
    244 int psCompareU16(const void* a, const void* b);
     244int psCompareU16(const void *a, const void *b);
    245245
    246246/** Compare function of psU32 data.
     
    250250 *                   than, equal to, or greater than the second.
    251251 */
    252 int psCompareU32(const void* a, const void* b);
     252int psCompareU32(const void *a, const void *b);
    253253
    254254/** Compare function of psU64 data.
     
    258258 *                   than, equal to, or greater than the second.
    259259 */
    260 int psCompareU64(const void* a, const void* b);
     260int psCompareU64(const void *a, const void *b);
    261261
    262262/** Compare function of psF32 data.
     
    266266 *                   than, equal to, or greater than the second.
    267267 */
    268 int psCompareF32(const void* a, const void* b);
     268int psCompareF32(const void *a, const void *b);
    269269
    270270/** Compare function of psF64 data.
     
    274274 *                   than, equal to, or greater than the second.
    275275 */
    276 int psCompareF64(const void* a, const void* b);
     276int psCompareF64(const void *a, const void *b);
    277277
    278278/** Compare function of psS8 data.
     
    282282 *                   than, equal to, or less than the second.
    283283 */
    284 int psCompareDescendingS8(const void* a, const void* b);
     284int psCompareDescendingS8(const void *a, const void *b);
    285285
    286286/** Compare function of psS16 data.
     
    290290 *                   than, equal to, or less than the second.
    291291 */
    292 int psCompareDescendingS16(const void* a, const void* b);
     292int psCompareDescendingS16(const void *a, const void *b);
    293293
    294294/** Compare function of psS32 data.
     
    298298 *                   than, equal to, or less than the second.
    299299 */
    300 int psCompareDescendingS32(const void* a, const void* b);
     300int psCompareDescendingS32(const void *a, const void *b);
    301301
    302302/** Compare function of psS64 data.
     
    306306 *                   than, equal to, or less than the second.
    307307 */
    308 int psCompareDescendingS64(const void* a, const void* b);
     308int psCompareDescendingS64(const void *a, const void *b);
    309309
    310310/** Compare function of psU8 data.
     
    314314 *                   than, equal to, or less than the second.
    315315 */
    316 int psCompareDescendingU8(const void* a, const void* b);
     316int psCompareDescendingU8(const void *a, const void *b);
    317317
    318318/** Compare function of psU16 data.
     
    322322 *                   than, equal to, or less than the second.
    323323 */
    324 int psCompareDescendingU16(const void* a, const void* b);
     324int psCompareDescendingU16(const void *a, const void *b);
    325325
    326326/** Compare function of psU32 data.
     
    330330 *                   than, equal to, or lessg than the second.
    331331 */
    332 int psCompareDescendingU32(const void* a, const void* b);
     332int psCompareDescendingU32(const void *a, const void *b);
    333333
    334334/** Compare function of psU64 data.
     
    338338 *                   than, equal to, or lessg than the second.
    339339 */
    340 int psCompareDescendingU64(const void* a, const void* b);
     340int psCompareDescendingU64(const void *a, const void *b);
    341341
    342342/** Compare function of psF32 data.
     
    346346 *                   than, equal to, or lessg than the second.
    347347 */
    348 int psCompareDescendingF32(const void* a, const void* b);
     348int psCompareDescendingF32(const void *a, const void *b);
    349349
    350350/** Compare function of psF64 data.
     
    354354 *                   than, equal to, or lessg than the second.
    355355 */
    356 int psCompareDescendingF64(const void* a, const void* b);
    357 
    358 
     356int psCompareDescendingF64(const void *a, const void *b);
    359357
    360358/// @}
  • trunk/psLib/src/collections/psList.c

    r1406 r1407  
     1
    12/** @file psList.c
    23 *  @brief Support for doubly linked lists
     
    67 *  @author Robert Daniel DeSonia, MHPCC
    78 *
    8  *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2004-08-06 22:34:05 $
     9 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
     10 *  @date $Date: 2004-08-07 00:06:06 $
    1011 *
    1112 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516#include <stdbool.h>
    1617#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.
    1819
    1920#include "psError.h"
     
    2425#include "psLogMsg.h"
    2526
    26 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head
    27 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail
     27#define ITER_INIT_HEAD ((void *)1)         // next iteration should return head
     28#define ITER_INIT_TAIL ((void *)2)         // next iteration should return tail
    2829
    2930// 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 
     31static psListElem *listGetIterator(psList * list);
     32static int listGetIteratorIndex(psList * list);
     33static void listSetIterator(psList * list, int where, bool lockList);
     34static void listFree(psList * list);
    3535
    3636psList *psListAlloc(void *data)
    3737{
    3838    psList *list = psAlloc(sizeof(psList));
    39     p_psMemSetDeallocator(list,(psFreeFcn)listFree);
     39
     40    p_psMemSetDeallocator(list, (psFreeFcn) listFree);
    4041
    4142    list->size = 0;
     
    4445    list->iterIndex = PS_LIST_HEAD;
    4546
    46     pthread_mutex_init(&(list->lock),NULL)
     47    pthread_mutex_init(&(list->lock), NULL)
    4748    ;
    4849
     
    5455}
    5556
    56 static void listFree(psList *list)
     57static void listFree(psList * list)
    5758{
    5859    if (list == NULL) {
     
    6364    ;
    6465
    65     for(psListElem *ptr = list->head; ptr != NULL; ) {
     66    for (psListElem * ptr = list->head; ptr != NULL;) {
    6667        psListElem *next = ptr->next;
    6768
     
    8081}
    8182
    82 bool psListAdd(psList *list, void *data, int where)
    83 {
    84     psListElem* position;
    85     psListElem* elem;
     83bool psListAdd(psList * list, void *data, int where)
     84{
     85    psListElem *position;
     86    psListElem *elem;
    8687    int cursorIndex = 0;
    8788
     
    9596
    9697    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);
    101100        return false;
    102101    }
     
    108107
    109108    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);
    113111        where = PS_LIST_TAIL;
    114112    }
     
    138136
    139137        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        }
    144141        // insert our new element in front of the given position
    145142        elem->prev = position->prev;
     
    147144        position->prev = elem;
    148145
    149         if (elem->prev == NULL) { // must be front of list
     146        if (elem->prev == NULL) {          // must be front of list
    150147            list->head = elem;
    151148        } else {
     
    167164
    168165/*****************************************************************************/
     166
    169167/*
    170168 * Remove an element from a list
    171169 */
    172 bool psListRemove(psList *list, void *data, int which)
    173 {
    174     psListElem *elem = NULL;  // element to remove
     170bool psListRemove(psList * list, void *data, int which)
     171{
     172    psListElem *elem = NULL;    // element to remove
    175173    int cursorIndex = 0;
    176174
    177175    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__);
    179177        return false;
    180178    }
    181 
    182179    // get exclusive access to list so that other threads will not get in the way.
    183180    pthread_mutex_lock(&list->lock)
     
    187184        // search list for the data item.
    188185
    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) {
    191189            if (ptr->data == data) {
    192190                which = i;
     
    201199        }
    202200    }
    203 
    204201    // position the list's cursor to the desired location
    205     listSetIterator(list,which,false);
     202    listSetIterator(list, which, false);
    206203    elem = listGetIterator(list);
    207204    cursorIndex = listGetIteratorIndex(list);
    208205
    209206    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);
    211208        return false;
    212209    }
     
    214211    list->size--;
    215212
    216     if (elem->prev == NULL) { // head of list?
     213    if (elem->prev == NULL) {              // head of list?
    217214        list->head = elem->next;
    218215    } else {
     
    220217    }
    221218
    222     if (elem->next == NULL) { // tail of list?
     219    if (elem->next == NULL) {              // tail of list?
    223220        list->tail = elem->prev;
    224221
     
    246243}
    247244
    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;
     245void psListSetIterator(psList * list, int where)
     246{
     247    listSetIterator(list, where, true);
     248}
     249
     250void listSetIterator(psList * list, int where, bool lockList)
     251{
     252    psListElem *cursor;
    256253    int position;
    257254
    258255    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__);
    260257        return;
    261258    }
     
    291288        if (cursor != NULL) {
    292289            list->iter = cursor->prev;
    293             list->iterIndex = position-1;
     290            list->iterIndex = position - 1;
    294291        }
    295292        break;
     
    301298        if (cursor != NULL) {
    302299            list->iter = cursor->next;
    303             list->iterIndex = position+1;
     300            list->iterIndex = position + 1;
    304301        }
    305302        break;
     
    309306
    310307    default:
    311         if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above
    312             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.");
    313310        } else {
    314311            cursor = listGetIterator(list);
    315             if (cursor == NULL) { // reset the iterator if it is invalid
     312            if (cursor == NULL) {      // reset the iterator if it is invalid
    316313                list->iter = ITER_INIT_HEAD;
    317314                list->iterIndex = 0;
     
    321318
    322319            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);
    326324                }
    327325            } 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);
    331330                }
    332331            }
     
    341340}
    342341
    343 psListElem* listGetIterator(psList* list)
     342psListElem *listGetIterator(psList * list)
    344343{
    345344    if (list == NULL) {
     
    349348    if (list->iter == ITER_INIT_HEAD) {
    350349        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
     357int listGetIteratorIndex(psList * list)
    360358{
    361359    if (list->iter == ITER_INIT_HEAD) {
    362360        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
     368void *psListGet(psList * list, int which)
     369{
     370    psListElem *element;
     371
     372    psListSetIterator(list, which);
    376373    element = listGetIterator(list);
    377374
     
    382379    }
    383380}
     381
    384382/*
    385383 * and now return the previous/next element of the list
    386384 */
    387 void *psListGetNext(psList *list)
     385void *psListGetNext(psList * list)
    388386{
    389387    return psListGet(list, PS_LIST_NEXT);
    390388}
    391389
    392 void *psListGetPrevious(psList *list)
     390void *psListGetPrevious(psList * list)
    393391{
    394392    return psListGet(list, PS_LIST_PREVIOUS);
    395393}
    396394
    397 void *psListGetCurrent(psList *list)
     395void *psListGetCurrent(psList * list)
    398396{
    399397    return psListGet(list, PS_LIST_CURRENT);
     
    403401 * Convert a psList to/from a psVoidPtrArray
    404402 */
    405 psArray* psListToArray(psList* restrict list)
    406 {
    407     psListElem* ptr;
     403psArray *psListToArray(psList * restrict list)
     404{
     405    psListElem *ptr;
    408406    unsigned int n;
    409     psArray* restrict arr;
     407    psArray *restrict arr;
    410408
    411409    if (list == NULL) {
     
    431429}
    432430
    433 psList* psArrayToList(psArray* arr)
     431psList *psArrayToList(psArray * arr)
    434432{
    435433    unsigned int n;
    436     psList* list; // list of elements
     434    psList *list;              // list of elements
    437435
    438436    if (arr == NULL) {
     
    443441    n = arr->n;
    444442    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);
    446444    }
    447445
     
    449447}
    450448
    451 
    452 psList* psListSort(psList* list, psComparePtrFcn compare)
    453 {
    454     psArray* arr;
     449psList *psListSort(psList * list, psComparePtrFcn compare)
     450{
     451    psArray *arr;
     452
    455453    if (list == NULL) {
    456454        return NULL;
    457455    }
    458 
    459456    // convert to indexable vector for use by qsort.
    460457    arr = psListToArray(list);
    461458    psFree(list);
    462459
    463     arr = psArraySort(arr,compare);
     460    arr = psArraySort(arr, compare);
    464461
    465462    // convert back to linked list
  • trunk/psLib/src/collections/psList.h

    r1228 r1407  
    11#if !defined(PS_LIST_H)
    2 #define PS_LIST_H
     2#    define PS_LIST_H
    33
    44/** @file psList.h
     
    1010 *  @ingroup LinkedList
    1111 *
    12  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-07-15 22:18:02 $
     12 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1414 *
    1515 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1616 */
    1717
    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.
    2020
    21 #include "psCompare.h"
    22 #include "psArray.h"
     21#    include "psCompare.h"
     22#    include "psArray.h"
    2323
    2424/** @addtogroup LinkedList
     
    3333 */
    3434enum {
    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)
     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)
    4141};
    4242
     
    4444typedef struct psListElem
    4545{
    46     struct psListElem *prev;            ///< previous link in list
    47     struct psListElem *next;            ///< next link in list
    48     void *data;                         ///< real data item
     46    struct psListElem *prev;    // /< previous link in list
     47    struct psListElem *next;    // /< next link in list
     48    void *data;                 // /< real data item
    4949}
    5050psListElem;
     
    5757typedef struct
    5858{
    59     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
     59    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
    6565}
    6666psList;
     
    7070 *  @return psList*     A new psList object.
    7171 */
    72 psList* psListAlloc(
    73     void *data
    74     ///< initial data item; may be NULL if no an empty psList is desired
    75 )
     72psList *psListAlloc(void *data
     73                    // /< initial data item; may be NULL if no an empty psList is desired
     74                   )
    7675;
    7776
     
    8180 *                      NULL, the return value will also be NULL.
    8281 */
    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 );
     82bool 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              );
    8886
    8987/** Remove an item from a list.  If which parameter is PS_LIST_UNKNOWN,
     
    9189 *  @return bool        TRUE if element is successfully removed, otherwise FALSE.
    9290 */
    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 );
     91bool 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                 );
    10198
    10299/** Retrieve an item from a list.
     
    107104 *                      NULL is returned.
    108105 */
    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 );
     106void *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               );
    113109
    114110/** Set the iterator of the list to a given position.  If where is invalid the
     
    116112 *
    117113 */
    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 );
     114void psListSetIterator(psList * restrict list,  // /< list to retrieve element from
     115                       int where        // /< index number, PS_LIST_HEAD, or PS_LIST_TAIL
     116                      );
    122117
    123118/** Get next element relative to the iterator.  This also moves the iterator to
     
    128123 *                      parameter was NULL.
    129124 */
    130 void* psListGetNext(
    131     psList* restrict list              ///< list to retrieve element from
    132 );
     125void *psListGetNext(psList * restrict list      // /< list to retrieve element from
     126                   );
    133127
    134128/** Get current element according to the psList's iterator cursor.  This does
     
    139133 *                      iterator is not valid or list parameter was NULL.
    140134 */
    141 void* psListGetCurrent(
    142     psList* restrict list              ///< list to retrieve element from
    143 );
     135void *psListGetCurrent(psList * restrict list   // /< list to retrieve element from
     136                      );
    144137
    145138/** Get previous element relative to list's iterator. This also moves the
     
    150143 *                      parameter was NULL.
    151144 */
    152 void* psListGetPrevious(
    153     psList* restrict list              ///< list to retrieve element from
    154 );
     145void *psListGetPrevious(psList * restrict list  // /< list to retrieve element from
     146                       );
    155147
    156148/** Convert a linked list to an array
     
    159151 *                      or NULL if the given dlist parameter is NULL.
    160152 */
    161 psArray* psListToArray(
    162     psList *dlist                      ///< List to convert
    163 );
     153psArray *psListToArray(psList * dlist   // /< List to convert
     154                      );
    164155
    165156/** Convert array to a doubly-linked list
     
    168159 *                      or NULL is the given arr parameter is NULL.
    169160 */
    170 psList* psArrayToList(
    171     psArray* arr                      ///< vector to convert
    172 );
     161psList *psArrayToList(psArray * arr     // /< vector to convert
     162                     );
    173163
    174 psList* psListSort(psList* list, psComparePtrFcn compare);
     164psList *psListSort(psList * list, psComparePtrFcn compare);
    175165
    176166/// @} End of DataGroup Functions
    177167
    178168#endif
    179 
  • trunk/psLib/src/collections/psMetadata.c

    r1406 r1407  
     1
    12/** @file  psMetadata.c
    23*
     
    1112*  @author Ross Harman, MHPCC
    1213*
    13 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    14 *  @date $Date: 2004-08-06 22:34:05 $
     14*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     15*  @date $Date: 2004-08-07 00:06:06 $
    1516*
    1617*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225#include<stdio.h>
     
    3437#include "psString.h"
    3538
    36 
    3739/******************************************************************************/
     40
    3841/*  DEFINE STATEMENTS                                                         */
     42
    3943/******************************************************************************/
    4044
     
    5660
    5761/******************************************************************************/
     62
    5863/*  TYPE DEFINITIONS                                                          */
     64
    5965/******************************************************************************/
    6066
     
    6268
    6369/*****************************************************************************/
     70
    6471/*  GLOBAL VARIABLES                                                         */
     72
    6573/*****************************************************************************/
    6674
     
    6876
    6977/*****************************************************************************/
     78
    7079/*  FILE STATIC VARIABLES                                                    */
     80
    7181/*****************************************************************************/
    7282
     
    7484
    7585/*****************************************************************************/
     86
    7687/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    77 /*****************************************************************************/
    78 static void metadataItemFree( psMetadataItem *metadataItem )
     88
     89/*****************************************************************************/
     90static void metadataItemFree(psMetadataItem * metadataItem)
    7991{
    8092    psMetadataType type;
     
    8294    type = metadataItem->type;
    8395
    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 ||
    93105            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
     111static void metadataFree(psMetadata * metadata)
     112{
     113    if (metadata == NULL) {
     114        return;
     115    }
     116    psFree(metadata->list);
     117    psFree(metadata->table);
     118}
     119
     120/*****************************************************************************/
     121
    112122/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    113 /*****************************************************************************/
    114 
    115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... )
     123
     124/*****************************************************************************/
     125
     126psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...)
    116127{
    117128    va_list argPtr;
     
    119130
    120131    // Get the variable list parameters to pass to allocation function
    121     va_start( argPtr, comment );
     132    va_start(argPtr, comment);
    122133
    123134    // Call metadata item allocation
    124     metadataItem = psMetadataItemAllocV( name, type, comment, argPtr );
     135    metadataItem = psMetadataItemAllocV(name, type, comment, argPtr);
    125136
    126137    // Clean up stack after variable arguement has been used
    127     va_end( argPtr );
     138    va_end(argPtr);
    128139
    129140    return metadataItem;
    130141}
    131142
    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 
     143psMetadataItem *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    }
    141152    // 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    }
    147157    // Set deallocator
    148     p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree );
     158    p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree);
    149159
    150160    // 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) {
    153163        // Per SDRS, null isn't allowed, must use "" instead
    154         strncpy( metadataItem->comment, "", MAX_STRING_LENGTH );
     164        strncpy(metadataItem->comment, "", MAX_STRING_LENGTH);
    155165    } else {
    156         strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH );
     166        strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH);
    157167    }
    158168
    159169    // Set metadata item unique id
    160     *( int* ) ( &metadataItem->id ) = ++metadataId;
     170    *(int *)(&metadataItem->id) = ++metadataId;
    161171
    162172    // Set metadata item type
     
    164174
    165175    // Set metadata item value
    166     switch(type) {
     176    switch (type) {
    167177    case PS_META_BOOL:
    168         metadataItem->data.B = ( bool ) va_arg( argPtr, int );
     178        metadataItem->data.B = (bool) va_arg(argPtr, int);
     179
    169180        break;
    170181    case PS_META_S32:
    171         metadataItem->data.S32 = va_arg( argPtr, psS32 );
     182        metadataItem->data.S32 = va_arg(argPtr, psS32);
    172183        break;
    173184    case PS_META_F32:
    174         metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64 );
     185        metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64);
    175186        break;
    176187    case PS_META_F64:
    177         metadataItem->data.F64 = va_arg( argPtr, psF64 );
     188        metadataItem->data.F64 = va_arg(argPtr, psF64);
    178189        break;
    179190    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
    181193        break;
    182194    case PS_META_IMG:
     
    186198    case PS_META_UNKNOWN:
    187199    default:
    188         psError( __func__, "Invalid psMetadataType: %d", type );
     200        psError(__func__, "Invalid psMetadataType: %d", type);
    189201    }
    190202
    191203    // 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);
    194206
    195207    // Allocate metadata items with same name.
    196     metadataItem->items = psListAlloc( NULL );
     208    metadataItem->items = psListAlloc(NULL);
    197209
    198210    return metadataItem;
    199211}
    200212
    201 psMetadata *psMetadataAlloc( void )
    202 {
    203     psList * list = NULL;
     213psMetadata *psMetadataAlloc(void)
     214{
     215    psList *list = NULL;
    204216    psHash *table = NULL;
    205217    psMetadata *metadata = NULL;
    206218
    207219    // 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    }
    213224    // Set deallocator
    214     p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree );
     225    p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree);
    215226
    216227    // 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");
    225236    }
    226237
     
    231242}
    232243
    233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem )
    234 {
    235     char * key = NULL;
     244bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem)
     245{
     246    char *key = NULL;
    236247    psHash *mdTable = NULL;
    237248    psList *mdList = NULL;
     
    239250    psMetadataType type = PS_META_ITEM_SET;
    240251
    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");
    248259        return false;
    249260    }
     
    252263
    253264    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");
    262273        return false;
    263274    }
    264275
    265276    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    }
    271281    // 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) {
    274284
    275285        // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so
    276286        // 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);
    280289            return false;
    281290        }
    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);
    289304            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    }
    299307
    300308    // 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);
    304312        return false;
    305313    }
     
    308316}
    309317
    310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,
    311                     const char *comment, ... )
     318bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type,
     319                   const char *comment, ...)
    312320{
    313321    va_list argPtr;
    314322    psMetadataItem *metadataItem = NULL;
    315323
    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 needed here
    328     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);
    329337
    330338    return true;
    331339}
    332340
    333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key )
     341bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key)
    334342{
    335343    int numChildren = 0;
     
    340348
    341349    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");
    344352        return false;
    345353    }
    346354
    347355    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    }
    353360    // Select removal by key or index
    354     if(key != NULL) {
     361    if (key != NULL) {
    355362
    356363        // 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);
    360367            return false;
    361368        }
    362369
    363370        numChildren = entry->items->size;
    364         if(entry->type == PS_META_ITEM_SET && numChildren > 0) {
     371        if (entry->type == PS_META_ITEM_SET && numChildren > 0) {
    365372
    366373            // 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);
    372379                    return false;
    373380                }
    374                 entryChild = psListGetNext( entry->items );
     381                entryChild = psListGetNext(entry->items);
    375382            }
    376383        }
    377 
    378384        // 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);
    381387            return false;
    382388        }
    383 
    384389        // 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);
    387392            return false;
    388393        }
     
    390395
    391396        // 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);
    395400            return false;
    396401        }
    397402
    398403        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);
    401406            return false;
    402407        }
    403 
    404408        // Use recursive remove, now that key is known
    405         psMetadataRemove( md, PS_LIST_UNKNOWN, key );
     409        psMetadataRemove(md, PS_LIST_UNKNOWN, key);
    406410    }
    407411
     
    409413}
    410414
    411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key )
    412 {
    413     psHash * mdTable = NULL;
     415psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key)
     416{
     417    psHash *mdTable = NULL;
    414418    psMetadataItem *entry = NULL;
    415419
    416420    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);
    430434        return NULL;
    431435    }
     
    434438}
    435439
    436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where )
    437 {
    438     psList * mdList = NULL;
     440psMetadataItem *psMetadataGet(psMetadata * restrict md, int where)
     441{
     442    psList *mdList = NULL;
    439443    psMetadataItem *entry = NULL;
    440444
    441445    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);
    450454        return NULL;
    451455    }
     
    454458}
    455459
    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 );
     460bool 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);
    467471
    468472    return true;
    469473}
    470474
    471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which )
    472 {
    473     psList * mdList = NULL;
     475psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which)
     476{
     477    psList *mdList = NULL;
    474478    psMetadataItem *entry = NULL;
    475479
    476480    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))) {
    492496
    493497            // Match found
    494498            return entry;
    495499        }
    496         entry = psListGetNext( mdList );
     500        entry = psListGetNext(mdList);
    497501    }
    498502
    499503    // 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);
    502506    }
    503507
     
    505509}
    506510
    507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which )
    508 {
    509     psList * mdList = NULL;
     511psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which)
     512{
     513    psList *mdList = NULL;
    510514    psMetadataItem *entry = NULL;
    511515
    512516    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))) {
    528532
    529533            // Match found
    530534            return entry;
    531535        }
    532         entry = psListGetPrevious( mdList );
     536        entry = psListGetPrevious(mdList);
    533537    }
    534538
    535539    // 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);
    538542    }
    539543
     
    541545}
    542546
    543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem )
     547void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem)
    544548{
    545549    psMetadataType type;
    546550
    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;
    560564    }
    561565
    562566    type = metadataItem->type;
    563567
    564     switch(type) {
     568    switch (type) {
    565569    case PS_META_BOOL:
    566         fprintf( fd, format, metadataItem->data.B );
     570        fprintf(fd, format, metadataItem->data.B);
    567571        break;
    568572    case PS_META_S32:
    569         fprintf( fd, format, metadataItem->data.S32 );
     573        fprintf(fd, format, metadataItem->data.S32);
    570574        break;
    571575    case PS_META_F32:
    572         fprintf( fd, format, metadataItem->data.F32 );
     576        fprintf(fd, format, metadataItem->data.F32);
    573577        break;
    574578    case PS_META_F64:
    575         fprintf( fd, format, metadataItem->data.F64 );
     579        fprintf(fd, format, metadataItem->data.F64);
    576580        break;
    577581    case PS_META_STR:
    578         fprintf( fd, format, metadataItem->data.V );
     582        fprintf(fd, format, metadataItem->data.V);
    579583        break;
    580584    case PS_META_ITEM_SET:
     
    585589    case PS_META_UNKNOWN:
    586590    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
     595psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd)
    592596{
    593597    bool tempBool;
    594598    bool success;
    595599    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];
    600604    int i;
    601605    int hduType = 0;
     
    605609    psMetadataType metadataItemType;
    606610
    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    }
    621623    // Allocate metadata if user didn't
    622     if(output == NULL) {
     624    if (output == NULL) {
    623625        output = psMetadataAlloc();
    624626    }
    625 
    626627    // 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) {
    629630            FITS_ERROR("FITS error while locating header %s: %s", extName);
    630631        }
    631632    } else {
    632         if(fits_movabs_hdu( fd, extNum, &hduType, &status ) != 0) {
     633        if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) {
    633634            FITS_ERROR("FITS error while locating header %d: %s", extNum);
    634635        }
     
    636637
    637638    // 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) {
    639640        FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    640641    }
    641 
    642642    // 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) {
    645645            FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    646646        }
    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) {
    650650                FITS_ERROR("FITS error while determining key %d type: %s", keyNum);
    651651            } 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
    653654                keyType = 'C';
    654655                status = 0;
     
    656657        }
    657658
    658         switch(keyType) {
     659        switch (keyType) {
    659660        case 'I':
    660661            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));
    662665            break;
    663666        case 'F':
    664667            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));
    666671            break;
    667672        case 'C':
    668673            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);
    670676            break;
    671677        case 'L':
    672678            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);
    675682            break;
    676683        case 'U':
    677684        case 'X':
    678685        default:
    679             psError( __func__, "Invalid psMetadataType: %c", keyType );
     686            psError(__func__, "Invalid psMetadataType: %c", keyType);
    680687            return output;
    681688        }
    682689
    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);
    685692            return output;
    686693        }
  • trunk/psLib/src/collections/psMetadata.h

    r1394 r1407  
     1
    12/** @file  psMetadata.h
    23*
     
    1011*  @author Ross Harman, MHPCC
    1112*
    12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-05 20:55:22 $
     13*  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617*/
    1718#ifndef PS_METADATA_H
    18 #define PS_METADATA_H
    19 
    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"
    2627
    2728/// @addtogroup Metadata
     
    3334 */
    3435typedef enum {
    35     PS_META_ITEM_SET = 0,                   ///< Null. Metadata is in psMetadataItem.items
    36     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.
    4748} psMetadataType;
    4849
     
    5455typedef struct psMetadataItem
    5556{
    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 {
    6161        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.
    6969}
    7070psMetadataItem;
     
    7878typedef struct psMetadata
    7979{
    80     psList* restrict list;
    81     psHash* restrict table;
     80    psList *restrict list;
     81    psHash *restrict table;
    8282}
    8383psMetadata;
    8484
    85 
    8685/*****************************************************************************/
     86
    8787/* FUNCTION PROTOTYPES                                                       */
     88
    8889/*****************************************************************************/
    8990
     
    101102 * @return psMetadataItem*: Pointer metadata item.
    102103 */
    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 );
     104psMetadataItem *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                                   );
    109109
    110110/** Create a metadata item with va_list.
     
    121121 * @return psMetadataItem*: Pointer metadata item.
    122122 */
    123 psMetadataItem *psMetadataItemAllocV(
    124     const char *name,                       ///< Name of metadata item.
    125     psMetadataType type,                    ///< Type of metadata item.
    126     const char *comment,                    ///< Comment for metadata item.
    127     va_list list                        ///< Arguments for name formatting and metadata item data.
    128 );
     123psMetadataItem *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                                    );
    129129
    130130/** Create a metadata collection.
     
    134134 * @return psMetadata*: Pointer metadata.
    135135 */
    136 psMetadata *psMetadataAlloc(
    137     void                                ///< Void.
    138 );
     136psMetadata *psMetadataAlloc(void        // /< Void.
     137                           );
    139138
    140139/** Add existing metadata item to metadata collection.
     
    144143 * @return bool: True for success, false for failure.
    145144 */
    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 );
     145bool 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                      );
    151149
    152150/** Create and add a metadata item to metadata collection.
     
    156154 * @return bool: True for success, false for failure.
    157155 */
    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 );
     156bool 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                  );
    166163
    167164/** Remove an item from metadata collection.
     
    174171 * @return bool: True for success, false for failure.
    175172 */
    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 );
     173bool 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                     );
    181177
    182178/** Find an item in the metadata collection based on key name.
     
    187183 * @return psMetadataItem*: Pointer metadata item.
    188184 */
    189 psMetadataItem *psMetadataLookup(
    190     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    191     const char *restrict key            ///< Name of metadata key.
    192 );
     185psMetadataItem *psMetadataLookup(psMetadata * restrict md,      // /< Metadata collection to insert metadat
     186                                 // item.
     187                                 const char *restrict key       // /< Name of metadata key.
     188                                );
    193189
    194190/** Find an item in the metadata collection based on list index.
     
    198194 * @return psMetadataItem*: Pointer metadata item.
    199195 */
    200 psMetadataItem *psMetadataGet(
    201     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    202     int where                           ///< Location to be retrieved.
    203 );
     196psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item.
     197                              int where // /< Location to be retrieved.
     198                             );
    204199
    205200/** Set or reset metadata iterator.
     
    209204 * @return void: void.
    210205 */
    211 bool psMetadataSetIterator(
    212     psMetadata *restrict md,                ///< Metadata collection to iterate.
    213     int where                           ///< Location of iterator.
    214 );
     206bool psMetadataSetIterator(psMetadata * restrict md,    // /< Metadata collection to iterate.
     207                           int where    // /< Location of iterator.
     208                          );
    215209
    216210/** Get next metadata item.
     
    220214 * @return psMetadataItem*: Pointer metadata item.
    221215 */
    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 );
     216psMetadataItem *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                                 );
    227220
    228221/** Get previous metadata item.
     
    232225 * @return psMetadataItem*: Pointer metadata item.
    233226 */
    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 );
     227psMetadataItem *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                                     );
    239231
    240232/** Print metadata item to file.
     
    248240 * @return psMetadataItem*: Pointer metadata item.
    249241 */
    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 );
     242void 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                        );
    255246
    256247/** Read metadata header.
     
    261252 * @return psMetadata*: Pointer metadata.
    262253 */
    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 );
     254psMetadata *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                                );
    269259
    270260/** Read metadata header.
     
    274264 * @return psMetadata*: Pointer metadata.
    275265 */
    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 );
     266psMetadata *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
    282272/// @}
    283273
  • trunk/psLib/src/collections/psScalar.c

    r1406 r1407  
     1
    12/** @file  psScalar.c
    23 *
     
    89 *  @author Ross Harman, MHPCC
    910 *
    10  *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    1922#include "psMemory.h"
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873psScalar *psScalarAlloc(psC64 value, psElemType dataType)
     
    6176
    6277    // 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__);
    6681    }
    6782
     
    7186    switch (dataType) {
    7287    case PS_TYPE_S8:
    73         scalar->data.S8 = (psS8)value;
     88        scalar->data.S8 = (psS8) value;
    7489        break;
    7590    case PS_TYPE_U8:
    76         scalar->data.U8 = (psU8)value;
     91        scalar->data.U8 = (psU8) value;
    7792        break;
    7893    case PS_TYPE_S16:
    79         scalar->data.S16 = (psS16)value;
     94        scalar->data.S16 = (psS16) value;
    8095        break;
    8196    case PS_TYPE_U16:
    82         scalar->data.U16 = (psU16)value;
     97        scalar->data.U16 = (psU16) value;
    8398        break;
    8499    case PS_TYPE_S32:
    85         scalar->data.S32 = (psS32)value;
     100        scalar->data.S32 = (psS32) value;
    86101        break;
    87102    case PS_TYPE_U32:
    88         scalar->data.U32 = (psU32)value;
     103        scalar->data.U32 = (psU32) value;
    89104        break;
    90105    case PS_TYPE_S64:
    91         scalar->data.S64 = (psS64)value;
     106        scalar->data.S64 = (psS64) value;
    92107        break;
    93108    case PS_TYPE_U64:
    94         scalar->data.U64 = (psU64)value;
     109        scalar->data.U64 = (psU64) value;
    95110        break;
    96111    case PS_TYPE_F32:
    97         scalar->data.F32 = (psF32)value;
     112        scalar->data.F32 = (psF32) value;
    98113        break;
    99114    case PS_TYPE_F64:
    100         scalar->data.F64 = (psF64)value;
     115        scalar->data.F64 = (psF64) value;
    101116        break;
    102117    case PS_TYPE_C32:
    103         scalar->data.C32 = (psC32)value;
     118        scalar->data.C32 = (psC32) value;
    104119        break;
    105120    case PS_TYPE_C64:
    106         scalar->data.C64 = (psC64)value;
     121        scalar->data.C64 = (psC64) value;
    107122        break;
    108123    default:
     
    110125    }
    111126
    112 
    113127    return scalar;
    114128}
    115129
    116 void psScalarFree(psScalar *restrict scalar)
     130void psScalarFree(psScalar * restrict scalar)
    117131{
    118132    if (scalar == NULL) {
     
    122136    psFree(scalar);
    123137}
    124 
    125 
  • trunk/psLib/src/collections/psScalar.h

    r1406 r1407  
     1
    12/** @file  psScalar.h
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_SCALAR_H
    19 #define PS_SCALAR_H
     20#    define PS_SCALAR_H
    2021
    21 #include "psType.h"
     22#    include "psType.h"
    2223
    2324/// @addtogroup Scalar
     
    3132typedef struct
    3233{
    33     psType type;                       ///< Type of data.
     34    psType type;                // /< Type of data.
    3435
    3536    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.
    4950}
    5051psScalar;
    5152
    5253/*****************************************************************************/
     54
    5355/* FUNCTION PROTOTYPES                                                       */
     56
    5457/*****************************************************************************/
    5558
     
    6265 *
    6366 */
    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 
     67psScalar *psScalarAlloc(psC64 value,    // /< Data to be put into psScalar.
     68                        psElemType dataType     // /< Type of data to be held by psScalar.
     69                       );
    6970
    7071/** Deallocate a scalar.
     
    7576 *
    7677 */
    77 void psScalarFree(
    78     psScalar *restrict scalar  ///< Scalar to free.
    79 );
     78void psScalarFree(psScalar * restrict scalar    // /< Scalar to free.
     79                 );
    8080
    8181/// @}
  • trunk/psLib/src/collections/psVector.c

    r1406 r1407  
     1
    12/** @file  psVector.c
    23*
     
    89*  @author Ross Harman, MHPCC
    910*
    10 *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
    18 /******************************************************************************/
    19 #include <string.h>        // for memcpy
     20
     21/******************************************************************************/
     22#include <string.h>                        // for memcpy
    2023#include <stdlib.h>
    2124#include <math.h>
     
    2831
    2932/******************************************************************************/
     33
    3034/*  DEFINE STATEMENTS                                                         */
     35
    3136/******************************************************************************/
    3237
     
    3439
    3540/******************************************************************************/
     41
    3642/*  TYPE DEFINITIONS                                                          */
     43
    3744/******************************************************************************/
    3845
     
    4047
    4148/*****************************************************************************/
     49
    4250/*  GLOBAL VARIABLES                                                         */
     51
    4352/*****************************************************************************/
    4453
     
    4655
    4756/*****************************************************************************/
     57
    4858/*  FILE STATIC VARIABLES                                                    */
     59
    4960/*****************************************************************************/
    5061
     
    5263
    5364/*****************************************************************************/
     65
    5466/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    55 /*****************************************************************************/
    56 static void vectorFree( psVector *restrict psVec );
    57 
    58 /*****************************************************************************/
     67
     68/*****************************************************************************/
     69static void vectorFree(psVector * restrict psVec);
     70
     71/*****************************************************************************/
     72
    5973/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    60 /*****************************************************************************/
    61 psVector* psVectorAlloc( unsigned int nalloc, psElemType elemType )
    62 {
    63     psVector * psVec = NULL;
     74
     75/*****************************************************************************/
     76psVector *psVectorAlloc(unsigned int nalloc, psElemType elemType)
     77{
     78    psVector *psVec = NULL;
    6479    int elementSize = 0;
    6580
    6681    // 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);
    6984        return NULL;
    7085    }
    7186
    72     elementSize = PSELEMTYPE_SIZEOF( elemType );
     87    elementSize = PSELEMTYPE_SIZEOF(elemType);
    7388
    7489    // 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);
    7792
    7893    psVec->type.dimen = PS_DIMEN_VECTOR;
     
    8297
    8398    // Create vector data array
    84     psVec->data.V = psAlloc( nalloc * elementSize );
     99    psVec->data.V = psAlloc(nalloc * elementSize);
    85100
    86101    return psVec;
    87102}
    88103
    89 psVector *psVectorRealloc( unsigned int nalloc, psVector *restrict in )
     104psVector *psVectorRealloc(unsigned int nalloc, psVector * restrict in)
    90105{
    91106    int elementSize = 0;
     
    93108
    94109    // 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);
    97112        return NULL;
    98113    }
    99114
    100     if ( in == NULL ) {
    101         psError( __func__, "Null input vector\n" );
     115    if (in == NULL) {
     116        psError(__func__, "Null input vector\n");
    102117        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;
    114123        }
     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    }
    115128
    116129    return in;
    117130}
    118131
    119 psVector *psVectorRecycle( psVector *restrict in, unsigned int nalloc, psElemType type )
     132psVector *psVectorRecycle(psVector * restrict in, unsigned int nalloc, psElemType type)
    120133{
    121134    psElemType elemType;
    122135
    123     if ( in == NULL ) {
    124         return psVectorAlloc( nalloc, type );
     136    if (in == NULL) {
     137        return psVectorAlloc(nalloc, type);
    125138    }
    126139
    127140    elemType = in->type.type;
    128141
    129     if ( in->nalloc == nalloc && elemType == type ) {
     142    if (in->nalloc == nalloc && elemType == type) {
    130143        // it is proper size/type already
    131144        return in;
    132145    }
    133 
    134146    // 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);
    138150        return NULL;
    139151    }
    140152
    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));
    143154
    144155    in->type.type = type;
     
    149160}
    150161
    151 psVector *psVectorSort( psVector *restrict outVector, const psVector *restrict inVector )
     162psVector *psVectorSort(psVector * restrict outVector, const psVector * restrict inVector)
    152163{
    153164    int inN = 0;
     
    158169    psElemType inType = 0;
    159170
    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__);
    162173        return outVector;
    163174    }
     
    166177    inN = inVector->n;
    167178    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);
    172183        outVector->n = inVector->n;
    173184    }
     
    176187    outVec = outVector->data.V;
    177188
    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    }
    200210    // Copy input vector values into output vector
    201     memcpy( outVec, inVec, elSize * outN );
     211    memcpy(outVec, inVec, elSize * outN);
    202212
    203213    // Sort output vector
    204     switch ( inType ) {
     214    switch (inType) {
    205215    case PS_TYPE_U8:
    206         qsort( outVec, inN, elSize, psCompareU8 );
     216        qsort(outVec, inN, elSize, psCompareU8);
    207217        break;
    208218    case PS_TYPE_U16:
    209         qsort( outVec, inN, elSize, psCompareU16 );
     219        qsort(outVec, inN, elSize, psCompareU16);
    210220        break;
    211221    case PS_TYPE_U32:
    212         qsort( outVec, inN, elSize, psCompareU32 );
     222        qsort(outVec, inN, elSize, psCompareU32);
    213223        break;
    214224    case PS_TYPE_U64:
    215         qsort( outVec, inN, elSize, psCompareU64 );
     225        qsort(outVec, inN, elSize, psCompareU64);
    216226        break;
    217227    case PS_TYPE_S8:
    218         qsort( outVec, inN, elSize, psCompareS8 );
     228        qsort(outVec, inN, elSize, psCompareS8);
    219229        break;
    220230    case PS_TYPE_S16:
    221         qsort( outVec, inN, elSize, psCompareS16 );
     231        qsort(outVec, inN, elSize, psCompareS16);
    222232        break;
    223233    case PS_TYPE_S32:
    224         qsort( outVec, inN, elSize, psCompareS32 );
     234        qsort(outVec, inN, elSize, psCompareS32);
    225235        break;
    226236    case PS_TYPE_S64:
    227         qsort( outVec, inN, elSize, psCompareS64 );
     237        qsort(outVec, inN, elSize, psCompareS64);
    228238        break;
    229239    case PS_TYPE_F32:
    230         qsort( outVec, inN, elSize, psCompareF32 );
     240        qsort(outVec, inN, elSize, psCompareF32);
    231241        break;
    232242    case PS_TYPE_F64:
    233         qsort( outVec, inN, elSize, psCompareF64 );
     243        qsort(outVec, inN, elSize, psCompareF64);
    234244        break;
    235245    default:
    236         psError( __func__, " : Line %d - Invalid psType\n", __LINE__ );
     246        psError(__func__, " : Line %d - Invalid psType\n", __LINE__);
    237247    }
    238248
     
    251261}
    252262
    253 psVector *psVectorSortIndex( psVector *restrict outVector, const psVector *restrict inVector )
     263psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector)
    254264{
    255265    int inN = 0;
     
    263273    psElemType inType = 0;
    264274
    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__);
    267277        return outVector;
    268278    }
     
    272282    inType = inVector->type.type;
    273283
    274     if ( outVector == NULL ) {
    275         outVector = psVectorAlloc( inN, PS_TYPE_U32 );
     284    if (outVector == NULL) {
     285        outVector = psVectorAlloc(inN, PS_TYPE_U32);
    276286        outVector->n = inN;
    277287    }
     
    280290    outVec = outVector->data.V;
    281291
    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);
    295305    tmpVector->n = inN;
    296     tmpVector = psVectorSort( tmpVector, inVector );
     306    tmpVector = psVectorSort(tmpVector, inVector);
    297307
    298308    // Sort output vector
    299     switch ( inType ) {
     309    switch (inType) {
    300310    case PS_TYPE_U8:
    301         SORT_INDICES( U8 );
     311        SORT_INDICES(U8);
    302312        break;
    303313    case PS_TYPE_U16:
    304         SORT_INDICES( U16 );
     314        SORT_INDICES(U16);
    305315        break;
    306316    case PS_TYPE_U32:
    307         SORT_INDICES( U32 );
     317        SORT_INDICES(U32);
    308318        break;
    309319    case PS_TYPE_U64:
    310         SORT_INDICES( U64 );
     320        SORT_INDICES(U64);
    311321        break;
    312322    case PS_TYPE_S8:
    313         SORT_INDICES( S8 );
     323        SORT_INDICES(S8);
    314324        break;
    315325    case PS_TYPE_S16:
    316         SORT_INDICES( S16 );
     326        SORT_INDICES(S16);
    317327        break;
    318328    case PS_TYPE_S32:
    319         SORT_INDICES( S32 );
     329        SORT_INDICES(S32);
    320330        break;
    321331    case PS_TYPE_S64:
    322         SORT_INDICES( S64 );
     332        SORT_INDICES(S64);
    323333        break;
    324334    case PS_TYPE_F32:
    325         SORT_INDICES( F32 );
     335        SORT_INDICES(F32);
    326336        break;
    327337    case PS_TYPE_F64:
    328         SORT_INDICES( F64 );
     338        SORT_INDICES(F64);
    329339        break;
    330340    default:
    331         psError( __func__, " : Line %d - Invalid psType\n", __LINE__ );
     341        psError(__func__, " : Line %d - Invalid psType\n", __LINE__);
    332342    }
    333343
    334344    // Free temp memory
    335     psFree( tmpVector );
     345    psFree(tmpVector);
    336346
    337347    return outVector;
    338348}
    339349
    340 static void vectorFree( psVector *restrict psVec )
    341 {
    342     if ( psVec == NULL ) {
    343         return ;
    344     }
    345 
    346     psFree( psVec->data.V );
    347 }
     350static 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
    12/** @file  psVector.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_VECTOR_H
    20 #define PS_VECTOR_H
     21#    define PS_VECTOR_H
    2122
    22 #include "psType.h"
     23#    include "psType.h"
    2324
    2425/// @addtogroup Vector
     
    3233typedef struct
    3334{
    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.
    3738
    3839    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.
    5354}
    5455psVector;
    5556
    5657/*****************************************************************************/
     58
    5759/* FUNCTION PROTOTYPES                                                       */
     60
    5861/*****************************************************************************/
    5962
     
    6568 *
    6669 */
    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 );
     70psVector *psVectorAlloc(unsigned int nalloc,    // /< Total number of elements to make available.
     71                        psElemType dataType     // /< Type of data to be held by vector.
     72                       );
    7173
    7274/** Reallocate a vector.
     
    7880 *
    7981 */
    80 psVector *psVectorRealloc(
    81     unsigned int nalloc,                ///< Total number of elements to make available.
    82     psVector *restrict psVec            ///< Vector to reallocate.
    83 );
     82psVector *psVectorRealloc(unsigned int nalloc,  // /< Total number of elements to make available.
     83                          psVector * restrict psVec     // /< Vector to reallocate.
     84                         );
    8485
    8586/** Recycle a vector.
     
    9192 *
    9293 */
    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 );
     94psVector *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                         );
    100100
    101101/** Sort an array of floats.
     
    107107 */
    108108
    109 psVector *psVectorSort(
    110     psVector *restrict outVector,  ///< the output vector to recycle, or NULL if new vector desired.
    111     const psVector *restrict inVector ///< the vector to sort.
    112 );
     109psVector *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                      );
    113113
    114114/** Creates an array of indices based on sort odred of float array.
     
    120120 */
    121121
    122 psVector *psVectorSortIndex(
    123     psVector *restrict outVector,
    124     const psVector *restrict inVector
    125 );
    126 
     122psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector);
    127123
    128124/// @}
  • trunk/psLib/src/dataManip/psFFT.c

    r1406 r1407  
     1
    12/** @file  psFFT.c
    23*
     
    56*  @author Robert DeSonia, MHPCC
    67*
    7 *  @version $Revision: 1.18 $ $Name: not supported by cvs2svn $
    8 *  @date $Date: 2004-08-06 22:34:05 $
     8*  @version $Revision: 1.19 $ $Name: not supported by cvs2svn $
     9*  @date $Date: 2004-08-07 00:06:06 $
    910*
    1011*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728static bool p_fftwWisdomImported = false;
    2829
    29 psImage* psImageFFT( psImage* out, const psImage* in, psFftDirection direction )
     30psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction)
    3031{
    3132    unsigned int numCols;
     
    3536
    3637    /* 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);
    6361        return NULL;
    6462    }
    6563
    6664    /* make sure the system-level wisdom information is imported. */
    67     if ( ! p_fftwWisdomImported ) {
     65    if (!p_fftwWisdomImported) {
    6866        fftwf_import_system_wisdom();
    6967        p_fftwWisdomImported = true;
     
    7371    numCols = in->numCols;
    7472
    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);
    8783        return NULL;
    8884    }
    8985
    9086    /* 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
     95psImage *psImageReal(psImage * out, const psImage * in)
    10196{
    10297    psElemType type;
     
    10499    unsigned int numRows;
    105100
    106 
    107     if ( in == NULL ) {
    108         psFree( out );
     101    if (in == NULL) {
     102        psFree(out);
    109103        return NULL;
    110104    }
     
    115109
    116110    /* 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)) {
    118112        // 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
     153psImage *psImageImaginary(psImage * out, const psImage * in)
    162154{
    163155    psElemType type;
     
    165157    unsigned int numRows;
    166158
    167 
    168     if ( in == NULL ) {
    169         psFree( out );
     159    if (in == NULL) {
     160        psFree(out);
    170161        return NULL;
    171162    }
     
    176167
    177168    /* 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)) {
    179170        // 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);
    184175        return out;
    185176    }
    186177
    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
     213psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag)
    225214{
    226215    psElemType type;
     
    228217    unsigned int numRows;
    229218
    230 
    231     if ( real == NULL || imag == NULL ) {
    232         psFree( out );
     219    if (real == NULL || imag == NULL) {
     220        psFree(out);
    233221        return NULL;
    234222    }
     
    238226    numRows = real->numRows;
    239227
    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
     292psImage *psImageConjugate(psImage * out, const psImage * in)
    308293{
    309294    psElemType type;
     
    311296    unsigned int numRows;
    312297
    313 
    314     if ( in == NULL ) {
    315         psFree( out );
     298    if (in == NULL) {
     299        psFree(out);
    316300        return NULL;
    317301    }
     
    322306
    323307    /* 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)) {
    325309        // 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
     350psImage *psImagePowerSpectrum(psImage * out, const psImage * in)
    369351{
    370352    psElemType type;
     
    373355    int numElementsSquared;
    374356
    375     if ( in == NULL ) {
    376         psFree( out );
     357    if (in == NULL) {
     358        psFree(out);
    377359        return NULL;
    378360    }
     
    384366
    385367    /* 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;
    395377        psF32 real;
    396378        psF32 imag;
    397379
    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    }
    435413
    436414    return out;
     
    440418/************************************** Vector Functions ***************************************/
    441419
    442 psVector* psVectorFFT( psVector* out, const psVector* in, psFftDirection direction )
     420psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction)
    443421{
    444422    unsigned int numElements;
     
    447425
    448426    /* 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);
    475450        return NULL;
    476451    }
    477452
    478453    /* make sure the system-level wisdom information is imported. */
    479     if ( ! p_fftwWisdomImported ) {
     454    if (!p_fftwWisdomImported) {
    480455        fftwf_import_system_wisdom();
    481456        p_fftwWisdomImported = true;
     
    484459    numElements = in->n;
    485460
    486     out = psVectorRecycle( out, numElements, PS_TYPE_C32 );
     461    out = psVectorRecycle(out, numElements, PS_TYPE_C32);
    487462    out->n = numElements;
    488463
    489     if ( type == PS_TYPE_F32 ) {
     464    if (type == PS_TYPE_F32) {
    490465        // 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);
    514489        return NULL;
    515490    }
    516491
    517492    /* 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
     500psVector *psVectorReal(psVector * out, const psVector * in)
    527501{
    528502    psElemType type;
    529503    unsigned int numElements;
    530504
    531     if ( in == NULL ) {
    532         psFree( out );
     505    if (in == NULL) {
     506        psFree(out);
    533507        return NULL;
    534508    }
     
    538512
    539513    /* 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)) {
    541515        // 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);
    545519        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));
    547521        return out;
    548522    }
    549523
    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);
    555529        out->n = numElements;
    556530        outVec = out->data.F32;
    557531
    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
     544psVector *psVectorImaginary(psVector * out, const psVector * in)
    572545{
    573546    psElemType type;
    574547    unsigned int numElements;
    575548
    576 
    577     if ( in == NULL ) {
    578         psFree( out );
     549    if (in == NULL) {
     550        psFree(out);
    579551        return NULL;
    580552    }
     
    584556
    585557    /* 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)) {
    587559        // 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);
    591563        out->n = numElements;
    592         memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements );
     564        memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements);
    593565        return out;
    594566    }
    595567
    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);
    601573        out->n = numElements;
    602574        outVec = out->data.F32;
    603575
    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
     588psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag)
    618589{
    619590    psElemType type;
    620591    unsigned int numElements;
    621592
    622 
    623     if ( real == NULL || imag == NULL ) {
    624         psFree( out );
     593    if (real == NULL || imag == NULL) {
     594        psFree(out);
    625595        return NULL;
    626596    }
    627597
    628598    type = real->type.type;
    629     if ( real->n < imag->n ) {
     599    if (real->n < imag->n) {
    630600        numElements = real->n;
    631601    } else {
     
    633603    }
    634604
    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);
    653623        out->n = numElements;
    654624        outVec = out->data.C32;
    655625
    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
     638psVector *psVectorConjugate(psVector * out, const psVector * in)
    670639{
    671640    psElemType type;
    672641    unsigned int numElements;
    673642
    674 
    675     if ( in == NULL ) {
    676         psFree( out );
     643    if (in == NULL) {
     644        psFree(out);
    677645        return NULL;
    678646    }
     
    682650
    683651    /* 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)) {
    685653        // 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);
    690658        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);
    692660        return out;
    693661    }
    694662
    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);
    700668        out->n = numElements;
    701669        outVec = out->data.C32;
    702670
    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
     683psVector *psVectorPowerSpectrum(psVector * out, const psVector * in)
    717684{
    718685    psElemType type;
     
    722689    unsigned int inNumElementsSquared;
    723690
    724     if ( in == NULL ) {
    725         psFree( out );
     691    if (in == NULL) {
     692        psFree(out);
    726693        return NULL;
    727694    }
     
    734701
    735702    /* 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;
    745712        psF32 inAbs1;
    746713        psF32 inAbs2;
    747714
    748         out = psVectorRecycle( out, outNumElements, PS_TYPE_F32 );
     715        out = psVectorRecycle(out, outNumElements, PS_TYPE_F32);
    749716        out->n = outNumElements;
    750717        outVec = out->data.F32;
    751718
    752719        // 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;
    755722
    756723        // 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;
    761728        }
    762729
    763730        // 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
    12/** @file  psFFT.h
    23 *
     
    78 *  @author Robert DeSonia, MHPCC
    89 *
    9  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1415
    1516#ifndef PS_FFT_H
    16 #define PS_FFT_H
     17#    define PS_FFT_H
    1718
    18 #include "psImage.h"
    19 #include "psVector.h"
     19#    include "psImage.h"
     20#    include "psVector.h"
    2021
    2122/// @addtogroup Transform
     
    2425/** Details on FFT implementation (private). */
    2526
    26 
    2727typedef enum {
    28     /// psImageFFT/psVectorFFT should perform a forward FFT.
     28    // / psImageFFT/psVectorFFT should perform a forward FFT.
    2929    PS_FFT_FORWARD = (-1),
    3030
    31     ///< psImageFFT/psVectorFFT should perform a reverse FFT.
     31    // /< psImageFFT/psVectorFFT should perform a reverse FFT.
    3232    PS_FFT_REVERSE = (+1)
    3333} psFftDirection;
    3434
    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);
     35psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction);
     36psImage *psImageReal(psImage * out, const psImage * in);
     37psImage *psImageImaginary(psImage * out, const psImage * in);
     38psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag);
     39psImage *psImageConjugate(psImage * out, const psImage * in);
     40psImage *psImagePowerSpectrum(psImage * out, const psImage * in);
    4141
    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);
     42psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction);
     43psVector *psVectorReal(psVector * out, const psVector * in);
     44psVector *psVectorImaginary(psVector * out, const psVector * in);
     45psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag);
     46psVector *psVectorConjugate(psVector * out, const psVector * in);
     47psVector *psVectorPowerSpectrum(psVector * out, const psVector * in);
    4848
    4949/// @}
    5050
    5151#endif
    52 
  • trunk/psLib/src/dataManip/psFunctions.c

    r1406 r1407  
     1
    12/** @file  psFunctions.c
    23 *
     
    78 *  polynomials.  It also contains a Gaussian functions.
    89 *
    9  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1314 */
    14 /*****************************************************************************/
     15
     16/*****************************************************************************/
     17
    1518/*  INCLUDE FILES                                                            */
     19
    1620/*****************************************************************************/
    1721#include <stdlib.h>
     
    3135#include <gsl/gsl_rng.h>
    3236#include <gsl/gsl_randist.h>
    33 /*****************************************************************************/
     37
     38/*****************************************************************************/
     39
    3440/* DEFINE STATEMENTS                                                         */
     41
    3542/*****************************************************************************/
    3643
     
    3845
    3946/*****************************************************************************/
     47
    4048/* 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/*****************************************************************************/
     51static void polynomial1DFree(psPolynomial1D * myPoly);
     52static void polynomial2DFree(psPolynomial2D * myPoly);
     53static void polynomial3DFree(psPolynomial3D * myPoly);
     54static void polynomial4DFree(psPolynomial4D * myPoly);
     55static void dPolynomial1DFree(psDPolynomial1D * myPoly);
     56static void dPolynomial2DFree(psDPolynomial2D * myPoly);
     57static void dPolynomial3DFree(psDPolynomial3D * myPoly);
     58static void dPolynomial4DFree(psDPolynomial4D * myPoly);
     59
     60/*****************************************************************************/
     61
    5262/* GLOBAL VARIABLES                                                          */
     63
    5364/*****************************************************************************/
    5465
     
    5667
    5768/*****************************************************************************/
     69
    5870/* FILE STATIC VARIABLES                                                     */
     71
    5972/*****************************************************************************/
    6073
     
    6275
    6376/*****************************************************************************/
     77
    6478/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     79
    6580/*****************************************************************************/
    6681
     
    6883
    6984/*****************************************************************************/
     85
    7086/*  FUNCTION IMPLEMENTATION - PUBLIC                                         */
     87
    7188/*****************************************************************************/
    7289
     
    7693    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f]
    7794 *****************************************************************************/
    78 float
    79 psGaussian(float x,
    80            float mean,
    81            float sigma,
    82            bool  normal)
     95float psGaussian(float x, float mean, float sigma, bool normal)
    8396{
    8497    float tmp = 1.0;
     
    94107    }
    95108
    96     return(tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));
     109    return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma)));
    97110}
    98111
     
    107120 NOTE: There is no way to seed the random generator.
    108121 *****************************************************************************/
    109 psVector *psGaussianDev(float mean,
    110                         float sigma,
    111                         int Npts)
     122psVector *psGaussianDev(float mean, float sigma, int Npts)
    112123{
    113124    psVector *gauss = NULL;
     
    127138
    128139    // NOTE: Should I free r as well?
    129     return(gauss);
    130 }
    131 
     140    return (gauss);
     141}
    132142
    133143/*****************************************************************************
     
    140150
    141151    newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D));
    142     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial1DFree);
     152    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree);
    143153    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++) {
    148158        newPoly->coeff[i] = 0.0;
    149159        newPoly->coeffErr[i] = 0.0;
     
    151161    }
    152162
    153     return(newPoly);
     163    return (newPoly);
    154164}
    155165
     
    161171
    162172    newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D));
    163     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial2DFree);
     173    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree);
    164174    newPoly->nX = nX;
    165175    newPoly->nY = nY;
    166176
    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++) {
    177187            newPoly->coeff[x][y] = 0.0;
    178188            newPoly->coeffErr[x][y] = 0.0;
     
    181191    }
    182192
    183     return(newPoly);
     193    return (newPoly);
    184194}
    185195
     
    192202
    193203    newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D));
    194     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial3DFree);
     204    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree);
    195205    newPoly->nX = nX;
    196206    newPoly->nY = nY;
    197207    newPoly->nZ = nZ;
    198208
    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++) {
    215225                newPoly->coeff[x][y][z] = 0.0;
    216226                newPoly->coeffErr[x][y][z] = 0.0;
     
    220230    }
    221231
    222     return(newPoly);
     232    return (newPoly);
    223233}
    224234
     
    232242
    233243    newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D));
    234     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial4DFree);
     244    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree);
    235245    newPoly->nW = nW;
    236246    newPoly->nX = nX;
     
    238248    newPoly->nZ = nZ;
    239249
    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++) {
    262272                    newPoly->coeff[w][x][y][z] = 0.0;
    263273                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    268278    }
    269279
    270     return(newPoly);
    271 }
    272 
    273 static void polynomial1DFree(psPolynomial1D *myPoly)
     280    return (newPoly);
     281}
     282
     283static void polynomial1DFree(psPolynomial1D * myPoly)
    274284{
    275285    psFree(myPoly->coeff);
     
    278288}
    279289
    280 static void polynomial2DFree(psPolynomial2D *myPoly)
    281 {
    282     int x = 0;
    283 
    284     for (x=0;x<myPoly->nX;x++) {
     290static void polynomial2DFree(psPolynomial2D * myPoly)
     291{
     292    int x = 0;
     293
     294    for (x = 0; x < myPoly->nX; x++) {
    285295        psFree(myPoly->coeff[x]);
    286296        psFree(myPoly->coeffErr[x]);
     
    292302}
    293303
    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++) {
     304static 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++) {
    301311            psFree(myPoly->coeff[x][y]);
    302312            psFree(myPoly->coeffErr[x][y]);
     
    313323}
    314324
    315 static void polynomial4DFree(psPolynomial4D *myPoly)
     325static void polynomial4DFree(psPolynomial4D * myPoly)
    316326{
    317327    int w = 0;
     
    319329    int y = 0;
    320330
    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++) {
    324334                psFree(myPoly->coeff[w][x][y]);
    325335                psFree(myPoly->coeffErr[w][x][y]);
     
    343353    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    344354 *****************************************************************************/
    345 float
    346 psPolynomial1DEval(float x,
    347                    const psPolynomial1D *myPoly)
     355float psPolynomial1DEval(float x, const psPolynomial1D * myPoly)
    348356{
    349357    int loop_x = 0;
     
    355363    }
    356364
    357 
    358365    // NOTE: Do we want to flag this case?
    359366    if (myPoly->n == 0) {
    360         return(1.0);
     367        return (1.0);
    361368    }
    362369
     
    365372    }
    366373
    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
     382float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly)
    380383{
    381384    int loop_x = 0;
     
    385388    float ySum = 1.0;
    386389
    387     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     390    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    388391        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
     402float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly)
    404403{
    405404    int loop_x = 0;
     
    411410    float zSum = 1.0;
    412411
    413     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     412    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    414413        ySum = xSum;
    415         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     414        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    416415            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
     428float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly)
    435429{
    436430    int loop_w = 0;
     
    444438    float zSum = 1.0;
    445439
    446     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     440    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    447441        xSum = wSum;
    448         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     442        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    449443            ySum = xSum;
    450             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     444            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    451445                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;
    456449                }
    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}
    469459
    470460psDPolynomial1D *psDPolynomial1DAlloc(int n)
     
    474464
    475465    newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D));
    476     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial1DFree);
     466    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree);
    477467    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++) {
    482472        newPoly->coeff[i] = 0.0;
    483473        newPoly->coeffErr[i] = 0.0;
     
    485475    }
    486476
    487     return(newPoly);
     477    return (newPoly);
    488478}
    489479
     
    495485
    496486    newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D));
    497     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial2DFree);
     487    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree);
    498488    newPoly->nX = nX;
    499489    newPoly->nY = nY;
    500490
    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++) {
    511501            newPoly->coeff[x][y] = 0.0;
    512502            newPoly->coeffErr[x][y] = 0.0;
     
    515505    }
    516506
    517     return(newPoly);
     507    return (newPoly);
    518508}
    519509
     
    526516
    527517    newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D));
    528     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial3DFree);
     518    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree);
    529519    newPoly->nX = nX;
    530520    newPoly->nY = nY;
    531521    newPoly->nZ = nZ;
    532522
    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++) {
    549539                newPoly->coeff[x][y][z] = 0.0;
    550540                newPoly->coeffErr[x][y][z] = 0.0;
     
    554544    }
    555545
    556     return(newPoly);
     546    return (newPoly);
    557547}
    558548
     
    566556
    567557    newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D));
    568     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial4DFree);
     558    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree);
    569559    newPoly->nW = nW;
    570560    newPoly->nX = nX;
     
    572562    newPoly->nZ = nZ;
    573563
    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++) {
    596586                    newPoly->coeff[w][x][y][z] = 0.0;
    597587                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    602592    }
    603593
    604     return(newPoly);
    605 }
    606 
    607 static void dPolynomial1DFree(psDPolynomial1D *myPoly)
     594    return (newPoly);
     595}
     596
     597static void dPolynomial1DFree(psDPolynomial1D * myPoly)
    608598{
    609599    psFree(myPoly->coeff);
     
    612602}
    613603
    614 static void dPolynomial2DFree(psDPolynomial2D *myPoly)
    615 {
    616     int x = 0;
    617 
    618     for (x=0;x<myPoly->nX;x++) {
     604static void dPolynomial2DFree(psDPolynomial2D * myPoly)
     605{
     606    int x = 0;
     607
     608    for (x = 0; x < myPoly->nX; x++) {
    619609        psFree(myPoly->coeff[x]);
    620610        psFree(myPoly->coeffErr[x]);
     
    626616}
    627617
    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++) {
     618static 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++) {
    635625            psFree(myPoly->coeff[x][y]);
    636626            psFree(myPoly->coeffErr[x][y]);
     
    647637}
    648638
    649 static void dPolynomial4DFree(psDPolynomial4D *myPoly)
     639static void dPolynomial4DFree(psDPolynomial4D * myPoly)
    650640{
    651641    int w = 0;
     
    653643    int y = 0;
    654644
    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++) {
    658648                psFree(myPoly->coeff[w][x][y]);
    659649                psFree(myPoly->coeffErr[w][x][y]);
     
    677667    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    678668 *****************************************************************************/
    679 double
    680 psDPolynomial1DEval(double x,
    681                     const psDPolynomial1D *myPoly)
     669double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly)
    682670{
    683671    int loop_x = 0;
     
    687675    // NOTE: Do we want to flag this case?
    688676    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
     688double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly)
    705689{
    706690    int loop_x = 0;
     
    710694    double ySum = 1.0;
    711695
    712     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     696    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    713697        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
     708double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly)
    729709{
    730710    int loop_x = 0;
     
    736716    double zSum = 1.0;
    737717
    738     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     718    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    739719        ySum = xSum;
    740         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     720        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    741721            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
     734double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly)
    760735{
    761736    int loop_w = 0;
     
    769744    double zSum = 1.0;
    770745
    771     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     746    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    772747        xSum = wSum;
    773         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     748        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    774749            ySum = xSum;
    775             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     750            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    776751                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;
    781755                }
    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
    12/** @file psFunctions.h
    23*  \brief Standard Mathematical Functions.
     
    1213*  @author George Gusciora, MHPCC
    1314*
    14 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    15 *  @date $Date: 2004-08-06 22:34:05 $
     15*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     16*  @date $Date: 2004-08-07 00:06:06 $
    1617*
    1718*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#if !defined(PS_FUNCTIONS_H)
    21 #define PS_FUNCTIONS_H
    22 
    23 #include <stdbool.h>
    24 
    25 #include "psVector.h"
     22#    define PS_FUNCTIONS_H
     23
     24#    include <stdbool.h>
     25
     26#    include "psVector.h"
    2627
    2728/** \addtogroup Stats
     
    3334    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */
    3435
    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 
     36float 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                );
    4241
    4342/** Produce a vector of random numbers from a Gaussian distribution with
    4443    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 
     44psVector *psGaussianDev(float mean,     // /< The mean of the Gaussian
     45                        float sigma,    // /< The sigma of the Gaussian
     46                        int Npts);      // /< The size of the vector
    5247
    5348/** One-dimensional polynomial */
    5449typedef struct
    5550{
    56     int n;           ///< Number of terms
    57     float *coeff;    ///< Coefficients
    58     float *coeffErr; ///< Error in coefficients
    59     char *mask;      ///< Coefficient mask
     51    int n;                      // /< Number of terms
     52    float *coeff;               // /< Coefficients
     53    float *coeffErr;            // /< Error in coefficients
     54    char *mask;                 // /< Coefficient mask
    6055}
    6156psPolynomial1D;
     
    6459typedef struct
    6560{
    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
    7066}
    7167psPolynomial2D;
     
    7470typedef struct
    7571{
    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
    8078}
    8179psPolynomial3D;
     
    8482typedef struct
    8583{
    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
    9091}
    9192psPolynomial4D;
    9293
    93 
    9494/** Functions **************************************************************/
    9595
    9696/** 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
     97psPolynomial1D *psPolynomial1DAlloc(int n       // /< Number of terms
     98                                   );
     99
     100/** Constructor */
     101psPolynomial2D *psPolynomial2DAlloc(int nX, int nY      // /< Number of terms in x and y
     102                                   );
     103
     104/** Constructor */
     105psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ      // /< Number of terms in x, y and z
     106                                   );
     107
     108/** Constructor */
     109psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ      // /< Number of terms in w, x, y and
     110                                    // z
    107111                                   );
    108112
    109113/** Evaluate 1D polynomial */
    110 float
    111 psPolynomial1DEval( float x,   ///< Value at which to evaluate
    112                     const psPolynomial1D *myPoly ///< Coefficients for the polynomial
    113                   );
     114float psPolynomial1DEval(float x,       // /< Value at which to evaluate
     115                         const psPolynomial1D * myPoly  // /< Coefficients for the polynomial
     116                        );
    114117
    115118/** 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                   );
     119float 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                        );
    121123
    122124/** 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                   );
     125float 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                        );
    129130
    130131/** 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                   );
     132float 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                        );
    138138
    139139/*****************************************************************************/
     
    144144typedef struct
    145145{
    146     int n;    ///< Number of terms
    147     double *coeff;   ///< Coefficients
    148     double *coeffErr;   ///< Error in coefficients
    149     char *mask;    ///< Coefficient mask
     146    int n;                      // /< Number of terms
     147    double *coeff;              // /< Coefficients
     148    double *coeffErr;           // /< Error in coefficients
     149    char *mask;                 // /< Coefficient mask
    150150}
    151151psDPolynomial1D;
     
    154154typedef struct
    155155{
    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
    160161}
    161162psDPolynomial2D;
     
    164165typedef struct
    165166{
    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
    170173}
    171174psDPolynomial3D;
     
    174177typedef struct
    175178{
    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
    180186}
    181187psDPolynomial4D;
    182188
    183189/** 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
     190psDPolynomial1D *psDPolynomial1DAlloc(int n     // /< Number of terms
     191                                     );
     192
     193/** Constructor */
     194psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY    // /< Number of terms in x and y
     195                                     );
     196
     197/** Constructor */
     198psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ    // /< Number of terms in x, y and z
     199                                     );
     200
     201/** Constructor */
     202psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ    // /< Number of terms in w, x, y and
     203                                      // z
    194204                                     );
    195205
    196206/** 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                    );
     207double psDPolynomial1DEval(double x,    // /< Value at which to evaluate
     208                           const psDPolynomial1D * myPoly       // /< Coefficients for the polynomial
     209                          );
    201210
    202211/** 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                    );
     212double 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                          );
    208216
    209217/** 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                    );
     218double 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                          );
    216223
    217224/** 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
     225double 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
    227233
    228234#endif
  • trunk/psLib/src/dataManip/psMatrix.c

    r1406 r1407  
     1
    12/** @file  psMatrix.c
    23 *
     
    2021 *  @author Ross Harman, MHPCC
    2122 *   
    22  *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
    23  *  @date $Date: 2004-08-06 22:34:05 $
     23 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
     24 *  @date $Date: 2004-08-07 00:06:06 $
    2425 *
    2526 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728
    2829/******************************************************************************/
     30
    2931/*  INCLUDE FILES                                                             */
     32
    3033/******************************************************************************/
    3134#include <string.h>
     
    4245
    4346/******************************************************************************/
     47
    4448/*  DEFINE STATEMENTS                                                         */
     49
    4550/******************************************************************************/
    4651
     
    4853
    4954/******************************************************************************/
     55
    5056/*  TYPE DEFINITIONS                                                          */
     57
    5158/******************************************************************************/
    5259
     
    5461
    5562/*****************************************************************************/
     63
    5664/*  GLOBAL VARIABLES                                                         */
     65
    5766/*****************************************************************************/
    5867
     
    6069
    6170/*****************************************************************************/
     71
    6272/*  FILE STATIC VARIABLES                                                    */
     73
    6374/*****************************************************************************/
    6475
     
    6677
    6778/*****************************************************************************/
     79
    6880/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     81
    6982/*****************************************************************************/
    7083
     
    142155
    143156/*****************************************************************************/
     157
    144158/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    145 /*****************************************************************************/
    146 
    147 psImage *psMatrixLUD(psImage *outImage, psVector *outPerm, psImage *inImage)
     159
     160/*****************************************************************************/
     161
     162psImage *psMatrixLUD(psImage * outImage, psVector * outPerm, psImage * inImage)
    148163{
    149164    int signum = 0;
     
    169184    numRows = inImage->numRows;
    170185    numCols = inImage->numCols;
    171     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     186    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    172187
    173188    // Initialize GSL data
     
    190205}
    191206
    192 psVector *psMatrixLUSolve(psVector *outVector, const psImage *inImage, const psVector *inVector, const
    193                           psVector *inPerm)
     207psVector *psMatrixLUSolve(psVector * outVector, const psImage * inImage, const psVector * inVector, const
     208                          psVector * inPerm)
    194209{
    195210    int arraySize = 0;
     
    219234    numRows = inImage->numRows;
    220235    numCols = inImage->numCols;
    221     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     236    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    222237
    223238    // Initialize GSL data
     
    243258}
    244259
    245 psImage *psMatrixInvert(psImage *outImage, const psImage *inImage, float *restrict det)
     260psImage *psMatrixInvert(psImage * outImage, const psImage * inImage, float *restrict det)
    246261{
    247262    int signum = 0;
     
    254269
    255270    // Error checks
    256     if(det == NULL) {
     271    if (det == NULL) {
    257272        psError(__func__, "Invalid operation: determinant argument is NULL.");
    258273        return outImage;
     
    269284    numRows = inImage->numRows;
    270285    numCols = inImage->numCols;
    271     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     286    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    272287
    273288    // Allocate GSL structs
     
    297312}
    298313
    299 float* psMatrixDeterminant(const psImage *restrict inImage)
     314float *psMatrixDeterminant(const psImage * restrict inImage)
    300315{
    301316    int signum = 0;
     
    315330    numRows = inImage->numRows;
    316331    numCols = inImage->numCols;
    317     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     332    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    318333
    319334    // Allocate GSL structs
     
    328343
    329344    // Calculate determinant
    330     det = (float*)psAlloc(sizeof(float));
     345    det = (float *)psAlloc(sizeof(float));
    331346    gsl_linalg_LU_decomp(lu, perm, &signum);
    332347    *det = (float)gsl_linalg_LU_det(lu, signum);
     
    339354}
    340355
    341 psImage* psMatrixMultiply(psImage *outImage, psImage *inImage1, psImage *inImage2)
     356psImage *psMatrixMultiply(psImage * outImage, psImage * inImage1, psImage * inImage2)
    342357{
    343358    int arraySize = 0;
     
    364379    numRows = inImage1->numRows;
    365380    numCols = inImage1->numCols;
    366     arraySize = PSELEMTYPE_SIZEOF(outImage->type.type)*numRows*numCols;
     381    arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) * numRows * numCols;
    367382
    368383    // Initialize GSL data
     
    381396}
    382397
    383 psImage* psMatrixTranspose(psImage *outImage, const psImage *inImage)
     398psImage *psMatrixTranspose(psImage * outImage, const psImage * inImage)
    384399{
    385400    int arraySize = 0;
     
    400415    numRows = inImage->numRows;
    401416    numCols = inImage->numCols;
    402     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     417    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    403418
    404419    // Initialize GSL data
     
    418433}
    419434
    420 psImage *psMatrixEigenvectors(psImage *outImage, psImage *inImage)
     435psImage *psMatrixEigenvectors(psImage * outImage, psImage * inImage)
    421436{
    422437    int numRows = 0;
     
    462477}
    463478
    464 psVector *psMatrixToVector(psVector *outVector, psImage *inImage)
     479psVector *psMatrixToVector(psVector * outVector, psImage * inImage)
    465480{
    466481    int size = 0;
     
    471486    PS_CHECK_SIZE_IMAGE(inImage, outVector);
    472487
    473     if(inImage->numRows == 1) {
     488    if (inImage->numRows == 1) {
    474489        // Create transposed row vector
    475490        PS_CHECK_ALLOC_VECTOR(outVector, inImage->numCols, inImage->type.type);
    476491        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    }
    486500
    487501    PS_CHECK_NULL_VECTOR(outVector, outVector);
    488502
    489 
    490503    // More checks
    491     if(outVector->type.dimen == PS_DIMEN_VECTOR) {
     504    if (outVector->type.dimen == PS_DIMEN_VECTOR) {
    492505        PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector);
    493506
    494         if(outVector->n == 0) {
     507        if (outVector->n == 0) {
    495508            outVector->n = inImage->numRows;
    496509        }
    497510
    498         if(outVector->n != inImage->numRows) {
     511        if (outVector->n != inImage->numRows) {
    499512            psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numRows, outVector->n);
    500513            return outVector;
    501514        }
    502515
    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;
    519523        }
    520524
     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
    521533    memcpy(outVector->data.V, inImage->data.V[0], size);
    522534
     
    524536}
    525537
    526 psImage *psVectorToMatrix(psImage *outImage, psVector *inVector)
     538psImage *psVectorToMatrix(psImage * outImage, psVector * inVector)
    527539{
    528540    int size = 0;
     
    531543    PS_CHECK_NULL_VECTOR(inVector, outImage);
    532544
    533     if(inVector->type.dimen == PS_DIMEN_VECTOR) {
     545    if (inVector->type.dimen == PS_DIMEN_VECTOR) {
    534546        PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outImage);
    535547        PS_CHECK_SIZE_VECTOR(inVector, outImage);
    536548        PS_CHECK_ALLOC_IMAGE(outImage, 1, inVector->n, PS_TYPE_F64)
    537 
    538549        // More checks for PS_DIMEN_VECTOR
    539         if(outImage->numCols > 1) {
     550        if (outImage->numCols > 1) {
    540551            psError(__func__, "Image has more than 1 column: numCols = %d.", outImage->numCols);
    541552            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;
    567556        }
     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    }
    568575
    569576    PS_CHECK_NULL_IMAGE(outImage, outImage);
     
    574581    return outImage;
    575582}
    576 
  • trunk/psLib/src/dataManip/psMatrix.h

    r974 r1407  
     1
    12/** @file  psMatrix.h
    23 *
     
    2122 *  @author Ross Harman, MHPCC
    2223 *
    23  *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
    24  *  @date $Date: 2004-06-10 01:58:06 $
     24 *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
     25 *  @date $Date: 2004-08-07 00:06:06 $
    2526 *
    2627 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2829
    2930#ifndef PSMATRIX_H
    30 #define PSMATRIX_H
     31#    define PSMATRIX_H
    3132
    3233/// @addtogroup Matrix
     
    4243 *  @return  psImage*: Pointer to LU decomposed psImage.
    4344 */
    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 );
     45psImage *psMatrixLUD(psImage * outImage,        // /< Image to return, or NULL.
     46                     psVector * outPerm,        // /< Output permutation vector used by psMatrixLUSolve.
     47                     psImage * inImage  // /< Image to decompose.
     48                    );
    4949
    5050/** LU Solution of psImage matrix.
     
    5757 *  @return  psVector*: Pointer to psVector solution of matrix equation.
    5858 */
    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 psMatrixLUD function.
    64 );
     59psVector *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                         );
    6565
    6666/** Invert psImage matrix.
     
    7373 *  @return  psImage*: Pointer to inverted psImage.
    7474 */
    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 );
     75psImage *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                       );
    8079
    8180/** Calculate psImage matrix determinant.
     
    8786 *  @return  float: Determinant from psImage.
    8887 */
    89 float* psMatrixDeterminant(
    90     const psImage *restrict inMatrix    ///< Image used to calculate determinant.
    91 );
     88float *psMatrixDeterminant(const psImage * restrict inMatrix    // /< Image used to calculate determinant.
     89                          );
    9290
    9391/** Performs psImage matrix multiplication.
     
    10098 *  @return  psImage*: Pointer to resulting psImage.
    10199 */
    102 psImage *psMatrixMultiply(
    103     psImage *outImage,  ///< Matrix to return, or NULL.
    104     psImage *inImage1,  ///< First input image.
    105     psImage *inImage2   ///< Second input image.
    106 );
     100psImage *psMatrixMultiply(psImage * outImage,   // /< Matrix to return, or NULL.
     101                          psImage * inImage1,   // /< First input image.
     102                          psImage * inImage2    // /< Second input image.
     103                         );
    107104
    108105/** Transpose matrix.
     
    115112 *  @return  psImage*: Pointer to transposed psImage.
    116113 */
    117 psImage *psMatrixTranspose(
    118     psImage *outImage,      ///< Image to return, or NULL
    119     const psImage *inImage  ///< Image to transpose
    120 );
     114psImage *psMatrixTranspose(psImage * outImage,  // /< Image to return, or NULL
     115                           const psImage * inImage      // /< Image to transpose
     116                          );
    121117
    122118/** Calculate matrix eigenvectors.
     
    128124 *  @return  psImage*: Pointer to matrix of Eigenvectors.
    129125 */
    130 psImage *psMatrixEigenvectors(
    131     psImage *outImage,  ///< Eigenvectors to return, or NULL.
    132     psImage *inImage    ///< Input image.
    133 );
     126psImage *psMatrixEigenvectors(psImage * outImage,       // /< Eigenvectors to return, or NULL.
     127                              psImage * inImage // /< Input image.
     128                             );
    134129
    135130/** Convert matrix to vector.
     
    142137 *  @return  psVector*: Pointer to psVector.
    143138 */
    144 psVector *psMatrixToVector(
    145     psVector *outVector,    ///< Vector to return, or NULL.
    146     psImage *inImage        ///< Image to convert.
    147 );
     139psVector *psMatrixToVector(psVector * outVector,        // /< Vector to return, or NULL.
     140                           psImage * inImage    // /< Image to convert.
     141                          );
    148142
    149143/** Convert vector to matrix.
     
    156150 *  @return  psVector*: Pointer to psIamge.
    157151 */
    158 psImage *psVectorToMatrix(
    159     psImage *outImage,  ///< Matrix to return, or NULL.
    160     psVector *inVector  ///< Vector to convert.
    161 );
     152psImage *psVectorToMatrix(psImage * outImage,   // /< Matrix to return, or NULL.
     153                          psVector * inVector   // /< Vector to convert.
     154                         );
    162155
    163156/// @}
  • trunk/psLib/src/dataManip/psMatrixVectorArithmetic.c

    r1406 r1407  
     1
    12/** @file  psMatrixVectorArithmetic.c
    23 *
     
    2930 *  @author Ross Harman, MHPCC
    3031 *
    31  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    32  *  @date $Date: 2004-08-06 22:34:05 $
     32 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     33 *  @date $Date: 2004-08-07 00:06:06 $
    3334 *
    3435 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    3637
    3738/******************************************************************************/
     39
    3840/*  INCLUDE FILES                                                             */
     41
    3942/******************************************************************************/
    4043#include <string.h>
     
    4952
    5053/******************************************************************************/
     54
    5155/*  DEFINE STATEMENTS                                                         */
     56
    5257/******************************************************************************/
    5358
     
    5560
    5661/******************************************************************************/
     62
    5763/*  TYPE DEFINITIONS                                                          */
     64
    5865/******************************************************************************/
    5966
     
    6168
    6269/*****************************************************************************/
     70
    6371/*  GLOBAL VARIABLES                                                         */
     72
    6473/*****************************************************************************/
    6574
     
    6776
    6877/*****************************************************************************/
     78
    6979/*  FILE STATIC VARIABLES                                                    */
     80
    7081/*****************************************************************************/
    7182
     
    7384
    7485/*****************************************************************************/
     86
    7587/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     88
    7689/*****************************************************************************/
    7790
     
    8598static complex double psNanDiv(complex double a, complex double b)
    8699{
    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))) {
    90104        psError(__func__, ": Divide by zero");
    91105    }
     
    399413    psType *psTypeOut = NULL;
    400414
    401     psTypeOut = (psType*)out;
    402     if(psTypeOut == NULL) {
     415    psTypeOut = (psType *) out;
     416    if (psTypeOut == NULL) {
    403417        psError(__func__, ": Line %d - Null out argument", __LINE__);
    404418        return out;
    405419    }
    406420
    407     psType1 = (psType*)in1;
    408     if(psType1 == NULL) {
     421    psType1 = (psType *) in1;
     422    if (psType1 == NULL) {
    409423        psError(__func__, ": Line %d - Null in1 argument", __LINE__);
    410424        return out;
    411425    }
    412426
    413     psType2 = (psType*)in2;
    414     if(psType2 == NULL) {
     427    psType2 = (psType *) in2;
     428    if (psType2 == NULL) {
    415429        psError(__func__, ": Line %d - Null in2 argument", __LINE__);
    416430        return out;
    417431    }
    418432
    419     if(op == NULL) {
     433    if (op == NULL) {
    420434        psError(__func__, ": Line %d - Null op argument", __LINE__);
    421435        return out;
     
    429443    elTypeOut = psTypeOut->type;
    430444
    431     if(elType1!=elType2 &&  elType1!=elTypeOut) {
     445    if (elType1 != elType2 && elType1 != elTypeOut) {
    432446        psError(__func__, ": Line %d - Element types for arguments inconsistent: (%d, %d, %d)", __LINE__,
    433447                elType1, elType2, elTypeOut);
     
    435449    }
    436450
    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) {
    438452        psError(__func__, ": Line %d - PS_DIMEN_OTHER not allowed for arguments: (%d, %d, %d)", __LINE__,
    439453                dim1, dim2, dimOut);
     
    441455    }
    442456
    443     if(dim1 == PS_DIMEN_VECTOR) {
    444         if(((psVector*)in1)->n == 0) {
     457    if (dim1 == PS_DIMEN_VECTOR) {
     458        if (((psVector *) in1)->n == 0) {
    445459            psError(__func__, ": Line %d - Vector contains zero elements");
    446460        }
    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) {
    456469            psError(__func__, ": Line %d - Vector contains zero elements");
    457470        }
    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    }
    506510
    507511    return out;
     
    567571    }                                                                                                        \
    568572}
    569 
    570573
    571574// Preprocessor macro function to create arithmetic function based on input type
     
    596599}
    597600
    598 
    599601// Preprocessor macro function to create arithmetic function operation name
    600602#define UNARY_OP(DIM,OUT,IN,OP)                                                                              \
     
    714716    psType *psTypeOut = NULL;
    715717
    716     psTypeOut = (psType*)out;
    717     if(psTypeOut == NULL) {
     718    psTypeOut = (psType *) out;
     719    if (psTypeOut == NULL) {
    718720        psError(__func__, ": Line %d - Null out argument", __LINE__);
    719721        return out;
    720722    }
    721723
    722     psTypeIn = (psType*)in;
    723     if(psTypeIn == NULL) {
     724    psTypeIn = (psType *) in;
     725    if (psTypeIn == NULL) {
    724726        psError(__func__, ": Line %d - Null in argument", __LINE__);
    725727        return out;
    726728    }
    727729
    728     if(op == NULL) {
     730    if (op == NULL) {
    729731        psError(__func__, ": Line %d - Null op argument", __LINE__);
    730732        return out;
     
    736738    elTypeOut = psTypeOut->type;
    737739
    738     if(elTypeIn!=elTypeOut) {
     740    if (elTypeIn != elTypeOut) {
    739741        psError(__func__, ": Line %d - Element types for arguments inconsistent: (%d, %d)", __LINE__,
    740742                elTypeIn, elTypeOut);
     
    742744    }
    743745
    744     if(dimIn!=dimOut) {
     746    if (dimIn != dimOut) {
    745747        psError(__func__, ": Line %d - Dimensionality for arguments inconsistent: (%d, %d)", __LINE__,
    746748                dimIn, dimOut);
     
    748750    }
    749751
    750     if(dimIn==PS_DIMEN_OTHER || dimOut==PS_DIMEN_OTHER) {
     752    if (dimIn == PS_DIMEN_OTHER || dimOut == PS_DIMEN_OTHER) {
    751753        psError(__func__, ": Line %d - PS_DIMEN_OTHER not allowed for arguments: (%d, %d)", __LINE__,
    752754                dimIn, dimOut);
     
    754756    }
    755757
    756     if(dimIn == PS_DIMEN_VECTOR) {
    757         if(((psVector*)in)->n == 0) {
     758    if (dimIn == PS_DIMEN_VECTOR) {
     759        if (((psVector *) in)->n == 0) {
    758760            psError(__func__, ": Line %d - Vector contains zero elements");
    759761        }
    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) {
    769770            psError(__func__, ": Line %d - Vector contains zero elements");
    770771        }
    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    }
    789787
    790788    return out;
  • trunk/psLib/src/dataManip/psMatrixVectorArithmetic.h

    r1058 r1407  
     1
    12/** @file  psMatrixVectorArithmetic.h
    23 *
     
    2930 *  @author Ross Harman, MHPCC
    3031 *
    31  *  @version $Revision: 1.1 $ $Name: not supported by cvs2svn $
    32  *  @date $Date: 2004-06-18 00:54:43 $
     32 *  @version $Revision: 1.2 $ $Name: not supported by cvs2svn $
     33 *  @date $Date: 2004-08-07 00:06:06 $
    3334 *
    3435 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    3637
    3738#ifndef PSMATRIX_VECTOR_ARITHMETIC_H
    38 #define PSMATRIX_VECTOR_ARITHMETIC_H
     39#    define PSMATRIX_VECTOR_ARITHMETIC_H
    3940
    4041/// @addtogroup MatrixVectorArithmetic
     
    5455 *  @return  psType*: Pointer to either psImage or psVector.
    5556 */
    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 );
     57psType *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                  );
    6262
    6363/** Perform simple unary arithmetic with images or vectors
     
    7777 *  @return  psType*: Pointer to either psImage or psVector.
    7878 */
    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 );
     79psType *psUnaryOp(void *out,    // / Output type, either psImage or psVector.
     80                  void *in,     // / Input, either psImage or psVector.
     81                  char *op      // / Operator.
     82                 );
    8483
    8584/// @}
  • trunk/psLib/src/dataManip/psMinimize.c

    r1406 r1407  
     1
    12/** @file  psMinimize.c
    23 *  \brief basic minimization functions
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.27 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.28 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    16 /*****************************************************************************/
     17
     18/*****************************************************************************/
     19
    1720/* INCLUDE FILES                                                             */
     21
    1822/*****************************************************************************/
    1923#include <stdlib.h>
     
    4044#include "psMinimize.h"
    4145#include "psMatrix.h"
    42 /*****************************************************************************/
     46
     47/*****************************************************************************/
     48
    4349/* DEFINE STATEMENTS                                                         */
     50
    4451/*****************************************************************************/
    4552#define MAX_LMM_ITERATIONS 100
     
    8390}
    8491
    85 
    86 /*****************************************************************************/
     92/*****************************************************************************/
     93
    8794/* TYPE DEFINITIONS                                                          */
     95
    8896/*****************************************************************************/
    8997typedef struct
    9098{
    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;
    95103    const psVector *restrict data;
    96     const psVector *restrict  errors;
     104    const psVector *restrict errors;
    97105    const psVector *restrict paramMask;
    98106    float (*evalModel) (const psVector *, const psVector *);
     
    103111typedef struct
    104112{
    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;
    108116    const psVector *restrict paramMask;
    109117    float (*evalModel) (const psVector *, const psVector *);
     
    113121
    114122/*****************************************************************************/
     123
    115124/* GLOBAL VARIABLES                                                          */
     125
    116126/*****************************************************************************/
    117127
     
    119129
    120130/*****************************************************************************/
     131
    121132/* FILE STATIC VARIABLES                                                     */
     133
    122134/*****************************************************************************/
    123135
     
    125137
    126138/*****************************************************************************/
     139
    127140/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     141
    128142/*****************************************************************************/
    129143
     
    143157 guess at the parameters, an option parameter mask, etc.
    144158 *****************************************************************************/
    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;
     159double 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;
    156168    psVector *inputParameterList = NULL;
    157169
     
    163175    if (mask != NULL) {
    164176        j = 0;
    165         for (i=0;i<mask->n;i++) {
     177        for (i = 0; i < mask->n; i++) {
    166178            if (mask->data.U8[i] != 0) {
    167179                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    171183        }
    172184    } else {
    173         for (i=0;i<initialGuess->n;i++) {
     185        for (i = 0; i < initialGuess->n; i++) {
    174186            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    175187        }
     
    181193    // Free allocated memory and return the value of the function.
    182194    psFree(inputParameterList);
    183     return(tmpf);
     195    return (tmpf);
    184196}
    185197
     
    199211 in "params" and return those derivatives in this psVector.
    200212 *****************************************************************************/
    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) =
     213void 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) =
    212222        ((psMinimizeData *) funcData)->d_evalModel;
    213223    psVector *inputParameterList = NULL;
     
    220230    if (mask != NULL) {
    221231        j = 0;
    222         for (i=0;i<mask->n;i++) {
     232        for (i = 0; i < mask->n; i++) {
    223233            if (mask->data.U8[i] != 0) {
    224234                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    228238        }
    229239    } else {
    230         for (i=0;i<initialGuess->n;i++) {
     240        for (i = 0; i < initialGuess->n; i++) {
    231241            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    232242        }
     
    235245    // Evaluate the derivative w.r.t. each parameter.
    236246    // 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++) {
    238248        tmpf = d_evalModel(inputParameterList, coord, i);
    239249        gsl_vector_set(df, i, tmpf);
     
    247257    Compute both p_psMinFunc and p_psMinFuncDeriv together.
    248258 *****************************************************************************/
    249 void p_psMinFuncFuncDeriv(const gsl_vector *params,
    250                           void *funcData,
    251                           double *f,
    252                           gsl_vector *df)
     259void p_psMinFuncFuncDeriv(const gsl_vector * params, void *funcData, double *f, gsl_vector * df)
    253260{
    254261    *f = p_psMinFunc(params, funcData);
     
    281288  expected value and divide by the error.
    282289 *****************************************************************************/
    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;
     290int 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;
    296301    psVector *inputParameterList = NULL;
    297302    psVector *tmpVecPtr = NULL;
     
    307312    if (mask != NULL) {
    308313        j = 0;
    309         for (i=0;i<mask->n;i++) {
     314        for (i = 0; i < mask->n; i++) {
    310315            if (mask->data.U8[i] != 0) {
    311316                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    315320        }
    316321    } else {
    317         for (i=0;i<initialGuess->n;i++) {
     322        for (i = 0; i < initialGuess->n; i++) {
    318323            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    319324        }
     
    321326
    322327    // 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++) {
    325330            tmpVecPtr->data.F32[j] = domain->data.F32[i][j];
    326331        }
    327332        tmpf = evalModel(tmpVecPtr, inputParameterList);
    328333
    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]);
    331335    }
    332336
     
    354358 and returned in this data structure.
    355359 *****************************************************************************/
    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;
     360int 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;
    364366    psVector *inputParameterList = NULL;
    365367    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;
    367370
    368371    size_t i;
     
    380383    if (mask != NULL) {
    381384        j = 0;
    382         for (i=0;i<mask->n;i++) {
     385        for (i = 0; i < mask->n; i++) {
    383386            if (mask->data.U8[i] != 0) {
    384387                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    388391        }
    389392    } else {
    390         for (i=0;i<initialGuess->n;i++) {
     393        for (i = 0; i < initialGuess->n; i++) {
    391394            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    392395        }
     
    394397
    395398    // 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++) {
    398401            tmpVecPtr->data.F32[j] = domain->data.F32[i][j];
    399402        }
    400403
    401         for (j=0;j<inputParameterList->n;j++) {
     404        for (j = 0; j < inputParameterList->n; j++) {
    402405            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]));
    404407        }
    405408    }
     
    410413}
    411414
    412 
    413 int p_psMinChi2FuncFuncDeriv(const gsl_vector *params,
    414                              void *funcData,
    415                              gsl_vector *f,
    416                              gsl_matrix *J)
     415int p_psMinChi2FuncFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * f, gsl_matrix * J)
    417416{
    418417    p_psMinChi2Func(params, funcData, f);
     
    421420    return GSL_SUCCESS;
    422421}
    423 
    424422
    425423/******************************************************************************
     
    428426returned as a psVector sums.
    429427 *****************************************************************************/
    430 void p_psBuildSums1D(double x,
    431                      int polyOrder,
    432                      psVector *sums)
    433 {
    434     int       i = 0;
    435     double    xSum = 0.0;
     428void p_psBuildSums1D(double x, int polyOrder, psVector * sums)
     429{
     430    int i = 0;
     431    double xSum = 0.0;
    436432
    437433    xSum = 1.0;
    438     for(i=0;i<=polyOrder;i++) {
     434    for (i = 0; i <= polyOrder; i++) {
    439435        sums->data.F64[i] = xSum;
    440         xSum*= x;
    441     }
    442 }
    443 
     436        xSum *= x;
     437    }
     438}
    444439
    445440/******************************************************************************
     
    448443 *****************************************************************************/
    449444psVector *psBuildImageScalingFactors(int x)
    450 
    451445{
    452446    int i = 0;                  // loop index variable.
    453447    psVector *imageScalingFactors = NULL;
    454448
    455 
    456449    imageScalingFactors = psVectorAlloc(x, PS_TYPE_F32);
    457450
    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);
    463456}
    464457
     
    481474    *flag   Set this to 1 if we must recalculate the coefficients.
    482475 *****************************************************************************/
    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
     476void 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
    493482    // 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
    497487    // polynomial.
    498     int         lastTerm = 0;           // The index location of the first
     488    int lastTerm = 0;           // The index location of the first
     489
    499490    // 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.
    501492
    502493    // 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));
    508499    }
    509500
    510501    // Invert the matrix A and put the result in y[][].  This code is taken
    511502    // 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++) {
    514505            col[i] = 0.0;
    515506        }
    516507        col[j] = 1.0;
    517508        // 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++) {
    520511            y[i][j] = col[i];
    521512        }
     
    527518    // terms and check if they are consistent with zero.
    528519
    529     numPolyTerms = (((polyOrder+1) * (polyOrder + 2)) / 2);
     520    numPolyTerms = (((polyOrder + 1) * (polyOrder + 2)) / 2);
    530521    lastTerm = numPolyTerms + 1;
    531522    firstTerm = lastTerm - polyOrder;
    532523    *flag = 1;
    533     for (i=firstTerm; i<=lastTerm; i++) {
     524    for (i = firstTerm; i <= lastTerm; i++) {
    534525        #ifdef DARWIN
    535526        error[i] = (float)sqrt(y[i][i]);
     
    539530        #endif
    540531
    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]))) {
    543533            *flag = 0;
    544534        }
     
    548538    psFree(error);
    549539    psFree(col);
    550     for(j=1;j<=N;j++) {
     540    for (j = 1; j <= N; j++) {
    551541        psFree(y[j]);
    552542    }
     
    554544}
    555545
    556 
    557 
    558 
    559 /*****************************************************************************/
     546/*****************************************************************************/
     547
    560548/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    561 /*****************************************************************************/
    562 
    563 
     549
     550/*****************************************************************************/
    564551
    565552/******************************************************************************
     
    569556parameters of that function such that the ...
    570557 *****************************************************************************/
    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)
     558psVector *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)
    577562{
    578563    int status;
     
    607592    // for the parameters.
    608593    if (paramMask != NULL) {
    609         for (i=0;i<paramMask->n;i++) {
     594        for (i = 0; i < paramMask->n; i++) {
    610595            if (paramMask->data.U8[i] != 0) {
    611596                inputData.paramCount++;
     
    613598        }
    614599    } else {
    615         inputData.paramCount= initialGuess->n;
     600        inputData.paramCount = initialGuess->n;
    616601    }
    617602
     
    622607    if (paramMask != NULL) {
    623608        j = 0;
    624         for (i=0;i<initialGuess->n;i++) {
     609        for (i = 0; i < initialGuess->n; i++) {
    625610            if (paramMask->data.U8[i] == 0) {
    626611                gsl_vector_set(x, j++, initialGuess->data.F32[i]);
     
    628613        }
    629614    } else {
    630         for (i=0;i<initialGuess->n;i++) {
     615        for (i = 0; i < initialGuess->n; i++) {
    631616            gsl_vector_set(x, i, initialGuess->data.F32[i]);
    632617        }
     
    651636
    652637        if (status == GSL_SUCCESS)
    653             printf ("Minimum found at:\n");
     638            printf("Minimum found at:\n");
    654639
    655640    } while (status == GSL_CONTINUE && iter < MAX_MINIMIZE_ITERATIONS);
     
    660645    if (paramMask != NULL) {
    661646        j = 0;
    662         for (i=0;i<initialGuess->n;i++) {
     647        for (i = 0; i < initialGuess->n; i++) {
    663648            if (paramMask->data.U8[i] == 0) {
    664649                initialGuess->data.F32[i] = gsl_vector_get(s->x, j++);
     
    668653        }
    669654    } else {
    670         for (i=0;i<initialGuess->n;i++) {
     655        for (i = 0; i < initialGuess->n; i++) {
    671656            initialGuess->data.F32[i] = gsl_vector_get(s->x, i);
    672657        }
    673658    }
    674     return(initialGuess);
    675 }
    676 
    677 
    678 
    679 
    680 
     659    return (initialGuess);
     660}
    681661
    682662/******************************************************************************
     
    684664    such that they best fit the supplied data points.
    685665 *****************************************************************************/
    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
     666psVector *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
    702680    // 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
    704683    // with masked parameters removed.
    705684    const gsl_multifit_fdfsolver_type *T;
     685
    706686    // This tells GSL to use the Levenberg-
    707687    // Marquardt algorithm for chi2
    708688    // minimization.
    709     gsl_multifit_fdfsolver *s; // GSL data structure.
     689    gsl_multifit_fdfsolver *s;  // GSL data structure.
    710690    psMinChi2Data inputData;
    711691    float chiSqOld = 0.0;
     
    721701    PS_CHECK_VECTOR_SIZE_EQUAL(data, errors);
    722702    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.");
    724704    }
    725705    if (paramMask != NULL) {
     
    743723    // for the parameters.
    744724    if (paramMask != NULL) {
    745         for (i=0;i<paramMask->n;i++) {
     725        for (i = 0; i < paramMask->n; i++) {
    746726            if (paramMask->data.U8[i] != 0) {
    747727                inputData.paramCount++;
     
    749729        }
    750730    } else {
    751         inputData.paramCount= initialGuess->n;
     731        inputData.paramCount = initialGuess->n;
    752732    }
    753733
     
    755735    // the vector inputParameterList.  If the paramMask is not NULL, then those
    756736    // parameters are masked out.
    757     xInit = (double *) psAlloc(inputData.paramCount * sizeof(double));
     737    xInit = (double *)psAlloc(inputData.paramCount * sizeof(double));
    758738    if (paramMask != NULL) {
    759739        j = 0;
    760         for (i=0;i<initialGuess->n;i++) {
     740        for (i = 0; i < initialGuess->n; i++) {
    761741            if (paramMask->data.U8[i] == 0) {
    762742                xInit[j++] = initialGuess->data.F32[i];
     
    764744        }
    765745    } else {
    766         for (i=0;i<initialGuess->n;i++) {
     746        for (i = 0; i < initialGuess->n; i++) {
    767747            xInit[i] = initialGuess->data.F32[i];
    768748        }
     
    771751    const gsl_rng_type *type;
    772752    gsl_rng *r;
     753
    773754    gsl_rng_env_setup();
    774755
     
    789770
    790771    gsl_vector_view x = gsl_vector_view_array(xInit, inputData.paramCount);
     772
    791773    T = gsl_multifit_fdfsolver_lmsder;
    792774    s = gsl_multifit_fdfsolver_alloc(T, numData, inputData.paramCount);
     
    796778    do {
    797779        iter++;
    798         for (i=0;i<initialGuess->n;i++) {
     780        for (i = 0; i < initialGuess->n; i++) {
    799781            printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i));
    800782        }
     
    802784        status = gsl_multifit_fdfsolver_iterate(s);
    803785        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++) {
    805787            printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i));
    806788        }
     
    810792            psAbort(__func__, "gsl_multifit_fdfsolver_iterate(%s)\n", gsl_strerror(status));
    811793        }
    812 
    813794        // Test if the parameters changed by a small enough amount.
    814795        // NOTE: This wasn't working right when the parameters fit exactly.
    815796        // 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);
    817798
    818799        // We test for convergence if chiSquared changes by less than 1.0
     
    829810    } while (status == GSL_CONTINUE && iter < MAX_LMM_ITERATIONS);
    830811
    831 
    832812    // In the above steps we had removed the masked elements from the
    833813    // the solver.  This next code blocks puts those masked elements
     
    835815    if (paramMask != NULL) {
    836816        j = 0;
    837         for (i=0;i<initialGuess->n;i++) {
     817        for (i = 0; i < initialGuess->n; i++) {
    838818            if (paramMask->data.U8[i] == 0) {
    839819                initialGuess->data.F32[i] = gsl_vector_get(s->x, j++);
     
    843823        }
    844824    } else {
    845         for (i=0;i<initialGuess->n;i++) {
     825        for (i = 0; i < initialGuess->n; i++) {
    846826            initialGuess->data.F32[i] = gsl_vector_get(s->x, i);
    847827        }
     
    857837
    858838    // Bye bye.
    859     return(initialGuess);
    860 }
    861 
     839    return (initialGuess);
     840}
    862841
    863842/******************************************************************************
     
    868847NOTE: yErr is currently ignored.
    869848 *****************************************************************************/
    870 psPolynomial1D *
    871 psVectorFitPolynomial1D(psPolynomial1D *myPoly,
    872                         const psVector *restrict x,
    873                         const psVector *restrict y,
    874                         const psVector *restrict yErr)
     849psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly,
     850                                        const psVector * restrict x,
     851                                        const psVector * restrict y, const psVector * restrict yErr)
    875852{
    876853    int polyOrder = myPoly->n;
     
    879856    psVector *B = NULL;
    880857    psVector *outPerm = NULL;
    881     psVector *X = NULL;   // NOTE: do we need this?
     858    psVector *X = NULL;         // NOTE: do we need this?
    882859    psVector *coeffs = NULL;
    883860    int i = 0;
     
    886863    psVector *xSums = NULL;
    887864
    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    // }
    892869
    893870    PS_CHECK_NULL_1DPOLY(myPoly);
     
    901878    PS_CHECK_VECTOR_SIZE_EQUAL(y, yErr);
    902879
    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);
    908885    outPerm = psVectorAlloc(polyOrder, PS_TYPE_F64);
    909     xSums   = psVectorAlloc(1+2*polyOrder, PS_TYPE_F64);
     886    xSums = psVectorAlloc(1 + 2 * polyOrder, PS_TYPE_F64);
    910887
    911888    // Initialize data structures.
    912     for(i=0;i<(polyOrder);i++) {
     889    for (i = 0; i < (polyOrder); i++) {
    913890        B->data.F64[i] = 0.0;
    914891        coeffs->data.F64[i] = 0.0;
    915892        outPerm->data.F64[i] = 0.0;
    916         for(j=0;j<(polyOrder);j++) {
     893        for (j = 0; j < (polyOrder); j++) {
    917894            A->data.F64[i][j] = 0.0;
    918895            ALUD->data.F64[i][j] = 0.0;
    919896        }
    920897    }
    921     for (i=0;i<X->n;i++) {
     898    for (i = 0; i < X->n; i++) {
    922899        X->data.F64[i] = x->data.F64[i];
    923900    }
    924901
    925902    // 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];
    936913            }
    937914        }
     
    941918    coeffs = psMatrixLUSolve(coeffs, ALUD, B, outPerm);
    942919
    943     for(k=0;k<(polyOrder);k++) {
     920    for (k = 0; k < (polyOrder); k++) {
    944921        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    // }
    952929
    953930    psFree(A);
     
    959936    psFree(xSums);
    960937
    961     return(myPoly);
    962 }
     938    return (myPoly);
     939}
  • trunk/psLib/src/dataManip/psMinimize.h

    r1406 r1407  
    11#if !defined(PS_MINIMIZE_H)
    2 #define PS_MINIMIZE_H
     2#    define PS_MINIMIZE_H
    33
    4 #include "psFunctions.h"
     4#    include "psFunctions.h"
     5
    56/** \file psMinimize.h
    67 *  \brief minimization operations
     
    910
    1011/** Functions **************************************************************/
     12
    1113/** \addtogroup Stats
    1214 *  \{
     
    1416
    1517/** 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 
     18psVector *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);
    2322
    2423/** 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               );
     24psVector *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);
    3848
    3949/** 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 use the indices)
    43                         const psVector *restrict y, ///< Coordinates
    44                         const psVector *restrict yErr ///< Errors in coordinates, or NULL
    45                        );
     50psPolynomial1D *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                                       );
    4656
    47 /* \} */ // End of MathGroup Functions
     57/* \} */// End of MathGroup Functions
    4858
    4959#endif
  • trunk/psLib/src/dataManip/psStats.c

    r1406 r1407  
     1
    12/** @file  psStats.c
    23 *  \brief basic statistical operations
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.51 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.52 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2122#include <float.h>
    2223#include <math.h>
     24
    2325/*****************************************************************************/
     26
    2427/* INCLUDE FILES                                                             */
     28
    2529/*****************************************************************************/
    2630#include "psMemory.h"
     
    3539
    3640/*****************************************************************************/
     41
    3742/* DEFINE STATEMENTS                                                         */
     43
    3844/*****************************************************************************/
    3945// 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.
    4147#define CLIPPED_NUM_ITER_LB 1
    4248#define CLIPPED_NUM_ITER_UB 10
     
    4854#define MAX_ITERATIONS 10
    4955
    50 void p_psVectorRobustStats( const psVector *restrict myVector,
    51                             const psVector *restrict maskVector,
    52                             unsigned int maskVal,
    53                             psStats *stats );
     56void p_psVectorRobustStats(const psVector * restrict myVector,
     57                           const psVector * restrict maskVector, unsigned int maskVal, psStats * stats);
    5458
    5559/** Preprocessor macro to generate error on an incorrect type */
     
    8387printf("\n"); \
    8488
     89
    8590/*****************************************************************************/
     91
    8692/* TYPE DEFINITIONS                                                          */
     93
    8794/*****************************************************************************/
    8895
    8996/*****************************************************************************/
     97
    9098/* GLOBAL VARIABLES                                                          */
     99
    91100/*****************************************************************************/
    92101
     
    94103
    95104/*****************************************************************************/
     105
    96106/* FILE STATIC VARIABLES                                                     */
     107
    97108/*****************************************************************************/
    98109
     
    100111
    101112/*****************************************************************************/
     113
    102114/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     115
    103116/*****************************************************************************/
    104117
    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 ) ) {
     118bool 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)) {
    110122    case PS_STAT_SAMPLE_MEAN:
    111123        *value = stats->sampleMean;
     
    163175 *****************************************************************************/
    164176
    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 ] );
     177void 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]);
    175184        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]);
    177186    }
    178187}
     
    195204 *****************************************************************************/
    196205
    197 
    198206/******************************************************************************
    199207p_psVectorSampleMean(myVector, maskVector, maskVal, stats): calculates the
     
    210218 *****************************************************************************/
    211219
    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
     220void 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
    222228
    223229    // If PS_STAT_USE_RANGE is requested, then we enter a slightly different
    224230    // loop.
    225     if ( stats->options & PS_STAT_USE_RANGE ) {
     231    if (stats->options & PS_STAT_USE_RANGE) {
    226232        rangeMin = stats->min;
    227233        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++) {
    230236                // 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];
    235240                    count++;
    236241                }
    237242            }
    238             mean /= ( float ) count;
     243            mean /= (float)count;
    239244        } 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];
    244248                    count++;
    245249                }
    246250            }
    247             mean /= ( float ) count;
     251            mean /= (float)count;
    248252        }
    249253    } 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];
    254258                    count++;
    255259                }
    256260            }
    257             mean /= ( float ) count;
     261            mean /= (float)count;
    258262        } 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;
    263267        }
    264268    }
     
    278282    NULL
    279283 *****************************************************************************/
    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
     284void 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
    289291
    290292    // 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) {
    292294        rangeMin = stats->min;
    293295        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];
    301302                    }
    302303                }
    303304            }
    304305        } 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];
    310310                }
    311311            }
    312312        }
    313313    } 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];
    319319                    }
    320320                }
    321321            }
    322322        } 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];
    326326                }
    327327            }
     
    343343    NULL
    344344 *****************************************************************************/
    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 ) {
     345void 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) {
    356354        rangeMin = stats->min;
    357355        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];
    365362                    }
    366363                }
    367364            }
    368365        } 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];
    374370                }
    375371            }
    376372        }
    377373    } 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];
    383379                    }
    384380                }
    385381            }
    386382        } 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];
    390386                }
    391387            }
     
    408404    NULL
    409405 *****************************************************************************/
    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 ) {
     406int 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) {
    421415        rangeMin = stats->min;
    422416        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)) {
    428421                    numData++;
    429422                }
    430423            }
    431424        } 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)) {
    435427                    numData++;
    436428                }
     
    440432        rangeMin = stats->min;
    441433        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])) {
    445437                    numData++;
    446438                }
     
    450442        }
    451443    }
    452     return ( numData );
    453 }
    454 
    455 
     444    return (numData);
     445}
    456446
    457447/******************************************************************************
     
    466456    NULL
    467457 *****************************************************************************/
    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 
     458void 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
    481468
    482469    // Determine if the number of data points exceed a threshold which will
     
    485472    // regardless of the vector size.
    486473    /*
    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; } */
    506489
    507490    // Determine how many data points fit inside this min/max range
    508491    // 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);
    510493
    511494    // Allocate temporary vectors for the data.
    512     unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     495    unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    513496    unsortedVector->n = unsortedVector->nalloc;
    514497
    515     sortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     498    sortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    516499    sortedVector->n = sortedVector->nalloc;
    517500
    518501    // 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) {
    520503        rangeMin = stats->min;
    521504        rangeMax = stats->max;
     
    524507        // into the temporary vectors.
    525508        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];
    532514                }
    533515            }
    534516        } 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];
    539520                }
    540521            }
     
    543524        // Store all non-masked data points into the temporary vectors.
    544525        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];
    549530                }
    550531            }
    551532        } 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];
    554535            }
    555536        }
    556537    }
    557538    // Sort the temporary vectors.
    558     psVectorSort( sortedVector, unsortedVector );
     539    psVectorSort(sortedVector, unsortedVector);
    559540
    560541    // Calculate the median exactly.
    561542    // 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]);
    565546    } else {
    566         stats->sampleMedian = sortedVector->data.F32[ nValues / 2 ];
     547        stats->sampleMedian = sortedVector->data.F32[nValues / 2];
    567548    }
    568549
    569550    // Free the temporary data structures.
    570     psFree( unsortedVector );
    571     psFree( sortedVector );
     551    psFree(unsortedVector);
     552    psFree(sortedVector);
    572553}
    573554
     
    584565    XXX: use a static variable for gaussianCoefs[] and compute them once.
    585566 *****************************************************************************/
    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 ) {
     567psVector *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) {
    598578            // If sigma does not equal zero, then we use Gaussian smoothing.
    599579            #ifdef  DARWIN
    600             denom = ( float ) sqrt( 2.0 * M_PI * sigma * sigma );
     580            denom = (float)sqrt(2.0 * M_PI * sigma * sigma);
    601581            #else
    602582
    603             denom = sqrtf( 2.0 * M_PI * sigma * sigma );
     583            denom = sqrtf(2.0 * M_PI * sigma * sigma);
    604584            #endif
    605585
    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);
    609589
    610590            // NOTE: Gaussian smoothing just isn't working with low sigma
     
    612592            // all zero, except for the middle coefficient, which is exactly
    613593            // 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]);
    616596        } 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);
    625603        }
    626604    }
    627605
    628606    // 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);
    639617}
    640618
     
    650628    NULL
    651629 *****************************************************************************/
    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
     630void 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
    664640
    665641    // Determine how many data points fit inside this min/max range
    666642    // 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);
    668644
    669645    // Allocate temporary vectors for the data.
    670     unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     646    unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    671647    unsortedVector->n = unsortedVector->nalloc;
    672     sortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     648    sortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    673649    sortedVector->n = sortedVector->nalloc;
    674650
    675651    // 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) {
    677653        rangeMin = stats->min;
    678654        rangeMax = stats->max;
     
    680656        // into the temporary vectors.
    681657        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];
    688663                }
    689664            }
    690665        } 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];
    695669                }
    696670            }
     
    699673        // Store all non-masked data points into the temporary vectors.
    700674        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];
    705679                }
    706680            }
    707681        } 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];
    710684            }
    711685        }
     
    713687
    714688    // Sort the temporary vectors.
    715     psVectorSort( sortedVector, unsortedVector );
     689    psVectorSort(sortedVector, unsortedVector);
    716690
    717691    // 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];
    720694
    721695    // Free the temporary data structures.
    722     psFree( unsortedVector );
    723     psFree( sortedVector );
    724 }
    725 
     696    psFree(unsortedVector);
     697    psFree(sortedVector);
     698}
    726699
    727700/******************************************************************************
     
    737710 
    738711 *****************************************************************************/
    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
     712void 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
    753724
    754725    // This procedure requires the mean.  If it has not been already
    755726    // 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);
    758729    }
    759730    mean = stats->sampleMean;
    760731
    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);
    769739                    sumDiffs += diff;
    770740                    countInt++;
     
    772742            }
    773743        } 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);
    779748                    sumDiffs += diff;
    780749                    countInt++;
     
    784753        }
    785754    } 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);
    791760                    sumDiffs += diff;
    792761                    countInt++;
     
    794763            }
    795764        } 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);
    799768                sumDiffs += diff;
    800769                countInt++;
     
    803772        }
    804773    }
    805     countFloat = ( float ) countInt;
     774    countFloat = (float)countInt;
    806775
    807776    #ifdef DARWIN
    808777
    809     stats->sampleStdev = ( float ) sqrt( ( sumSquares - ( sumDiffs *
    810                                            sumDiffs / countFloat ) ) / ( countFloat - 1 ) );
     778    stats->sampleStdev = (float)sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1));
    811779    #else
    812780
    813     stats->sampleStdev = sqrtf( ( sumSquares - ( sumDiffs *
    814                                   sumDiffs / countFloat ) ) / ( countFloat - 1 ) );
     781    stats->sampleStdev = sqrtf((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1));
    815782    #endif
    816783}
     
    828795    NULL
    829796 *****************************************************************************/
    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
     797void 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
    842807
    843808    // 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    }
    850812    // 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    }
    857816    // We allocate a temporary mask vector since during the iterative
    858817    // steps that follow, we will be masking off additional data points.
    859818    // 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);
    861820    tmpMask->n = myVector->n;
    862821
    863822    // If we were called with a mask vector, then initialize the temporary
    864823    // 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    }
    871829    // 1. Compute the sample median.
    872830    // NOTE: This seems odd.  Verify with IfA that we want to calculate the
    873831    // median here, not the mean.
    874     p_psVectorSampleMedian( myVector, maskVector, maskVal, stats );
     832    p_psVectorSampleMedian(myVector, maskVector, maskVal, stats);
    875833
    876834    // 2. Compute the sample standard deviation.
    877     p_psVectorSampleStdev( myVector, maskVector, maskVal, stats );
     835    p_psVectorSampleStdev(myVector, maskVector, maskVal, stats);
    878836
    879837    // 3. Use the sample median as the first estimator of the mean X.
     
    889847
    890848    // 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++) {
    893851            // 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;
    897854            }
    898855            // 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);
    901858
    902859            // c) Use the new mean for x
     
    912869
    913870    // 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) {
    915872        stats->clippedMean = clippedMean;
    916873    }
    917 
    918874    // 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) {
    920876        stats->clippedStdev = clippedStdev;
    921877    }
    922878
    923     psFree( tmpMask );
     879    psFree(tmpMask);
    924880}
    925881
     
    928884elements of a vector to a range between 0.0 and 1.0.
    929885 *****************************************************************************/
    930 void p_psNormalizeVector( psVector *myData )
    931 {
    932     float min = ( float ) HUGE;
    933     float max = ( float ) - HUGE;
     886void p_psNormalizeVector(psVector * myData)
     887{
     888    float min = (float)HUGE;
     889    float max = (float)-HUGE;
    934890    float range = 0.0;
    935891    int i = 0;
    936892
    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];
    943899        }
    944900    }
    945901
    946902    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}
    952907
    953908/*****************************************************************************
     
    956911specified data point.
    957912 *****************************************************************************/
    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 );
     913float 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);
    969924}
    970925
     
    973928calculates the specified partial derivative of the above Gaussian function.
    974929 *****************************************************************************/
    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 ];
     930float 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];
    982935    float tmp = 0.0;
    983936
    984     if ( whichParam == 0 ) {
     937    if (whichParam == 0) {
    985938        // 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}
    999950
    1000951/*****************************************************************************
     
    1003954specified data point.
    1004955 *****************************************************************************/
    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 ];
     956float 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];
    1012962    float tmp = 0.0;
    1013963
    1014     tmp = ( A * x * x ) + ( B * x ) + C;
    1015     return ( tmp );
     964    tmp = (A * x * x) + (B * x) + C;
     965    return (tmp);
    1016966}
    1017967
     
    1020970calculates the specified partial derivative of the above quadratic function.
    1021971 *****************************************************************************/
    1022 float p_psQuadraticDeriv( const psVector *restrict myParams,
    1023                           const psVector *restrict myCoords,
    1024                           int whichParamDeriv )
    1025 {
    1026     float x = myCoords->data.F32[ 0 ];
     972float p_psQuadraticDeriv(const psVector * restrict myParams,
     973                         const psVector * restrict myCoords, int whichParamDeriv)
     974{
     975    float x = myCoords->data.F32[0];
    1027976    float tmp = 0.0;
    1028977
    1029     if ( whichParamDeriv == 0 ) {
     978    if (whichParamDeriv == 0) {
    1030979        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);
    1040987}
    1041988
     
    1049996decreasing within that range.
    1050997 *****************************************************************************/
    1051 float p_ps1DPolyMedian( psPolynomial1D *myPoly,
    1052                         float rangeLow,
    1053                         float rangeHigh,
    1054                         float getThisValue )
     998float p_ps1DPolyMedian(psPolynomial1D * myPoly, float rangeLow, float rangeHigh, float getThisValue)
    1055999{
    10561000    int numIterations = 0;
     
    10591003    float f = 0.0;
    10601004
    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);
    10671011        }
    10681012        oldMidpoint = midpoint;
    10691013
    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) {
    10771021            rangeHigh = midpoint;
    10781022        } else {
     
    10811025        numIterations++;
    10821026    }
    1083     return ( midpoint );
     1027    return (midpoint);
    10841028}
    10851029
     
    10921036XXX: This function is currently not being used.
    10931037 *****************************************************************************/
    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 ) );
     1038float 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));
    11321067    } 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);
    11421076}
    11431077
     
    11661100    NULL
    11671101*****************************************************************************/
    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;
     1102void p_psVectorRobustStats(const psVector * restrict myVector,
     1103                           const psVector * restrict maskVector, unsigned int maskVal, psStats * stats)
     1104{
     1105    psHistogram *robustHistogram = NULL;
    11741106    psVector *robustHistogramVector = NULL;
    1175     float binSize = 0.0;                        // Size of the histogram bins
    1176     int LQBinNum = -1;                          // Bin num for lower quartile
    1177     int UQBinNum = -1;                          // Bin num for upper quartile
    1178     int i = 0;                                  // Loop index variable
     1107    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
    11791111    int maxBinNum = 0;
    11801112    float maxBinCount = 0.0;
    11811113    float dL = 0.0;
    11821114    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;
    11921125    float myMean = 0.0;
    11931126    float myStdev = 0.0;
     
    11961129    float sumSquares = 0.0;
    11971130    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);
    12021135    psVector *cumulativeRobustSumsFullRange = NULL;
    12031136    psVector *cumulativeRobustSumsDlRange = NULL;
     
    12101143    // by computing the clipped standard deviation of the vector, and dividing
    12111144    // that by 10.0;
    1212     p_psVectorClippedStats( myVector, maskVector, maskVal, tmpStats );
     1145    p_psVectorClippedStats(myVector, maskVector, maskVal, tmpStats);
    12131146    binSize = tmpStats->clippedStdev / 10.0f;
    12141147
    12151148    // If stats->clippedStdev == 0.0, then all data elements have the same
    12161149    // 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) {
    12191152            stats->robustMean = stats->clippedMean;
    12201153        }
    1221         if ( stats->options & PS_STAT_ROBUST_MEDIAN ) {
     1154        if (stats->options & PS_STAT_ROBUST_MEDIAN) {
    12221155            stats->robustMedian = stats->clippedMean;
    12231156        }
    1224         if ( stats->options & PS_STAT_ROBUST_MODE ) {
     1157        if (stats->options & PS_STAT_ROBUST_MODE) {
    12251158            stats->robustMode = stats->clippedMean;
    12261159        }
    1227         if ( stats->options & PS_STAT_ROBUST_STDEV ) {
     1160        if (stats->options & PS_STAT_ROBUST_STDEV) {
    12281161            stats->robustStdev = 0.0;
    12291162        }
    1230         if ( stats->options & PS_STAT_ROBUST_QUARTILE ) {
     1163        if (stats->options & PS_STAT_ROBUST_QUARTILE) {
    12311164            stats->robustUQ = stats->clippedMean;
    12321165            stats->robustLQ = stats->clippedMean;
     
    12351168        stats->robustNfit = 0.0;
    12361169        stats->robustN50 = 0.0;
    1237         psFree( tmpStats );
    1238         return ;
    1239     }
    1240 
     1170        psFree(tmpStats);
     1171        return;
     1172    }
    12411173    // 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    }
    12491180    // Create the histogram structure.  NOTE: we can not specify the bin size
    12501181    // precisely since the argument to psHistogramAlloc() is the number of
    12511182    // bins, not the binSize.  Also, if we get here, we know that
    12521183    // 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);
    12571186
    12581187    // Populate the histogram array.
    1259     psVectorHistogram( robustHistogram, myVector, maskVector, maskVal );
     1188    psVectorHistogram(robustHistogram, myVector, maskVector, maskVal);
    12601189
    12611190    // Smooth the histogram.
    12621191    // 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);
    12651193
    12661194    // The following was necessary to fit a gaussian to the data, since
     
    12741202    // index position i is equal to the sum of bins 0:i.  This will be used
    12751203    // 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];
    12841211
    12851212    // Determine the bin number containing the lower quartile point.
    12861213    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)) {
    12891216            LQBinNum = i;
    12901217            break;
     
    12941221    // Determine the bin number containing the upper quartile point.
    12951222    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)) {
    12981225            UQBinNum = i;
    12991226            break;
     
    13011228    }
    13021229
    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
    13071234    /**************************************************************************
    13081235    Determine the mode in the range LQ:UQ.
     
    13101237    // Determine the bin with the peak value in the range LQ to UQ.
    13111238    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) {
    13161243            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];
    13201247    }
    13211248
    13221249    // 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);
    13261253
    13271254    /**************************************************************************
    13281255    Determine the mean/stdev for the bins in the range mode-dL to mode+dL
    13291256    **************************************************************************/
    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;
    13331260    }
    13341261    sumNfit = 0.0;
    13351262    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];
    13431269        }
    13441270    }
     
    13481274    // that bin (this is a non-exact approximation).
    13491275    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];
    13561281        }
    13571282    }
     
    13611286    // mode-dL to mode+dL.  We use the midpoint of each bin as the mean for
    13621287    // 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));
    13721297
    13731298    /**************************************************************************
    13741299    Set the appropriate members in the output stats struct.
    13751300    **************************************************************************/
    1376     if ( stats->options & PS_STAT_ROBUST_MEAN ) {
     1301    if (stats->options & PS_STAT_ROBUST_MEAN) {
    13771302        stats->robustMean = myMean;
    13781303    }
    13791304
    1380     if ( stats->options & PS_STAT_ROBUST_MODE ) {
     1305    if (stats->options & PS_STAT_ROBUST_MODE) {
    13811306        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) {
    13871311        stats->robustStdev = myStdev;
    13881312    }
    1389 
    13901313    // To determine the median (and later, the lower/upper quartile), we fit
    13911314    // a quadratic to the three bins surrounding the bin containing the median.
     
    13941317    // this bin.  We then solve the quadratic for
    13951318
    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];
    14111334
    14121335            // Ensure that cumulativeMedian/2 is actually within the range of the bins
    14131336            // we are using.
    14141337            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");
    14191341            }
    14201342            // XXX: yErr is not currently used by psVectorFitPolynomial1D().  We
    14211343            // 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;
    14251347
    14261348            // Determine the coefficients of the polynomial.
    1427             myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr );
     1349            myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr);
    14281350            // Call p_ps1DPolyMedian(), which does a binary search on the
    14291351            // polynomial, looking for the value x such that
    14301352            // 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);
    14331354        } else {
    14341355            // If the mode is the first/last histogram bin, then simply use
    14351356            // 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    }
    14411361    // The lower/upper quartile calculations are very similar to the median
    14421362    // calculations.  We fit a quadratic to the array containing the
     
    14441364    // f(x) equals the lower/upper quartile exactly.
    14451365    //
    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);
    14781394
    14791395        } else {
    14801396            // If the LQ is the first/last histogram bin, then simply use
    14811397            // 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);
    15151429        } else {
    15161430            // If the UQ is the first/last histogram bin, then simply use
    15171431            // 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]);
    15201434        }
    15211435    }
     
    15231437    stats->robustN50 = sumN50;
    15241438
    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}
    15361448
    15371449/*
     
    15821494*/
    15831495
    1584 
    15851496/*****************************************************************************/
     1497
    15861498/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     1499
    15871500/*****************************************************************************/
    15881501
    1589 static void histogramFree( psHistogram *myHist );
     1502static void histogramFree(psHistogram * myHist);
    15901503
    15911504/******************************************************************************
    15921505    psStatsAlloc(): This routine must create a new psStats data structure.
    15931506 *****************************************************************************/
    1594 psStats *psStatsAlloc( psStatsOptions options )
    1595 {
    1596     psStats * newStruct = NULL;
    1597 
    1598     newStruct = ( psStats * ) psAlloc( sizeof( psStats ) );
     1507psStats *psStatsAlloc(psStatsOptions options)
     1508{
     1509    psStats *newStruct = NULL;
     1510
     1511    newStruct = (psStats *) psAlloc(sizeof(psStats));
    15991512    newStruct->sampleMean = NAN;
    16001513    newStruct->sampleMedian = NAN;
     
    16201533    newStruct->options = options;
    16211534
    1622     return ( newStruct );
     1535    return (newStruct);
    16231536}
    16241537
     
    16351548    The histogram structure
    16361549 *****************************************************************************/
    1637 psHistogram *psHistogramAlloc( float lower,
    1638                                float upper,
    1639                                int n )
    1640 {
    1641     int i = 0;                          // Loop index variable
     1550psHistogram *psHistogramAlloc(float lower, float upper, int n)
     1551{
     1552    int i = 0;                  // Loop index variable
    16421553    psHistogram *newHist = NULL;        // The new histogram structure
    1643     float binSize = 0.0;                // The histogram bin size
     1554    float binSize = 0.0;        // The histogram bin size
    16441555
    16451556    // 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    }
    16531563    // 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    }
    16581567    // Allocate memory for the new histogram structure.  If there are N
    16591568    // 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);
    16631572    newHist->bounds->n = newHist->bounds->nalloc;
    16641573
    16651574    // Calculate the bounds for each bin.
    1666     binSize = ( upper - lower ) / ( float ) n;
    1667     // NOTE: Is the following necessary?  It prevents the max data point
     1575    binSize = (upper - lower) / (float)n;
     1576    // NOTE: Is the following necessary? It prevents the max data point
    16681577    // from being in a non-existant bin.
    16691578    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);
    16721581    }
    16731582
    16741583    // Allocate the bins, and initialize them to zero.
    1675     newHist->nums = psVectorAlloc( n, PS_TYPE_U32 );
     1584    newHist->nums = psVectorAlloc(n, PS_TYPE_U32);
    16761585    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;
    16791588    }
    16801589
     
    16841593    newHist->uniform = true;
    16851594
    1686     return ( newHist );
     1595    return (newHist);
    16871596}
    16881597
     
    16961605    The histogram structure
    16971606 *****************************************************************************/
    1698 psHistogram *psHistogramAllocGeneric( const psVector *restrict bounds )
    1699 {
    1700     psHistogram * newHist = NULL;        // The new histogram structure
    1701     int i;                              // Loop index variable
     1607psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds)
     1608{
     1609    psHistogram *newHist = NULL;        // The new histogram structure
     1610    int i;                      // Loop index variable
    17021611
    17031612    // NOTE: Verify that this is the correct action.
    1704     if ( bounds == NULL ) {
     1613    if (bounds == NULL) {
    17051614        // psAbort(__func__, "psHistogram requested with NULL bounds");
    1706         return ( NULL );
    1707     }
    1708 
     1615        return (NULL);
     1616    }
    17091617    // NOTE: Verify that this is the correct action.
    1710     if ( bounds->n <= 1 ) {
     1618    if (bounds->n <= 1) {
    17111619        // 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) {
    17161624        // psAbort(__func__, "psHistogram request a bound which is not type F32");
    1717         return ( NULL );
    1718     }
    1719 
     1625        return (NULL);
     1626    }
    17201627    // 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);
    17241631    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];
    17271634    }
    17281635
    17291636    // Allocate the bins, and initialize them to zero.  If there are N bounds,
    17301637    // 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);
    17321639    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;
    17351642    }
    17361643
     
    17401647    newHist->uniform = false;
    17411648
    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
     1652static void histogramFree(psHistogram * myHist)
     1653{
     1654    psFree(myHist->bounds);
     1655    psFree(myHist->nums);
     1656}
    17511657
    17521658/*****************************************************************************
     
    17641670    The histogram structure "out".
    17651671 *****************************************************************************/
    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
     1672psHistogram *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
    17761681
    17771682    // 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    }
    17821686    // 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    }
    17931694    // 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");
    18111709        }
    18121710    }
     
    18151713
    18161714    numBins = out->nums->n;
    1817     for ( i = 0;i < in->n;i++ ) {
     1715    for (i = 0; i < in->n; i++) {
    18181716        // 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)))) {
    18211718            // Check if this pixel is below the minimum value, and if so
    18221719            // 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]) {
    18241721                out->minNum++;
    18251722                // Check if this pixel is above the maximum value, and if so
    18261723                // 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.
    18301744                } 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])++;
    18571751                        }
    18581752                    }
    18591753                }
    1860         }
    1861     }
    1862     return ( out );
     1754            }
     1755        }
     1756    }
     1757    return (out);
    18631758}
    18641759
     
    18721767the various stat functions.
    18731768 *****************************************************************************/
    1874 psVector *p_psConvertToF32( psStats *stats,
    1875                             psVector *in,
    1876                             psVector *mask,
    1877                             unsigned int maskVal )
     1769psVector *p_psConvertToF32(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal)
    18781770{
    18791771    int i = 0;
    18801772    psVector *tmp = NULL;
    18811773
    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}
    19081796
    19091797/******************************************************************************
     
    19241812macro-ize everything and add PS_TYPE_U16 and PS_TYPE_F64.
    19251813 *****************************************************************************/
    1926 psStats *psVectorStats( psStats *stats,
    1927                         psVector *in,
    1928                         psVector *mask,
    1929                         unsigned int maskVal )
    1930 {
    1931     psVector * inF32;
     1814psStats *psVectorStats(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal)
     1815{
     1816    psVector *inF32;
    19321817    int mustFreeTmp = 1;
    19331818
    19341819    // 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) {
    19441829        inF32 = in;
    19451830        mustFreeTmp = 0;
    19461831    }
    1947 
    19481832    // 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    }
    19631843    // ************************************************************************
    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    }
    19681847    // ************************************************************************
    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    }
    19731851    // ************************************************************************
    19741852    // 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    }
    19811858    // ************************************************************************
    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    }
    19861862    // Since the various robust stats quantities share much computation, they
    19871863    // are grouped together in a single private function:
    19881864    // 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    }
    20021875    // ************************************************************************
    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    }
    20071879    // ************************************************************************
    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
    12/** @file  psStats.h
    23 *  \brief basic statistical operations
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    1617#if !defined(PS_STATS_H)
    17 #define PS_STATS_H
     18#    define PS_STATS_H
    1819
    19 #include "psVector.h"
     20#    include "psVector.h"
    2021
    2122/// @addtogroup Stats
     
    2627 *****************************************************************************/
    2728typedef 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     = 0x008000
     29    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
    4445} psStatsOptions;
    45 
    4646
    4747/** This is the generic statistics structure.  It contails the data members
     
    5050typedef struct
    5151{
    52     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
     52    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
    6464    double XXX;
    65     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
     65    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
    7575}
    7676psStats;
    7777
    78 
    7978/** 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              );
     79psStats *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                      );
    8686
    8787/** A constructor for the stats structure.*/
    88 psStats *psStatsAlloc(psStatsOptions options); ///< Statistics to measure
     88psStats *psStatsAlloc(psStatsOptions options);  // /< Statistics to measure
    8989
    9090/******************************************************************************
    9191    Histogram functions and data structures.
    9292 *****************************************************************************/
     93
    9394/** The basic histogram structure which contains bounds and bins. */
    9495typedef struct
    9596{
    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 minimum
    99     int maxNum;                      ///< Number above the maximum
    100     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?
    101102}
    102103psHistogram;
    103104
    104 
    105105/** 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 
     106psHistogram *psHistogramAlloc(float lower,      // /< Lower limit for the bins
     107                              float upper,      // /< Upper limit for the bins
     108                              int n);   // /< Number of bins
    111109
    112110/** Generic constructor \ingroup MathGroup */
    113 psHistogram * psHistogramAllocGeneric(const psVector *restrict bounds); ///< Bounds for the bins
     111psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds); // /< Bounds for the bins
    114112
    115113/** Calculate a histogram \ingroup MathGroup **/
    116 psHistogram *psVectorHistogram (psHistogram *out,   ///< Histogram data
    117                                 const psVector *restrict in,       ///< Vector to analyse
    118                                 const psVector *restrict mask,     ///< Mask dat for input vector
    119                                 unsigned int maskVal);       ///< Mask value
     114psHistogram *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
    120118
    121 bool p_psGetStatValue(
    122     const psStats* stats,
    123     double* value
    124 );
     119bool p_psGetStatValue(const psStats * stats, double *value);
    125120
    126121/// @}
    127122
    128123#endif
    129 
  • trunk/psLib/src/dataManip/psVectorFFT.c

    r1406 r1407  
     1
    12/** @file  psFFT.c
    23*
     
    56*  @author Robert DeSonia, MHPCC
    67*
    7 *  @version $Revision: 1.18 $ $Name: not supported by cvs2svn $
    8 *  @date $Date: 2004-08-06 22:34:05 $
     8*  @version $Revision: 1.19 $ $Name: not supported by cvs2svn $
     9*  @date $Date: 2004-08-07 00:06:06 $
    910*
    1011*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728static bool p_fftwWisdomImported = false;
    2829
    29 psImage* psImageFFT( psImage* out, const psImage* in, psFftDirection direction )
     30psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction)
    3031{
    3132    unsigned int numCols;
     
    3536
    3637    /* 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);
    6361        return NULL;
    6462    }
    6563
    6664    /* make sure the system-level wisdom information is imported. */
    67     if ( ! p_fftwWisdomImported ) {
     65    if (!p_fftwWisdomImported) {
    6866        fftwf_import_system_wisdom();
    6967        p_fftwWisdomImported = true;
     
    7371    numCols = in->numCols;
    7472
    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);
    8783        return NULL;
    8884    }
    8985
    9086    /* 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
     95psImage *psImageReal(psImage * out, const psImage * in)
    10196{
    10297    psElemType type;
     
    10499    unsigned int numRows;
    105100
    106 
    107     if ( in == NULL ) {
    108         psFree( out );
     101    if (in == NULL) {
     102        psFree(out);
    109103        return NULL;
    110104    }
     
    115109
    116110    /* 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)) {
    118112        // 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
     153psImage *psImageImaginary(psImage * out, const psImage * in)
    162154{
    163155    psElemType type;
     
    165157    unsigned int numRows;
    166158
    167 
    168     if ( in == NULL ) {
    169         psFree( out );
     159    if (in == NULL) {
     160        psFree(out);
    170161        return NULL;
    171162    }
     
    176167
    177168    /* 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)) {
    179170        // 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);
    184175        return out;
    185176    }
    186177
    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
     213psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag)
    225214{
    226215    psElemType type;
     
    228217    unsigned int numRows;
    229218
    230 
    231     if ( real == NULL || imag == NULL ) {
    232         psFree( out );
     219    if (real == NULL || imag == NULL) {
     220        psFree(out);
    233221        return NULL;
    234222    }
     
    238226    numRows = real->numRows;
    239227
    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
     292psImage *psImageConjugate(psImage * out, const psImage * in)
    308293{
    309294    psElemType type;
     
    311296    unsigned int numRows;
    312297
    313 
    314     if ( in == NULL ) {
    315         psFree( out );
     298    if (in == NULL) {
     299        psFree(out);
    316300        return NULL;
    317301    }
     
    322306
    323307    /* 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)) {
    325309        // 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
     350psImage *psImagePowerSpectrum(psImage * out, const psImage * in)
    369351{
    370352    psElemType type;
     
    373355    int numElementsSquared;
    374356
    375     if ( in == NULL ) {
    376         psFree( out );
     357    if (in == NULL) {
     358        psFree(out);
    377359        return NULL;
    378360    }
     
    384366
    385367    /* 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;
    395377        psF32 real;
    396378        psF32 imag;
    397379
    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    }
    435413
    436414    return out;
     
    440418/************************************** Vector Functions ***************************************/
    441419
    442 psVector* psVectorFFT( psVector* out, const psVector* in, psFftDirection direction )
     420psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction)
    443421{
    444422    unsigned int numElements;
     
    447425
    448426    /* 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);
    475450        return NULL;
    476451    }
    477452
    478453    /* make sure the system-level wisdom information is imported. */
    479     if ( ! p_fftwWisdomImported ) {
     454    if (!p_fftwWisdomImported) {
    480455        fftwf_import_system_wisdom();
    481456        p_fftwWisdomImported = true;
     
    484459    numElements = in->n;
    485460
    486     out = psVectorRecycle( out, numElements, PS_TYPE_C32 );
     461    out = psVectorRecycle(out, numElements, PS_TYPE_C32);
    487462    out->n = numElements;
    488463
    489     if ( type == PS_TYPE_F32 ) {
     464    if (type == PS_TYPE_F32) {
    490465        // 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);
    514489        return NULL;
    515490    }
    516491
    517492    /* 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
     500psVector *psVectorReal(psVector * out, const psVector * in)
    527501{
    528502    psElemType type;
    529503    unsigned int numElements;
    530504
    531     if ( in == NULL ) {
    532         psFree( out );
     505    if (in == NULL) {
     506        psFree(out);
    533507        return NULL;
    534508    }
     
    538512
    539513    /* 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)) {
    541515        // 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);
    545519        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));
    547521        return out;
    548522    }
    549523
    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);
    555529        out->n = numElements;
    556530        outVec = out->data.F32;
    557531
    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
     544psVector *psVectorImaginary(psVector * out, const psVector * in)
    572545{
    573546    psElemType type;
    574547    unsigned int numElements;
    575548
    576 
    577     if ( in == NULL ) {
    578         psFree( out );
     549    if (in == NULL) {
     550        psFree(out);
    579551        return NULL;
    580552    }
     
    584556
    585557    /* 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)) {
    587559        // 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);
    591563        out->n = numElements;
    592         memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements );
     564        memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements);
    593565        return out;
    594566    }
    595567
    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);
    601573        out->n = numElements;
    602574        outVec = out->data.F32;
    603575
    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
     588psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag)
    618589{
    619590    psElemType type;
    620591    unsigned int numElements;
    621592
    622 
    623     if ( real == NULL || imag == NULL ) {
    624         psFree( out );
     593    if (real == NULL || imag == NULL) {
     594        psFree(out);
    625595        return NULL;
    626596    }
    627597
    628598    type = real->type.type;
    629     if ( real->n < imag->n ) {
     599    if (real->n < imag->n) {
    630600        numElements = real->n;
    631601    } else {
     
    633603    }
    634604
    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);
    653623        out->n = numElements;
    654624        outVec = out->data.C32;
    655625
    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
     638psVector *psVectorConjugate(psVector * out, const psVector * in)
    670639{
    671640    psElemType type;
    672641    unsigned int numElements;
    673642
    674 
    675     if ( in == NULL ) {
    676         psFree( out );
     643    if (in == NULL) {
     644        psFree(out);
    677645        return NULL;
    678646    }
     
    682650
    683651    /* 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)) {
    685653        // 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);
    690658        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);
    692660        return out;
    693661    }
    694662
    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);
    700668        out->n = numElements;
    701669        outVec = out->data.C32;
    702670
    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
     683psVector *psVectorPowerSpectrum(psVector * out, const psVector * in)
    717684{
    718685    psElemType type;
     
    722689    unsigned int inNumElementsSquared;
    723690
    724     if ( in == NULL ) {
    725         psFree( out );
     691    if (in == NULL) {
     692        psFree(out);
    726693        return NULL;
    727694    }
     
    734701
    735702    /* 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;
    745712        psF32 inAbs1;
    746713        psF32 inAbs2;
    747714
    748         out = psVectorRecycle( out, outNumElements, PS_TYPE_F32 );
     715        out = psVectorRecycle(out, outNumElements, PS_TYPE_F32);
    749716        out->n = outNumElements;
    750717        outVec = out->data.F32;
    751718
    752719        // 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;
    755722
    756723        // 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;
    761728        }
    762729
    763730        // 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
    12/** @file  psFFT.h
    23 *
     
    78 *  @author Robert DeSonia, MHPCC
    89 *
    9  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1415
    1516#ifndef PS_FFT_H
    16 #define PS_FFT_H
     17#    define PS_FFT_H
    1718
    18 #include "psImage.h"
    19 #include "psVector.h"
     19#    include "psImage.h"
     20#    include "psVector.h"
    2021
    2122/// @addtogroup Transform
     
    2425/** Details on FFT implementation (private). */
    2526
    26 
    2727typedef enum {
    28     /// psImageFFT/psVectorFFT should perform a forward FFT.
     28    // / psImageFFT/psVectorFFT should perform a forward FFT.
    2929    PS_FFT_FORWARD = (-1),
    3030
    31     ///< psImageFFT/psVectorFFT should perform a reverse FFT.
     31    // /< psImageFFT/psVectorFFT should perform a reverse FFT.
    3232    PS_FFT_REVERSE = (+1)
    3333} psFftDirection;
    3434
    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);
     35psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction);
     36psImage *psImageReal(psImage * out, const psImage * in);
     37psImage *psImageImaginary(psImage * out, const psImage * in);
     38psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag);
     39psImage *psImageConjugate(psImage * out, const psImage * in);
     40psImage *psImagePowerSpectrum(psImage * out, const psImage * in);
    4141
    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);
     42psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction);
     43psVector *psVectorReal(psVector * out, const psVector * in);
     44psVector *psVectorImaginary(psVector * out, const psVector * in);
     45psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag);
     46psVector *psVectorConjugate(psVector * out, const psVector * in);
     47psVector *psVectorPowerSpectrum(psVector * out, const psVector * in);
    4848
    4949/// @}
    5050
    5151#endif
    52 
  • trunk/psLib/src/fft/psVectorFFT.c

    r1406 r1407  
     1
    12/** @file  psFFT.c
    23*
     
    56*  @author Robert DeSonia, MHPCC
    67*
    7 *  @version $Revision: 1.18 $ $Name: not supported by cvs2svn $
    8 *  @date $Date: 2004-08-06 22:34:05 $
     8*  @version $Revision: 1.19 $ $Name: not supported by cvs2svn $
     9*  @date $Date: 2004-08-07 00:06:06 $
    910*
    1011*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728static bool p_fftwWisdomImported = false;
    2829
    29 psImage* psImageFFT( psImage* out, const psImage* in, psFftDirection direction )
     30psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction)
    3031{
    3132    unsigned int numCols;
     
    3536
    3637    /* 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);
    6361        return NULL;
    6462    }
    6563
    6664    /* make sure the system-level wisdom information is imported. */
    67     if ( ! p_fftwWisdomImported ) {
     65    if (!p_fftwWisdomImported) {
    6866        fftwf_import_system_wisdom();
    6967        p_fftwWisdomImported = true;
     
    7371    numCols = in->numCols;
    7472
    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);
    8783        return NULL;
    8884    }
    8985
    9086    /* 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
     95psImage *psImageReal(psImage * out, const psImage * in)
    10196{
    10297    psElemType type;
     
    10499    unsigned int numRows;
    105100
    106 
    107     if ( in == NULL ) {
    108         psFree( out );
     101    if (in == NULL) {
     102        psFree(out);
    109103        return NULL;
    110104    }
     
    115109
    116110    /* 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)) {
    118112        // 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
     153psImage *psImageImaginary(psImage * out, const psImage * in)
    162154{
    163155    psElemType type;
     
    165157    unsigned int numRows;
    166158
    167 
    168     if ( in == NULL ) {
    169         psFree( out );
     159    if (in == NULL) {
     160        psFree(out);
    170161        return NULL;
    171162    }
     
    176167
    177168    /* 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)) {
    179170        // 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);
    184175        return out;
    185176    }
    186177
    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
     213psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag)
    225214{
    226215    psElemType type;
     
    228217    unsigned int numRows;
    229218
    230 
    231     if ( real == NULL || imag == NULL ) {
    232         psFree( out );
     219    if (real == NULL || imag == NULL) {
     220        psFree(out);
    233221        return NULL;
    234222    }
     
    238226    numRows = real->numRows;
    239227
    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
     292psImage *psImageConjugate(psImage * out, const psImage * in)
    308293{
    309294    psElemType type;
     
    311296    unsigned int numRows;
    312297
    313 
    314     if ( in == NULL ) {
    315         psFree( out );
     298    if (in == NULL) {
     299        psFree(out);
    316300        return NULL;
    317301    }
     
    322306
    323307    /* 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)) {
    325309        // 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
     350psImage *psImagePowerSpectrum(psImage * out, const psImage * in)
    369351{
    370352    psElemType type;
     
    373355    int numElementsSquared;
    374356
    375     if ( in == NULL ) {
    376         psFree( out );
     357    if (in == NULL) {
     358        psFree(out);
    377359        return NULL;
    378360    }
     
    384366
    385367    /* 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;
    395377        psF32 real;
    396378        psF32 imag;
    397379
    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    }
    435413
    436414    return out;
     
    440418/************************************** Vector Functions ***************************************/
    441419
    442 psVector* psVectorFFT( psVector* out, const psVector* in, psFftDirection direction )
     420psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction)
    443421{
    444422    unsigned int numElements;
     
    447425
    448426    /* 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);
    475450        return NULL;
    476451    }
    477452
    478453    /* make sure the system-level wisdom information is imported. */
    479     if ( ! p_fftwWisdomImported ) {
     454    if (!p_fftwWisdomImported) {
    480455        fftwf_import_system_wisdom();
    481456        p_fftwWisdomImported = true;
     
    484459    numElements = in->n;
    485460
    486     out = psVectorRecycle( out, numElements, PS_TYPE_C32 );
     461    out = psVectorRecycle(out, numElements, PS_TYPE_C32);
    487462    out->n = numElements;
    488463
    489     if ( type == PS_TYPE_F32 ) {
     464    if (type == PS_TYPE_F32) {
    490465        // 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);
    514489        return NULL;
    515490    }
    516491
    517492    /* 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
     500psVector *psVectorReal(psVector * out, const psVector * in)
    527501{
    528502    psElemType type;
    529503    unsigned int numElements;
    530504
    531     if ( in == NULL ) {
    532         psFree( out );
     505    if (in == NULL) {
     506        psFree(out);
    533507        return NULL;
    534508    }
     
    538512
    539513    /* 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)) {
    541515        // 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);
    545519        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));
    547521        return out;
    548522    }
    549523
    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);
    555529        out->n = numElements;
    556530        outVec = out->data.F32;
    557531
    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
     544psVector *psVectorImaginary(psVector * out, const psVector * in)
    572545{
    573546    psElemType type;
    574547    unsigned int numElements;
    575548
    576 
    577     if ( in == NULL ) {
    578         psFree( out );
     549    if (in == NULL) {
     550        psFree(out);
    579551        return NULL;
    580552    }
     
    584556
    585557    /* 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)) {
    587559        // 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);
    591563        out->n = numElements;
    592         memset( out->data.V, 0, PSELEMTYPE_SIZEOF( type ) * numElements );
     564        memset(out->data.V, 0, PSELEMTYPE_SIZEOF(type) * numElements);
    593565        return out;
    594566    }
    595567
    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);
    601573        out->n = numElements;
    602574        outVec = out->data.F32;
    603575
    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
     588psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag)
    618589{
    619590    psElemType type;
    620591    unsigned int numElements;
    621592
    622 
    623     if ( real == NULL || imag == NULL ) {
    624         psFree( out );
     593    if (real == NULL || imag == NULL) {
     594        psFree(out);
    625595        return NULL;
    626596    }
    627597
    628598    type = real->type.type;
    629     if ( real->n < imag->n ) {
     599    if (real->n < imag->n) {
    630600        numElements = real->n;
    631601    } else {
     
    633603    }
    634604
    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);
    653623        out->n = numElements;
    654624        outVec = out->data.C32;
    655625
    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
     638psVector *psVectorConjugate(psVector * out, const psVector * in)
    670639{
    671640    psElemType type;
    672641    unsigned int numElements;
    673642
    674 
    675     if ( in == NULL ) {
    676         psFree( out );
     643    if (in == NULL) {
     644        psFree(out);
    677645        return NULL;
    678646    }
     
    682650
    683651    /* 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)) {
    685653        // 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);
    690658        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);
    692660        return out;
    693661    }
    694662
    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);
    700668        out->n = numElements;
    701669        outVec = out->data.C32;
    702670
    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
     683psVector *psVectorPowerSpectrum(psVector * out, const psVector * in)
    717684{
    718685    psElemType type;
     
    722689    unsigned int inNumElementsSquared;
    723690
    724     if ( in == NULL ) {
    725         psFree( out );
     691    if (in == NULL) {
     692        psFree(out);
    726693        return NULL;
    727694    }
     
    734701
    735702    /* 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;
    745712        psF32 inAbs1;
    746713        psF32 inAbs2;
    747714
    748         out = psVectorRecycle( out, outNumElements, PS_TYPE_F32 );
     715        out = psVectorRecycle(out, outNumElements, PS_TYPE_F32);
    749716        out->n = outNumElements;
    750717        outVec = out->data.F32;
    751718
    752719        // 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;
    755722
    756723        // 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;
    761728        }
    762729
    763730        // 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
    12/** @file  psFFT.h
    23 *
     
    78 *  @author Robert DeSonia, MHPCC
    89 *
    9  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1415
    1516#ifndef PS_FFT_H
    16 #define PS_FFT_H
     17#    define PS_FFT_H
    1718
    18 #include "psImage.h"
    19 #include "psVector.h"
     19#    include "psImage.h"
     20#    include "psVector.h"
    2021
    2122/// @addtogroup Transform
     
    2425/** Details on FFT implementation (private). */
    2526
    26 
    2727typedef enum {
    28     /// psImageFFT/psVectorFFT should perform a forward FFT.
     28    // / psImageFFT/psVectorFFT should perform a forward FFT.
    2929    PS_FFT_FORWARD = (-1),
    3030
    31     ///< psImageFFT/psVectorFFT should perform a reverse FFT.
     31    // /< psImageFFT/psVectorFFT should perform a reverse FFT.
    3232    PS_FFT_REVERSE = (+1)
    3333} psFftDirection;
    3434
    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);
     35psImage *psImageFFT(psImage * out, const psImage * in, psFftDirection direction);
     36psImage *psImageReal(psImage * out, const psImage * in);
     37psImage *psImageImaginary(psImage * out, const psImage * in);
     38psImage *psImageComplex(psImage * out, psImage * real, const psImage * imag);
     39psImage *psImageConjugate(psImage * out, const psImage * in);
     40psImage *psImagePowerSpectrum(psImage * out, const psImage * in);
    4141
    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);
     42psVector *psVectorFFT(psVector * out, const psVector * in, psFftDirection direction);
     43psVector *psVectorReal(psVector * out, const psVector * in);
     44psVector *psVectorImaginary(psVector * out, const psVector * in);
     45psVector *psVectorComplex(psVector * out, psVector * real, const psVector * imag);
     46psVector *psVectorConjugate(psVector * out, const psVector * in);
     47psVector *psVectorPowerSpectrum(psVector * out, const psVector * in);
    4848
    4949/// @}
    5050
    5151#endif
    52 
  • trunk/psLib/src/image/psImage.c

    r1406 r1407  
     1
    12/** @file  psImage.c
    23 *
     
    910 *  @author Ross Harman, MHPCC
    1011 *
    11  *  @version $Revision: 1.37 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.38 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225
     
    2932#include "psImage.h"
    3033
    31 static void imageFree(psImage* image);
     34static void imageFree(psImage * image);
    3235
    3336/*****************************************************************************/
     37
    3438/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     39
    3540/*****************************************************************************/
    3641
    37 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows,
    38                       const psElemType type)
     42psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, const psElemType type)
    3943{
    4044    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;
    4556
    4657    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);
    4960        return NULL;
    5061    }
    5162
    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     if(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;
    8091    image->parent = NULL;
    8192    image->nChildren = 0;
     
    8596}
    8697
    87 static void imageFree(psImage* image)
     98static void imageFree(psImage * image)
    8899{
    89100    if (image == NULL) {
     
    92103
    93104    if (image->type.type == PS_TYPE_PTR) {
    94         // 2-D array of pointers -- must dereference
     105        // 2-D array of pointers -- must
     106        // dereference
    95107        unsigned int oldNumRows = image->numRows;
    96108        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++) {
    100112            rowPtr = image->data.PTR[row];
    101             for (unsigned int col=0;col<oldNumCols;col++) {
     113            for (unsigned int col = 0; col < oldNumCols; col++) {
    102114                psMemDecrRefCounter(rowPtr[col]);
    103115            }
     
    112124}
    113125
    114 psImage* psImageRecycle(psImage* old,
    115                         unsigned int numCols,
    116                         unsigned int numRows,
    117                         const psElemType type)
     126psImage *psImageRecycle(psImage * old, unsigned int numCols, unsigned int numRows, const psElemType type)
    118127{
    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.
    121137
    122138    if (old == NULL) {
    123         old = psImageAlloc(numCols,numRows,type);
     139        old = psImageAlloc(numCols, numRows, type);
    124140        return old;
    125141    }
    126142
    127143    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.");
    129145        return NULL;
    130146    }
    131147
    132148    if (old->type.type == PS_TYPE_PTR) {
    133         // 2-D array of pointers -- must dereference
     149        // 2-D array of pointers -- must
     150        // dereference
    134151        unsigned int oldNumRows = old->numRows;
    135152        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++) {
    139156            rowPtr = old->data.PTR[row];
    140             for (unsigned int col=0;col<oldNumCols;col++) {
     157            for (unsigned int col = 0; col < oldNumCols; col++) {
    141158                psMemDecrRefCounter(rowPtr[col]);
    142159                rowPtr[col] = NULL;
     
    146163
    147164    /* 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) {
    150166        return old;
    151167    }
    152 
    153168    // 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 *));
    156171
    157172    // 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;
    165180
    166181    return old;
    167182}
    168183
    169 int psImageFreeChildren(psImage* image)
     184int psImageFreeChildren(psImage * image)
    170185{
    171186    int i = 0;
     
    181196    children = image->children;
    182197
    183     for(i=0; i<nChildren; i++) {
     198    for (i = 0; i < nChildren; i++) {
    184199        if (children[i] != NULL) {
    185200            numFreed++;
     
    191206    image->nChildren = 0;
    192207    image->children = NULL;
    193 
    194208
    195209    return numFreed;
     
    202216linear interpolation is performed on the image.
    203217 *****************************************************************************/
    204 psF32 psImagePixelInterpolate(
    205     const psImage *input,
    206     float x,
    207     float y,
    208     psF32 unexposedValue,
    209     psImageInterpolateMode mode)
     218psF32 psImagePixelInterpolate(const psImage * input,
     219                              float x, float y, psF32 unexposedValue, psImageInterpolateMode mode)
    210220{
    211221
    212222    if (input == NULL) {
    213         psError(__func__,"Image can not be NULL.");
     223        psError(__func__, "Image can not be NULL.");
    214224        return unexposedValue;
    215225    }
    216 
    217226    #define PSIMAGE_PIXEL_INTERPOLATE_CASE(TYPE) \
    218227case PS_TYPE_##TYPE: \
     
    243252        PSIMAGE_PIXEL_INTERPOLATE_CASE(C64);
    244253    default:
    245         psError(__func__,"Unsupported image datatype (%d)",input->type.type);
     254        psError(__func__, "Unsupported image datatype (%d)", input->type.type);
    246255    }
    247256
     
    303312PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C32)
    304313PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C64)
    305 
    306314#define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR(TYPE) \
    307315inline psF64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \
     
    359367    return(pixel); \
    360368}
    361 
    362369#define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(TYPE) \
    363370inline psC64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \
     
    428435PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C32)
    429436PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C64)
    430 
    431 
  • trunk/psLib/src/image/psImage.h

    r1406 r1407  
     1
    12/** @file  psImage.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.27 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.28 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1718 */
    18 # ifndef PS_IMAGE_H
    19 # define PS_IMAGE_H
     19#ifndef PS_IMAGE_H
     20#    define PS_IMAGE_H
    2021
    21 #include <complex.h>
     22#    include <complex.h>
    2223
    23 #include "psType.h"
     24#    include "psType.h"
    2425
    2526/// @addtogroup Image
     
    3940typedef struct psImage
    4041{
    41     const psType type;                  ///< Image data type and dimension.
    42     const unsigned int numCols;         ///< Number of columns in image
    43     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.
    4647
    4748    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.
    6667}
    6768psImage;
    6869
    6970/*****************************************************************************/
     71
    7072/* FUNCTION PROTOTYPES                                                       */
     73
    7174/*****************************************************************************/
    72 
    7375
    7476/** Create an image of the specified size and type.
     
    8082 *
    8183 */
    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 );
     84psImage *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                     );
    8788
    8889/** Resize a given image to the given size/type.
     
    9192 *
    9293 */
    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 
     94psImage *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                       );
    10099
    101100/** Frees all children of a psImage.
     
    104103 *
    105104 */
    106 int psImageFreeChildren(
    107     psImage* image
    108     /**< psImage in which all children shall be deallocated */
    109 );
     105int psImageFreeChildren(psImage * image
    110106
    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                       );
    118109
    119 #define p_psImagePixelInterpolateFcns(TYPE) \
     110psF32 psImagePixelInterpolate(const psImage * input,
     111                              float x, float y, psF32 unexposedValue, psImageInterpolateMode mode);
     112
     113#    define p_psImagePixelInterpolateFcns(TYPE) \
    120114inline psF64 p_psImagePixelInterpolateFLAT_##TYPE( \
    121115        const psImage *input, \
     
    131125                                                     );
    132126
    133 #define p_psImagePixelInterpolateComplexFcns(TYPE) \
     127#    define p_psImagePixelInterpolateComplexFcns(TYPE) \
    134128inline psC64 p_psImagePixelInterpolateFLAT_##TYPE( \
    135129        const psImage *input, \
     
    157151p_psImagePixelInterpolateComplexFcns(C32)
    158152p_psImagePixelInterpolateComplexFcns(C64)
    159 
    160153/// @}
    161 
    162154#endif
  • trunk/psLib/src/image/psImageExtraction.c

    r1406 r1407  
     1
    12/** @file  psImageExtraction.c
    23*
     
    910*  @author Robert DeSonia, MHPCC
    1011*
    11 *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-06 22:34:05 $
     12*  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2223#include "psError.h"
    2324
    24 psImage *psImageSubset( psImage *out, psImage *image, unsigned int numCols,
    25                         unsigned int numRows, unsigned int col0,
    26                         unsigned int row0 )
     25psImage *psImageSubset(psImage * out,
     26                       psImage * image,
     27                       unsigned int numCols, unsigned int numRows, unsigned int col0, unsigned int row0)
    2728{
    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);
    5165        return NULL;
    5266    }
    5367
    5468    /* 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.
    7389    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;
    7792
    7893    inputColOffset = elementSize * col0;
    7994    outputRowSize = elementSize * numCols;
    8095
    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);
    87101}
    88102
    89 
    90 psImage *psImageCopy( psImage* restrict output, const psImage *input,
    91                       psElemType type )
     103psImage *psImageCopy(psImage * restrict output, const psImage * input, psElemType type)
    92104{
    93105    psElemType inDatatype;
     
    97109    int numCols;
    98110
    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);
    115128        return NULL;
    116129    }
     
    120133    numCols = input->numCols;
    121134    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);
    135149        return output;
    136150    }
    137 
    138151    #define PSIMAGE_ELEMENT_COPY(IN,INTYPE,OUT,OUTTYPE,ELEMENTS) { \
    139152        ps##INTYPE *in = IN->data.INTYPE[0]; \
     
    186199    }
    187200
    188     switch ( type ) {
     201    switch (type) {
    189202    case PS_TYPE_S8:
    190         PSIMAGE_COPY_CASE( output, S8 );
     203        PSIMAGE_COPY_CASE(output, S8);
    191204        break;
    192205    case PS_TYPE_S16:
    193         PSIMAGE_COPY_CASE( output, S16 );
     206        PSIMAGE_COPY_CASE(output, S16);
    194207        break;
    195208    case PS_TYPE_S32:
    196         PSIMAGE_COPY_CASE( output, S32 );
     209        PSIMAGE_COPY_CASE(output, S32);
    197210        break;
    198211    case PS_TYPE_S64:
    199         PSIMAGE_COPY_CASE( output, S64 );
     212        PSIMAGE_COPY_CASE(output, S64);
    200213        break;
    201214    case PS_TYPE_U8:
    202         PSIMAGE_COPY_CASE( output, U8 );
     215        PSIMAGE_COPY_CASE(output, U8);
    203216        break;
    204217    case PS_TYPE_U16:
    205         PSIMAGE_COPY_CASE( output, U16 );
     218        PSIMAGE_COPY_CASE(output, U16);
    206219        break;
    207220    case PS_TYPE_U32:
    208         PSIMAGE_COPY_CASE( output, U32 );
     221        PSIMAGE_COPY_CASE(output, U32);
    209222        break;
    210223    case PS_TYPE_U64:
    211         PSIMAGE_COPY_CASE( output, U64 );
     224        PSIMAGE_COPY_CASE(output, U64);
    212225        break;
    213226    case PS_TYPE_F32:
    214         PSIMAGE_COPY_CASE( output, F32 );
     227        PSIMAGE_COPY_CASE(output, F32);
    215228        break;
    216229    case PS_TYPE_F64:
    217         PSIMAGE_COPY_CASE( output, F64 );
     230        PSIMAGE_COPY_CASE(output, F64);
    218231        break;
    219232    case PS_TYPE_C32:
    220         PSIMAGE_COPY_CASE( output, C32 );
     233        PSIMAGE_COPY_CASE(output, C32);
    221234        break;
    222235    case PS_TYPE_C64:
    223         PSIMAGE_COPY_CASE( output, C64 );
     236        PSIMAGE_COPY_CASE(output, C64);
    224237        break;
    225238    default:
     
    229242}
    230243
    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 )
     244psVector *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)
    242253{
    243254    double statVal;
    244     psStats* myStats;
     255    psStats *myStats;
    245256    psElemType type;
    246257    int inRows;
    247258    int inCols;
    248259    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);
    261271        return NULL;
    262272    }
     
    266276    inCols = in->numCols;
    267277
    268     if ( direction == PS_CUT_X_NEG || direction == PS_CUT_Y_NEG ) {
     278    if (direction == PS_CUT_X_NEG || direction == PS_CUT_Y_NEG) {
    269279        delta = -1;
    270280    }
    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) {
    275286        numRows = -numRows;
    276         row -= ( numRows - 1 );
     287        row -= (numRows - 1);
    277288        delta = -delta;
    278289    }
    279290
    280     if ( numCols < 0 ) {
     291    if (numCols < 0) {
    281292        numCols = -numCols;
    282         col -= ( numCols - 1 );
     293        col -= (numCols - 1);
    283294        delta = -delta;
    284295    }
    285296
    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 a single stats operation
    308     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 to create a 'scratch' stats struct
    315     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));
    316327    *myStats = *stats;
    317328
    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);
    329341        if (slicePositions != NULL) {
    330             slicePositions = psVectorRecycle(slicePositions,numCols,PS_TYPE_U32);
     342            slicePositions = psVectorRecycle(slicePositions, numCols, PS_TYPE_U32);
    331343            outPosition = slicePositions->data.U32;
    332344        }
    333345        outData = out->data.F64;
    334         if ( delta < 0 ) {
     346        if (delta < 0) {
    335347            outData += numCols - 1;
    336348            if (outPosition != NULL) {
     
    339351        }
    340352
    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        }
    345356        #define PSIMAGE_CUT_VERTICAL(TYPE) \
    346357    case PS_TYPE_##TYPE: { \
     
    373384        }
    374385
    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);
    388399        default:
    389             psError( __func__, "Unsupported datatype (%d)", type );
    390             psFree( out );
     400            psError(__func__, "Unsupported datatype (%d)", type);
     401            psFree(out);
    391402            out = NULL;
    392403        }
    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;
    410449            }
    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));
    418458            }
    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
    425471            }
    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);
    452489
    453490    return out;
    454491}
    455 
  • trunk/psLib/src/image/psImageExtraction.h

    r1404 r1407  
     1
    12/** @file  psImageExtraction.h
    23*
     
    910*  @author Robert DeSonia, MHPCC
    1011*
    11 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-06 21:50:13 $
     12*  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1617
    1718#ifndef PSIMAGEEXTRACTION_H
    18 #define PSIMAGEEXTRACTION_H
     19#    define PSIMAGEEXTRACTION_H
    1920
    20 #include "psImage.h"
    21 #include "psVector.h"
    22 #include "psStats.h"
     21#    include "psImage.h"
     22#    include "psVector.h"
     23#    include "psStats.h"
    2324
    2425/// @addtogroup Image
     
    4041*
    4142*/
    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 );
     43psImage *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                      );
    5050
    5151/** Makes a copy of a psImage
     
    5555 *
    5656 */
    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 );
     57psImage *psImageCopy(psImage * restrict output,
    6758
    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,
    8163
    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
    9466
    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
     70psVector *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
     80psVector *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
     87psVector *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);
    10592
    10693/// @}
  • trunk/psLib/src/image/psImageIO.c

    r1406 r1407  
     1
    12/** @file  psImageIO.c
    23 *
     
    78 *  @author Robert DeSonia, MHPCC
    89 *
    9  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2122#include "psMemory.h"
    2223
    23 psImage* psImageReadSection(psImage* output, int col, int row, int numCols,
    24                             int numRows, int z, char* extname, int extnum, char* filename)
     24psImage *psImageReadSection(psImage * output,
     25                            int col,
     26                            int row,
     27                            int numCols, int numRows, int z, char *extname, int extnum, char *filename)
    2528{
    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;
    3942
    4043    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.");
    4245        psFree(output);
    4346        return NULL;
     
    4750    (void)fits_open_file(&fptr, filename, READONLY, &status);
    4851    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);
    5254        psFree(output);
    5355        return NULL;
     
    5658    /* find the specified extension */
    5759    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) {
    5961            fits_get_errstatus(status, fitsErr);
    6062            status = 0;
    6163            (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);
    6465            psFree(output);
    6566            return NULL;
    6667        }
    6768    } else {
    68         if (fits_movabs_hdu(fptr, extnum+1, &hduType, &status) != 0) {
     69        if (fits_movabs_hdu(fptr, extnum + 1, &hduType, &status) != 0) {
    6970            fits_get_errstatus(status, fitsErr);
    7071            status = 0;
    7172            (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);
    7474            psFree(output);
    7575            return NULL;
     
    8282        status = 0;
    8383        (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);
    8685        psFree(output);
    8786        return NULL;
     
    9392        status = 0;
    9493        (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);
    9795        psFree(output);
    9896        return NULL;
     
    10098
    10199    /* 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) {
    113110        (void)fits_get_errstatus(status, fitsErr);
    114111        status = 0;
    115112        (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);
    118114        psFree(output);
    119115        return NULL;
     
    127123    }
    128124
    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;
    132128
    133129    lastPixel[0] = firstPixel[0] + numCols - 1;
    134130    lastPixel[1] = firstPixel[1] + numRows - 1;
    135     lastPixel[2] = z+1;
     131    lastPixel[2] = z + 1;
    136132
    137133    increment[0] = 1;
     
    139135    increment[2] = 1;
    140136
    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);
    143141
    144142    switch (bitPix) {
     
    180178        break;
    181179    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) {
    190188        psFree(output);
    191189        (void)fits_get_errstatus(status, fitsErr);
    192190        status = 0;
    193191        (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);
    196193        return NULL;
    197194    }
     
    202199}
    203200
    204 
    205 bool psImageWriteSection(psImage* input, int col0,int row0,int z,
    206                          char* extname, int extnum, char* filename)
     201bool psImageWriteSection(psImage * input, int col0, int row0, int z, char *extname, int extnum,
     202                         char *filename)
    207203{
    208     int         numCols = 0;
    209     int         numRows = 0;
    210 
    211     int         status=0;               /* CFITSIO status */
    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;
    223219
    224220    /* 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);
    228223        return false;
    229224    }
     
    244239    case PS_TYPE_U16:
    245240        bitPix = SHORT_IMG;
    246         bzero = -1.0f*INT16_MIN;
     241        bzero = -1.0f * INT16_MIN;
    247242        datatype = TUSHORT;
    248243        break;
     
    253248    case PS_TYPE_U32:
    254249        bitPix = LONG_IMG;
    255         bzero = -1.0f*INT32_MIN;
     250        bzero = -1.0f * INT32_MIN;
    256251        datatype = TUINT;
    257252        break;
     
    269264        break;
    270265    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);
    273268        return false;
    274269    }
    275270
    276271    /* Open the FITS file */
    277     if (access(filename, F_OK) == 0) { // file exists
     272    if (access(filename, F_OK) == 0) {     // file
     273        // exists
    278274        (void)fits_open_file(&fptr, filename, READWRITE, &status);
    279275        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);
    283278            return false;
    284279        }
     
    286281        /* find the specified extension */
    287282        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) {
    289284                fits_get_errstatus(status, fitsErr);
    290285                status = 0;
    291286                (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);
    294289                return false;
    295290            }
    296291        } else {
    297292            int numHDUs = 0;
    298             fits_get_num_hdus(fptr,&numHDUs,&status);
     293
     294            fits_get_num_hdus(fptr, &numHDUs, &status);
    299295            if (numHDUs < extnum) {
    300296                status = 0;
    301297                (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);
    304300                return false;
    305             } else
    306                 if (numHDUs == extnum) {
    307                     createNewHDU = true;
    308                 } else
    309                     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 not exist
    320 
    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);
    322318        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);
    326321            return false;
    327322        }
     
    330325
    331326    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;
    336331        if (fits_create_img(fptr, bitPix, 3, nAxes, &status) != 0) {
    337332            (void)fits_get_errstatus(status, fitsErr);
    338333            status = 0;
    339334            (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);
    342336            return false;
    343337        }
    344 
    345338        // 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);
    349342
    350343        if (extname != NULL) {
     
    354347                status = 0;
    355348                (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);
    358351                return false;
    359352            }
     
    361354    }
    362355
    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;
    366359
    367360    lastPixel[0] = firstPixel[0] + numCols - 1;
    368361    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) {
    372365        (void)fits_get_errstatus(status, fitsErr);
    373366        status = 0;
    374367        (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);
    377369        return false;
    378370    }
  • trunk/psLib/src/image/psImageIO.h

    r1241 r1407  
     1
    12/** @file  psImageIO.h
    23 *
     
    910 *  @author Robert DeSonia, MHPCC
    1011 *
    11  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-07-19 22:01:19 $
     12 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    16 # ifndef PS_IMAGEIO_H
    17 # define PS_IMAGEIO_H
     17#ifndef PS_IMAGEIO_H
     18#    define PS_IMAGEIO_H
    1819
    19 #include <stdbool.h>
     20#    include <stdbool.h>
    2021
    21 #include "psImage.h"
     22#    include "psImage.h"
    2223
    2324/// @addtogroup ImageIO
     
    2930 *                          signifies that a problem had occured.
    3031 */
    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 );
     32psImage *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                           );
    5564
    5665/** Read an image or subimage from a FITS file specified by a filename.
     
    5867 *  return bool         TRUE is successful, otherwise FALSE.
    5968 */
    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 );
     69bool 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                        );
    8095
    8196/// @}
  • trunk/psLib/src/image/psImageManip.c

    r1406 r1407  
     1
    12/** @file  psImageManip.c
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617 */
    17 #include <math.h>                      // for isfinite(), etc.
     18#include <math.h>                          // for
     19// isfinite(),
     20// etc.
    1821#include <stdlib.h>
    1922#include <stdbool.h>
    20 #include <string.h>                    // for memcpy, etc.
     23#include <string.h>                        // for
     24// memcpy,
     25// etc.
    2126
    2227#include "psError.h"
     
    2631#include "psImageExtraction.h"
    2732
    28 int psImageClip(psImage* input, psF64 min, psF64 vmin, psF64 max, psF64 vmax)
     33int psImageClip(psImage * input, psF64 min, psF64 vmin, psF64 max, psF64 vmax)
    2934{
    3035    int numClipped = 0;
     
    3742
    3843    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.");
    4045        return 0;
    4146    }
     
    100105        break;
    101106
    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)
    114119
    115120    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);
    118122    }
    119123
     
    121125}
    122126
    123 int psImageClipNaN(psImage* input,psF64 value)
     127int psImageClipNaN(psImage * input, psF64 value)
    124128{
    125129    int numClipped = 0;
     
    154158
    155159    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);
    158161    }
    159162
     
    161164}
    162165
    163 int psImageOverlaySection(psImage* image, const psImage* overlay, int col0,
    164                           int row0, const char* op)
     166int psImageOverlaySection(psImage * image, const psImage * overlay, int col0, int row0, const char *op)
    165167{
    166168    unsigned int imageNumRows;
     
    170172    unsigned int imageRowLimit;
    171173    unsigned int imageColLimit;
    172     psElemType  type;
     174    psElemType type;
    173175
    174176    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.");
    176178        return 1;
    177179    }
    178180
    179181    if (op == NULL) {
    180         psError(__func__,"Operation can not be NULL.");
     182        psError(__func__, "Operation can not be NULL.");
    181183        return 1;
    182184    }
     
    185187
    186188    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);
    189190        return 2;
    190191    }
     
    197198    /* check row0/col0 to see if it is within the image size */
    198199    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).",
    200202                col0, row0, imageNumCols, imageNumRows);
    201203        return 3;
     
    203205
    204206    /* check if overlay is totally withing input image */
    205     imageRowLimit = row0+overlayNumRows;
    206     imageColLimit = col0+overlayNumCols;
     207    imageRowLimit = row0 + overlayNumRows;
     208    imageColLimit = col0 + overlayNumCols;
    207209    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"
    209212                " 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);
    212214        return 4;
    213215    }
     
    259261
    260262    default:
    261         psError(__func__,"Can not operate on type %d.",type);
     263        psError(__func__, "Can not operate on type %d.", type);
    262264    }
    263265
     
    265267}
    266268
    267 int psImageClipComplexRegion(psImage* input, psC64 min, psC64 vmin, psC64 max, psC64 vmax)
     269int psImageClipComplexRegion(psImage * input, psC64 min, psC64 vmin, psC64 max, psC64 vmax)
    268270{
    269271    int numClipped = 0;
     
    276278
    277279    if (input == NULL) {
    278         psError(__func__,"Can not perform clip on NULL image");
     280        psError(__func__, "Can not perform clip on NULL image");
    279281        return 0;
    280282    }
    281283
    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.");
    285287        return 0;
    286288    }
    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 "
    289292                "max < min in the imaginary image space.");
    290293        return 0;
     
    294297    numCols = input->numCols;
    295298
     299    #define psImageClipComplexRegionCase(type,typename,realfcn,imagfcn) \
     300case 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
    296330    switch (input->type.type) {
    297331
    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)
    331334
    332335    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);
    335337    }
    336338
     
    338340}
    339341
    340 
    341 psImage* psImageRebin(psImage* out,const psImage* in,unsigned int scale,const psStats* stats)
     342psImage *psImageRebin(psImage * out, const psImage * in, unsigned int scale, const psStats * stats)
    342343{
    343344    int inRows;
     
    345346    int outRows;
    346347    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;
    349353    double statVal;
    350354
    351355    if (in == NULL) {
    352         psError(__func__,"Input image is NULL.");
     356        psError(__func__, "Input image is NULL.");
    353357        psFree(out);
    354358        return NULL;
     
    356360
    357361    if (scale < 1) {
    358         psError(__func__,"The scale must be positive.");
     362        psError(__func__, "The scale must be positive.");
    359363        psFree(out);
    360364        return NULL;
     
    362366
    363367    if (stats == NULL) {
    364         psError(__func__,"The stats input can not be NULL.");
     368        psError(__func__, "The stats input can not be NULL.");
    365369        psFree(out);
    366370        return NULL;
    367371    }
    368372
    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.");
    371375        psFree(out);
    372376        return NULL;
     
    376380    *myStats = *stats;
    377381
    378     vec = psVectorAlloc(scale*scale,in->type.type);
     382    vec = psVectorAlloc(scale * scale, in->type.type);
    379383
    380384    // create output image.
    381385    inRows = in->numRows;
    382386    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);
    386394
    387395    #define PS_IMAGE_REBIN_CASE(type) \
     
    425433        PS_IMAGE_REBIN_CASE(C64);
    426434    default:
    427         psError(__func__,"Input image type not supported.");
     435        psError(__func__, "Input image type not supported.");
    428436        psFree(out);
    429437        out = NULL;
     
    435443    return out;
    436444}
    437 psImage* psImageResample(psImage* out, const psImage* in, int scale, psImageInterpolateMode mode)
     445
     446psImage *psImageResample(psImage * out, const psImage * in, int scale, psImageInterpolateMode mode)
    438447{
    439448    int outRows;
     
    442451
    443452    if (in == NULL) {
    444         psError(__func__,"Input image can not be NULL.");
     453        psError(__func__, "Input image can not be NULL.");
    445454        psFree(out);
    446455        return NULL;
    447456    }
    448 
    449     // create an output image of the same size and type
    450     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;
    452461    invScale = 1.0f / (float)scale;
    453 
    454462
    455463    #define PSIMAGE_RESAMPLE_CASE(TYPE) \
     
    466474    }
    467475
    468     switch(in->type.type) {
     476    switch (in->type.type) {
    469477        PSIMAGE_RESAMPLE_CASE(U8)
    470478        PSIMAGE_RESAMPLE_CASE(U16)
     
    480488        PSIMAGE_RESAMPLE_CASE(C64)
    481489    default:
    482         psError(__func__,"Unsupported type (%d)",in->type.type);
     490        psError(__func__, "Unsupported type (%d)", in->type.type);
    483491        psFree(out);
    484492        return NULL;
     
    488496}
    489497
    490 psImage* psImageRoll(psImage* out, const psImage* in, int dx, int dy)
     498psImage *psImageRoll(psImage * out, const psImage * in, int dx, int dy)
    491499{
    492500    int outRows;
     
    495503
    496504    if (in == NULL) {
    497         psError(__func__,"Input image can not be NULL.");
     505        psError(__func__, "Input image can not be NULL.");
    498506        psFree(out);
    499507        return NULL;
    500508    }
    501 
    502     // create an output image of the same size and type
     509    // create an output image of the same size
     510    // and type
    503511    outRows = in->numRows;
    504512    outCols = in->numCols;
    505513    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
    509518    dx = dx % outCols;
    510519    dy = dy % outRows;
     
    516525    }
    517526
    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
    523533        if (inRowNumber >= outRows) {
    524534            inRowNumber -= outRows;
    525535        }
    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);
    530548    }
    531549
     
    533551}
    534552
    535 psImage* psImageRotate(psImage* out, const psImage* in, float angle, float unexposedValue, psImageInterpolateMode mode)
     553psImage *psImageRotate(psImage * out,
     554                       const psImage * in, float angle, float unexposedValue, psImageInterpolateMode mode)
    536555{
    537556    if (in == NULL) {
    538         psError(__func__,"The input image was NULL.");
     557        psError(__func__, "The input image was NULL.");
    539558        psFree(out);
    540559        return NULL;
    541560    }
    542 
    543561    // 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) {
    547565        // perform 1/4 rotate counter-clockwise
    548566        int numRows = in->numCols;
     
    550568        int lastCol = numCols - 1;
    551569        psElemType type = in->type.type;
    552         out = psImageRecycle(out,numCols,numRows,type);
     570
     571        out = psImageRecycle(out, numCols, numRows, type);
    553572
    554573        #define PSIMAGE_ROTATE_LEFT_90(TYPE) \
     
    578597            PSIMAGE_ROTATE_LEFT_90(C64);
    579598        default:
    580             psError(__func__,"Unsupported type (%d)",type);
     599            psError(__func__, "Unsupported type (%d)", type);
    581600            psFree(out);
    582601            return NULL;
    583602        }
    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    }
    788801
    789802    return out;
    790803}
    791804
    792 psImage* psImageShift(psImage* out, const psImage* in, float dx, float dy, psF64 unexposedValue, psImageInterpolateMode mode)
     805psImage *psImageShift(psImage * out,
     806                      const psImage * in,
     807                      float dx, float dy, psF64 unexposedValue, psImageInterpolateMode mode)
    793808{
    794809    int outRows;
     
    798813
    799814    if (in == NULL) {
    800         psError(__func__,"Input image can not be NULL.");
     815        psError(__func__, "Input image can not be NULL.");
    801816        return NULL;
    802817    }
    803 
    804     // create an output image of the same size and type
     818    // create an output image of the same size
     819    // and type
    805820    outRows = in->numRows;
    806821    outCols = in->numCols;
    807822    type = in->type.type;
    808823    elementSize = PSELEMTYPE_SIZEOF(type);
    809     out = psImageRecycle(out,outCols, outRows, type);
     824    out = psImageRecycle(out, outCols, outRows, type);
    810825
    811826    #define PSIMAGE_SHIFT_CASE(TYPE) \
     
    842857        PSIMAGE_SHIFT_CASE(C64);
    843858    default:
    844         psError(__func__,"Image type (%d) not supported.",type);
     859        psError(__func__, "Image type (%d) not supported.", type);
    845860        psFree(out);
    846861        out = NULL;
  • trunk/psLib/src/image/psImageManip.h

    r1263 r1407  
     1
    12/** @file  psImageManip.h
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-07-22 20:42:22 $
     13 *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617 */
    1718#ifndef PS_IMAGE_MANIP_H
    18 #define PS_IMAGE_MANIP_H
     19#    define PS_IMAGE_MANIP_H
    1920
    20 #include "psImage.h"
     21#    include "psImage.h"
    2122
    2223/// @addtogroup Image
     
    3132 *  @return int     The number of clipped pixels
    3233 */
    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 );
     34int 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               );
    4040
    4141/** Clip image values outside of a specified complex region
     
    4848 *  @return int     The number of clipped pixels
    4949 */
    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 );
     50int 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                            );
    5756
    5857/** Clip NaN image pixels to given value.
     
    6362 *  @return int     The number of clipped pixels
    6463 */
    65 int psImageClipNaN(
    66     psImage* input,                 ///< the image to clip
    67     psF64 value                     ///< the value to set all NaN/Inf values to
    68 );
     64int psImageClipNaN(psImage * input,     // /< the image to clip
     65                   psF64 value  // /< the value to set all NaN/Inf values to
     66                  );
    6967
    7068/** Overlay subregion of image with another image
     
    7977 *  @return int         0 if success, non-zero if failed.
    8078 */
    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 );
     79int 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                         );
    8885
    8986/** Rebin image to new scale.
     
    9794 *  @return psImage    new image formed by rebinning input image.
    9895 */
    99 psImage* psImageRebin(
    100     psImage* out,                   ///< an psImage to recycle.  If NULL, a new image is created
    101     const psImage* in,              ///< input image
    102     unsigned int scale,             ///< the scale to rebin for each dimension
    103     const psStats* stats            ///< the statistic to perform when rebinning.  Only one method should be set.
    104 );
     96psImage *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                     );
    105102
    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 );
     103psImage *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);
    112106
    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 );
     107psImage *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);
    120110
    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 );
     111psImage *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);
    129114
    130115/** Roll image by an integer number of pixels in either direction.
     
    136121 *  @return psImage*    the rolled version of the input image.
    137122 */
    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 );
     123psImage *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                    );
    144128
    145129#endif
    146 
  • trunk/psLib/src/image/psImageStats.c

    r1406 r1407  
     1
    12/** @file psImageStats.c
    23*  \brief Routines for calculating statistics on images.
     
    910*  @author George Gusciora, MHPCC
    1011*
    11 *  @version $Revision: 1.29 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-06 22:34:05 $
     12*  @version $Revision: 1.30 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    3233
    3334/// This routine must determine the various statistics for the image.
     35
    3436/*****************************************************************************
    3537    NOTE: verify that image/mask have the correct types, and sizes.
    3638 *****************************************************************************/
    37 psStats *psImageStats(psStats *stats,
    38                       psImage *in,
    39                       psImage *mask,
    40                       int maskVal)
    41 {
    42     psVector* junkData=NULL;
    43     psVector* junkMask=NULL;
     39psStats *psImageStats(psStats * stats, psImage * in, psImage * mask, int maskVal)
     40{
     41    psVector *junkData = NULL;
     42    psVector *junkMask = NULL;
    4443
    4544    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.");
    4746        return NULL;
    4847    }
    4948
    5049    if (in == NULL) {
    51         psError(__func__,"The input image can not be NULL.");
     50        psError(__func__, "The input image can not be NULL.");
    5251        return NULL;
    5352    }
    5453
    5554    if (stats->options == 0) {
    56         psError(__func__,"No statistic option/operation was specified.");
     55        psError(__func__, "No statistic option/operation was specified.");
    5756        return stats;
    5857    }
    59 
    60     // stuff the image data into a psVector struct.
     58    // stuff the image data into a psVector
     59    // struct.
    6160    junkData = psAlloc(sizeof(psVector));
    6261    junkData->type = in->type;
    63     junkData->nalloc = in->numRows*in->numCols;
     62    junkData->nalloc = in->numRows * in->numCols;
    6463    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...
    6669
    6770    if (mask != NULL) {
    6871        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);
    7173            psFree(junkData);
    7274            return NULL;
    7375        }
    74 
    75         // stuff the mask data into a psVector struct.
     76        // stuff the mask data into a psVector
     77        // struct.
    7678        junkMask = psAlloc(sizeof(psVector));
    7779        junkMask->type = mask->type;
    78         junkMask->nalloc = mask->numRows*mask->numCols;
     80        junkMask->nalloc = mask->numRows * mask->numCols;
    7981        junkMask->n = junkMask->nalloc;
    8082        junkMask->data.V = mask->data.V[0];
     
    8587    psFree(junkMask);
    8688    psFree(junkData);
    87     return(stats);
     89    return (stats);
    8890}
    8991
     
    9395    NOTE: verify that image/mask have the, correct types and  sizes.
    9496 *****************************************************************************/
    95 psHistogram *psImageHistogram(psHistogram *out,
    96                               psImage *in,
    97                               psImage *mask,
    98                               unsigned int maskVal)
    99 {
    100     psVector *junkData=NULL;
    101     psVector *junkMask=NULL;
     97psHistogram *psImageHistogram(psHistogram * out, psImage * in, psImage * mask, unsigned int maskVal)
     98{
     99    psVector *junkData = NULL;
     100    psVector *junkMask = NULL;
    102101
    103102    // NOTE: Verify this action.
    104     if ((out == NULL) ||
    105             (in == NULL)) {
    106         return(NULL);
     103    if ((out == NULL) || (in == NULL)) {
     104        return (NULL);
    107105    }
    108106
    109107    junkData = psAlloc(sizeof(psVector));
    110108    junkData->type = in->type;
    111     junkData->nalloc = in->numRows*in->numCols;
     109    junkData->nalloc = in->numRows * in->numCols;
    112110    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...
    114116
    115117    if (mask != NULL) {
    116118        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);
    119120            psFree(junkData);
    120121            return NULL;
    121122        }
    122 
    123         // stuff the mask data into a psVector struct.
     123        // stuff the mask data into a psVector
     124        // struct.
    124125        junkMask = psAlloc(sizeof(psVector));
    125126        junkMask->type = mask->type;
    126         junkMask->nalloc = mask->numRows*mask->numCols;
     127        junkMask->nalloc = mask->numRows * mask->numCols;
    127128        junkMask->n = junkMask->nalloc;
    128129        junkMask->data.V = mask->data.V[0];
     
    134135    psFree(junkData);
    135136
    136     return(out);
     137    return (out);
    137138}
    138139
     
    141142    int i = 0;
    142143    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);
    150152        scalingFactors[i] = cos(tmp);
    151153    }
    152154
    153     return(scalingFactors);
     155    return (scalingFactors);
    154156}
    155157
     
    165167    int i = 0;
    166168    float tmp = 0.0;
     169
    167170    return p_psCalcScaleFactorsFit(n);
    168171
    169172    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);
    175180        scalingFactors[i] = cos(tmp);
    176181    }
    177     return(scalingFactors);
     182    return (scalingFactors);
    178183}
    179184
     
    184189    int j = 0;
    185190
    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.
    193198    chebPolys[0]->coeff[0] = 1;
    194199    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}
    207211
    208212/*****************************************************************************
     
    220224        over all pixels (x,y) in the image.
    221225 *****************************************************************************/
    222 psPolynomial2D *
    223 psImageFitPolynomial(const psImage *input,
    224                      psPolynomial2D *coeffs)
     226psPolynomial2D *psImageFitPolynomial(const psImage * input, psPolynomial2D * coeffs)
    225227{
    226228    int x = 0;
     
    235237    float tmp = 0.0;
    236238
    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
    245251    rScalingFactors = p_psCalcScaleFactorsFit(input->numRows);
    246252    cScalingFactors = p_psCalcScaleFactorsFit(input->numCols);
    247253
    248     // Determine how many Chebyshev polynomials are needed, then create them.
     254    // Determine how many Chebyshev polynomials
     255    // are needed, then create them.
    249256    maxChebyPoly = coeffs->nX;
    250257    if (coeffs->nY > coeffs->nX) {
     
    254261
    255262    // 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++) {
    258265            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]);
    262270
    263271            }
    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);
    265274        }
    266275    }
    267276
    268277    // 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++) {
    271280            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]);
    277288                }
    278289            }
     
    280291    }
    281292
    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++) {
    284295            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);
    286297
    287298            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 were created 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++) {
    300311        psFree(chebPolys[i]);
    301312    }
     
    303314
    304315    // Free some data
    305     for (i=0;i<coeffs->nX;i++) {
     316    for (i = 0; i < coeffs->nX; i++) {
    306317        psFree(sums[i]);
    307318    }
     
    310321    psFree(rScalingFactors);
    311322
    312     return(coeffs);
     323    return (coeffs);
    313324}
    314325
     
    316327 
    317328 *****************************************************************************/
    318 int
    319 psImageEvalPolynomial(const psImage *input,
    320                       const psPolynomial2D *coeffs)
     329int psImageEvalPolynomial(const psImage * input, const psPolynomial2D * coeffs)
    321330{
    322331    int x = 0;
     
    331340    float polySum = 0.0;
    332341
    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++) {
    341353            sums[i][j] = 0.0;
    342354        }
    343355    }
    344356
    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
    346359    rScalingFactors = p_psCalcScaleFactorsEval(input->numRows);
    347360    cScalingFactors = p_psCalcScaleFactorsEval(input->numCols);
    348361
    349     // Determine how many Chebyshev polynomials are needed, then create them.
     362    // Determine how many Chebyshev polynomials
     363    // are needed, then create them.
    350364    maxChebyPoly = coeffs->nX;
    351365    if (coeffs->nY > coeffs->nX) {
     
    355369    chebPolys = p_psCreateChebyshevPolys(maxChebyPoly);
    356370
    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++) {
    359373            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];
    365381
    366382                }
     
    370386    }
    371387
    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++) {
    374391        psFree(chebPolys[i]);
    375392    }
     
    377394
    378395    // Free some data
    379     for (i=0;i<coeffs->nX;i++) {
     396    for (i = 0; i < coeffs->nX; i++) {
    380397        psFree(sums[i]);
    381398    }
     
    384401    psFree(rScalingFactors);
    385402
    386     return(0);
    387 }
     403    return (0);
     404}
  • trunk/psLib/src/image/psImageStats.h

    r1374 r1407  
     1
    12/** @file psImageStats.h
    23*  \brief Routines for calculating statistics on images.
     
    910*  @author George Gusciora, MHPCC
    1011*
    11 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-04 00:55:17 $
     12*  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516*/
    1617#if !defined(PS_IMAGE_STATS_H)
    17 #define PS_IMAGE_STATS_H
     18#    define PS_IMAGE_STATS_H
    1819
    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"
    2525
    2626/// @addtogroup ImageStats
     
    2828
    2929/// 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                                
     30psStats *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
     35psHistogram *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
    4140/// 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 in desired terms & target
    45                     );
    46                    
     41psPolynomial2D *psImageFitPolynomial(const psImage * input,     // /< image to fit
     42                                     psPolynomial2D * coeffs    // /< coefficient structure carries in
     43                                     // desired terms & target
     44                                    );
     45
    4746/// 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                      
     47int psImageEvalPolynomial(const psImage * input,        // /< image to fit
     48                          const psPolynomial2D * coeffs // /< coefficient structure carries in desired terms
     49                         );
     50
    5351/// @}
    5452
  • trunk/psLib/src/imageops/psImageStats.c

    r1406 r1407  
     1
    12/** @file psImageStats.c
    23*  \brief Routines for calculating statistics on images.
     
    910*  @author George Gusciora, MHPCC
    1011*
    11 *  @version $Revision: 1.29 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-06 22:34:05 $
     12*  @version $Revision: 1.30 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    3233
    3334/// This routine must determine the various statistics for the image.
     35
    3436/*****************************************************************************
    3537    NOTE: verify that image/mask have the correct types, and sizes.
    3638 *****************************************************************************/
    37 psStats *psImageStats(psStats *stats,
    38                       psImage *in,
    39                       psImage *mask,
    40                       int maskVal)
    41 {
    42     psVector* junkData=NULL;
    43     psVector* junkMask=NULL;
     39psStats *psImageStats(psStats * stats, psImage * in, psImage * mask, int maskVal)
     40{
     41    psVector *junkData = NULL;
     42    psVector *junkMask = NULL;
    4443
    4544    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.");
    4746        return NULL;
    4847    }
    4948
    5049    if (in == NULL) {
    51         psError(__func__,"The input image can not be NULL.");
     50        psError(__func__, "The input image can not be NULL.");
    5251        return NULL;
    5352    }
    5453
    5554    if (stats->options == 0) {
    56         psError(__func__,"No statistic option/operation was specified.");
     55        psError(__func__, "No statistic option/operation was specified.");
    5756        return stats;
    5857    }
    59 
    60     // stuff the image data into a psVector struct.
     58    // stuff the image data into a psVector
     59    // struct.
    6160    junkData = psAlloc(sizeof(psVector));
    6261    junkData->type = in->type;
    63     junkData->nalloc = in->numRows*in->numCols;
     62    junkData->nalloc = in->numRows * in->numCols;
    6463    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...
    6669
    6770    if (mask != NULL) {
    6871        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);
    7173            psFree(junkData);
    7274            return NULL;
    7375        }
    74 
    75         // stuff the mask data into a psVector struct.
     76        // stuff the mask data into a psVector
     77        // struct.
    7678        junkMask = psAlloc(sizeof(psVector));
    7779        junkMask->type = mask->type;
    78         junkMask->nalloc = mask->numRows*mask->numCols;
     80        junkMask->nalloc = mask->numRows * mask->numCols;
    7981        junkMask->n = junkMask->nalloc;
    8082        junkMask->data.V = mask->data.V[0];
     
    8587    psFree(junkMask);
    8688    psFree(junkData);
    87     return(stats);
     89    return (stats);
    8890}
    8991
     
    9395    NOTE: verify that image/mask have the, correct types and  sizes.
    9496 *****************************************************************************/
    95 psHistogram *psImageHistogram(psHistogram *out,
    96                               psImage *in,
    97                               psImage *mask,
    98                               unsigned int maskVal)
    99 {
    100     psVector *junkData=NULL;
    101     psVector *junkMask=NULL;
     97psHistogram *psImageHistogram(psHistogram * out, psImage * in, psImage * mask, unsigned int maskVal)
     98{
     99    psVector *junkData = NULL;
     100    psVector *junkMask = NULL;
    102101
    103102    // NOTE: Verify this action.
    104     if ((out == NULL) ||
    105             (in == NULL)) {
    106         return(NULL);
     103    if ((out == NULL) || (in == NULL)) {
     104        return (NULL);
    107105    }
    108106
    109107    junkData = psAlloc(sizeof(psVector));
    110108    junkData->type = in->type;
    111     junkData->nalloc = in->numRows*in->numCols;
     109    junkData->nalloc = in->numRows * in->numCols;
    112110    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...
    114116
    115117    if (mask != NULL) {
    116118        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);
    119120            psFree(junkData);
    120121            return NULL;
    121122        }
    122 
    123         // stuff the mask data into a psVector struct.
     123        // stuff the mask data into a psVector
     124        // struct.
    124125        junkMask = psAlloc(sizeof(psVector));
    125126        junkMask->type = mask->type;
    126         junkMask->nalloc = mask->numRows*mask->numCols;
     127        junkMask->nalloc = mask->numRows * mask->numCols;
    127128        junkMask->n = junkMask->nalloc;
    128129        junkMask->data.V = mask->data.V[0];
     
    134135    psFree(junkData);
    135136
    136     return(out);
     137    return (out);
    137138}
    138139
     
    141142    int i = 0;
    142143    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);
    150152        scalingFactors[i] = cos(tmp);
    151153    }
    152154
    153     return(scalingFactors);
     155    return (scalingFactors);
    154156}
    155157
     
    165167    int i = 0;
    166168    float tmp = 0.0;
     169
    167170    return p_psCalcScaleFactorsFit(n);
    168171
    169172    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);
    175180        scalingFactors[i] = cos(tmp);
    176181    }
    177     return(scalingFactors);
     182    return (scalingFactors);
    178183}
    179184
     
    184189    int j = 0;
    185190
    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.
    193198    chebPolys[0]->coeff[0] = 1;
    194199    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}
    207211
    208212/*****************************************************************************
     
    220224        over all pixels (x,y) in the image.
    221225 *****************************************************************************/
    222 psPolynomial2D *
    223 psImageFitPolynomial(const psImage *input,
    224                      psPolynomial2D *coeffs)
     226psPolynomial2D *psImageFitPolynomial(const psImage * input, psPolynomial2D * coeffs)
    225227{
    226228    int x = 0;
     
    235237    float tmp = 0.0;
    236238
    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
    245251    rScalingFactors = p_psCalcScaleFactorsFit(input->numRows);
    246252    cScalingFactors = p_psCalcScaleFactorsFit(input->numCols);
    247253
    248     // Determine how many Chebyshev polynomials are needed, then create them.
     254    // Determine how many Chebyshev polynomials
     255    // are needed, then create them.
    249256    maxChebyPoly = coeffs->nX;
    250257    if (coeffs->nY > coeffs->nX) {
     
    254261
    255262    // 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++) {
    258265            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]);
    262270
    263271            }
    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);
    265274        }
    266275    }
    267276
    268277    // 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++) {
    271280            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]);
    277288                }
    278289            }
     
    280291    }
    281292
    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++) {
    284295            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);
    286297
    287298            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 were created 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++) {
    300311        psFree(chebPolys[i]);
    301312    }
     
    303314
    304315    // Free some data
    305     for (i=0;i<coeffs->nX;i++) {
     316    for (i = 0; i < coeffs->nX; i++) {
    306317        psFree(sums[i]);
    307318    }
     
    310321    psFree(rScalingFactors);
    311322
    312     return(coeffs);
     323    return (coeffs);
    313324}
    314325
     
    316327 
    317328 *****************************************************************************/
    318 int
    319 psImageEvalPolynomial(const psImage *input,
    320                       const psPolynomial2D *coeffs)
     329int psImageEvalPolynomial(const psImage * input, const psPolynomial2D * coeffs)
    321330{
    322331    int x = 0;
     
    331340    float polySum = 0.0;
    332341
    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++) {
    341353            sums[i][j] = 0.0;
    342354        }
    343355    }
    344356
    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
    346359    rScalingFactors = p_psCalcScaleFactorsEval(input->numRows);
    347360    cScalingFactors = p_psCalcScaleFactorsEval(input->numCols);
    348361
    349     // Determine how many Chebyshev polynomials are needed, then create them.
     362    // Determine how many Chebyshev polynomials
     363    // are needed, then create them.
    350364    maxChebyPoly = coeffs->nX;
    351365    if (coeffs->nY > coeffs->nX) {
     
    355369    chebPolys = p_psCreateChebyshevPolys(maxChebyPoly);
    356370
    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++) {
    359373            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];
    365381
    366382                }
     
    370386    }
    371387
    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++) {
    374391        psFree(chebPolys[i]);
    375392    }
     
    377394
    378395    // Free some data
    379     for (i=0;i<coeffs->nX;i++) {
     396    for (i = 0; i < coeffs->nX; i++) {
    380397        psFree(sums[i]);
    381398    }
     
    384401    psFree(rScalingFactors);
    385402
    386     return(0);
    387 }
     403    return (0);
     404}
  • trunk/psLib/src/imageops/psImageStats.h

    r1374 r1407  
     1
    12/** @file psImageStats.h
    23*  \brief Routines for calculating statistics on images.
     
    910*  @author George Gusciora, MHPCC
    1011*
    11 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
    12 *  @date $Date: 2004-08-04 00:55:17 $
     12*  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
     13*  @date $Date: 2004-08-07 00:06:06 $
    1314*
    1415*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516*/
    1617#if !defined(PS_IMAGE_STATS_H)
    17 #define PS_IMAGE_STATS_H
     18#    define PS_IMAGE_STATS_H
    1819
    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"
    2525
    2626/// @addtogroup ImageStats
     
    2828
    2929/// 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                                
     30psStats *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
     35psHistogram *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
    4140/// 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 in desired terms & target
    45                     );
    46                    
     41psPolynomial2D *psImageFitPolynomial(const psImage * input,     // /< image to fit
     42                                     psPolynomial2D * coeffs    // /< coefficient structure carries in
     43                                     // desired terms & target
     44                                    );
     45
    4746/// 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                      
     47int psImageEvalPolynomial(const psImage * input,        // /< image to fit
     48                          const psPolynomial2D * coeffs // /< coefficient structure carries in desired terms
     49                         );
     50
    5351/// @}
    5452
  • trunk/psLib/src/math/psCompare.c

    r1393 r1407  
     1
    12/** @file psCompare.c
    23 *  @brief Comparison functions for sorting routines
     
    67 *  @author Robert Daniel DeSonia, MHPCC
    78 *
    8  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2004-08-05 19:38:52 $
     9 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
     10 *  @date $Date: 2004-08-07 00:06:06 $
    1011 *
    1112 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
  • trunk/psLib/src/math/psCompare.h

    r1111 r1407  
    11#if !defined(PS_COMPARE_H)
    2 #define PS_COMPARE_H
     2#    define PS_COMPARE_H
    33
    44/** @file psCompare.h
     
    99 *  @ingroup Compare
    1010 *
    11  *  @version $Revision: 1.1 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-06-28 20:36:37 $
     11 *  @version $Revision: 1.2 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1313 *
    1414 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2626 *                   than, equal to, or greater than the second.
    2727 */
    28 typedef int (*psComparePtrFcn)(const void** a, const void** b);
     28typedef int (*psComparePtrFcn) (const void **a, const void **b);
    2929
    3030/** A comparison function for sorting.
     
    3434 *                   than, equal to, or greater than the second.
    3535 */
    36 typedef int (*psCompareFcn)(const void* a, const void* b);
     36typedef int (*psCompareFcn) (const void *a, const void *b);
    3737
    3838/** Compare function of psS8 data.  For use with psListSort.
     
    4242 *                   than, equal to, or greater than the second.
    4343 */
    44 int psCompareS8Ptr(const void** a, const void** b);
     44int psCompareS8Ptr(const void **a, const void **b);
    4545
    4646/** Compare function of psS16 data.  For use with psListSort.
     
    5050 *                   than, equal to, or greater than the second.
    5151 */
    52 int psCompareS16Ptr(const void** a, const void** b);
     52int psCompareS16Ptr(const void **a, const void **b);
    5353
    5454/** Compare function of psS32 data.  For use with psListSort.
     
    5858 *                   than, equal to, or greater than the second.
    5959 */
    60 int psCompareS32Ptr(const void** a, const void** b);
     60int psCompareS32Ptr(const void **a, const void **b);
    6161
    6262/** Compare function of psS64 data.  For use with psListSort.
     
    6666 *                   than, equal to, or greater than the second.
    6767 */
    68 int psCompareS64Ptr(const void** a, const void** b);
     68int psCompareS64Ptr(const void **a, const void **b);
    6969
    7070/** Compare function of psU8 data.  For use with psListSort.
     
    7474 *                   than, equal to, or greater than the second.
    7575 */
    76 int psCompareU8Ptr(const void** a, const void** b);
     76int psCompareU8Ptr(const void **a, const void **b);
    7777
    7878/** Compare function of psU16 data.  For use with psListSort.
     
    8282 *                   than, equal to, or greater than the second.
    8383 */
    84 int psCompareU16Ptr(const void** a, const void** b);
     84int psCompareU16Ptr(const void **a, const void **b);
    8585
    8686/** Compare function of psU32 data.  For use with psListSort.
     
    9090 *                   than, equal to, or greater than the second.
    9191 */
    92 int psCompareU32Ptr(const void** a, const void** b);
     92int psCompareU32Ptr(const void **a, const void **b);
    9393
    9494/** Compare function of psU64 data.  For use with psListSort.
     
    9898 *                   than, equal to, or greater than the second.
    9999 */
    100 int psCompareU64Ptr(const void** a, const void** b);
     100int psCompareU64Ptr(const void **a, const void **b);
    101101
    102102/** Compare function of psF32 data.  For use with psListSort.
     
    106106 *                   than, equal to, or greater than the second.
    107107 */
    108 int psCompareF32Ptr(const void** a, const void** b);
     108int psCompareF32Ptr(const void **a, const void **b);
    109109
    110110/** Compare function of psF64 data.  For use with psListSort.
     
    114114 *                   than, equal to, or greater than the second.
    115115 */
    116 int psCompareF64Ptr(const void** a, const void** b);
     116int psCompareF64Ptr(const void **a, const void **b);
    117117
    118118/** Compare function of psS8 data.  For use with psListSort for descending ordering.
     
    122122 *                   than, equal to, or less than the second.
    123123 */
    124 int psCompareDescendingS8Ptr(const void** a, const void** b);
     124int psCompareDescendingS8Ptr(const void **a, const void **b);
    125125
    126126/** Compare function of psS16 data.  For use with psListSort for descending ordering.
     
    130130 *                   than, equal to, or less than the second.
    131131 */
    132 int psCompareDescendingS16Ptr(const void** a, const void** b);
     132int psCompareDescendingS16Ptr(const void **a, const void **b);
    133133
    134134/** Compare function of psS32 data.  For use with psListSort for descending ordering.
     
    138138 *                   than, equal to, or less than the second.
    139139 */
    140 int psCompareDescendingS32Ptr(const void** a, const void** b);
     140int psCompareDescendingS32Ptr(const void **a, const void **b);
    141141
    142142/** Compare function of psS64 data.  For use with psListSort for descending ordering.
     
    146146 *                   than, equal to, or less than the second.
    147147 */
    148 int psCompareDescendingS64Ptr(const void** a, const void** b);
     148int psCompareDescendingS64Ptr(const void **a, const void **b);
    149149
    150150/** Compare function of psU8 data.  For use with psListSort for descending ordering.
     
    154154 *                   than, equal to, or less than the second.
    155155 */
    156 int psCompareDescendingU8Ptr(const void** a, const void** b);
     156int psCompareDescendingU8Ptr(const void **a, const void **b);
    157157
    158158/** Compare function of psU16 data.  For use with psListSort for descending ordering.
     
    162162 *                   than, equal to, or less than the second.
    163163 */
    164 int psCompareDescendingU16Ptr(const void** a, const void** b);
     164int psCompareDescendingU16Ptr(const void **a, const void **b);
    165165
    166166/** Compare function of psU32 data.  For use with psListSort for descending ordering.
     
    170170 *                   than, equal to, or lessg than the second.
    171171 */
    172 int psCompareDescendingU32Ptr(const void** a, const void** b);
     172int psCompareDescendingU32Ptr(const void **a, const void **b);
    173173
    174174/** Compare function of psU64 data.  For use with psListSort for descending ordering.
     
    178178 *                   than, equal to, or lessg than the second.
    179179 */
    180 int psCompareDescendingU64Ptr(const void** a, const void** b);
     180int psCompareDescendingU64Ptr(const void **a, const void **b);
    181181
    182182/** Compare function of psF32 data.  For use with psListSort for descending ordering.
     
    186186 *                   than, equal to, or lessg than the second.
    187187 */
    188 int psCompareDescendingF32Ptr(const void** a, const void** b);
     188int psCompareDescendingF32Ptr(const void **a, const void **b);
    189189
    190190/** Compare function of psF64 data.  For use with psListSort for descending ordering.
     
    194194 *                   than, equal to, or lessg than the second.
    195195 */
    196 int psCompareDescendingF64Ptr(const void** a, const void** b);
     196int psCompareDescendingF64Ptr(const void **a, const void **b);
    197197
    198198/** Compare function of psS8 data.
     
    202202 *                   than, equal to, or greater than the second.
    203203 */
    204 int psCompareS8(const void* a, const void* b);
     204int psCompareS8(const void *a, const void *b);
    205205
    206206/** Compare function of psS16 data.
     
    210210 *                   than, equal to, or greater than the second.
    211211 */
    212 int psCompareS16(const void* a, const void* b);
     212int psCompareS16(const void *a, const void *b);
    213213
    214214/** Compare function of psS32 data.
     
    218218 *                   than, equal to, or greater than the second.
    219219 */
    220 int psCompareS32(const void* a, const void* b);
     220int psCompareS32(const void *a, const void *b);
    221221
    222222/** Compare function of psS64 data.
     
    226226 *                   than, equal to, or greater than the second.
    227227 */
    228 int psCompareS64(const void* a, const void* b);
     228int psCompareS64(const void *a, const void *b);
    229229
    230230/** Compare function of psU8 data.
     
    234234 *                   than, equal to, or greater than the second.
    235235 */
    236 int psCompareU8(const void* a, const void* b);
     236int psCompareU8(const void *a, const void *b);
    237237
    238238/** Compare function of psU16 data.
     
    242242 *                   than, equal to, or greater than the second.
    243243 */
    244 int psCompareU16(const void* a, const void* b);
     244int psCompareU16(const void *a, const void *b);
    245245
    246246/** Compare function of psU32 data.
     
    250250 *                   than, equal to, or greater than the second.
    251251 */
    252 int psCompareU32(const void* a, const void* b);
     252int psCompareU32(const void *a, const void *b);
    253253
    254254/** Compare function of psU64 data.
     
    258258 *                   than, equal to, or greater than the second.
    259259 */
    260 int psCompareU64(const void* a, const void* b);
     260int psCompareU64(const void *a, const void *b);
    261261
    262262/** Compare function of psF32 data.
     
    266266 *                   than, equal to, or greater than the second.
    267267 */
    268 int psCompareF32(const void* a, const void* b);
     268int psCompareF32(const void *a, const void *b);
    269269
    270270/** Compare function of psF64 data.
     
    274274 *                   than, equal to, or greater than the second.
    275275 */
    276 int psCompareF64(const void* a, const void* b);
     276int psCompareF64(const void *a, const void *b);
    277277
    278278/** Compare function of psS8 data.
     
    282282 *                   than, equal to, or less than the second.
    283283 */
    284 int psCompareDescendingS8(const void* a, const void* b);
     284int psCompareDescendingS8(const void *a, const void *b);
    285285
    286286/** Compare function of psS16 data.
     
    290290 *                   than, equal to, or less than the second.
    291291 */
    292 int psCompareDescendingS16(const void* a, const void* b);
     292int psCompareDescendingS16(const void *a, const void *b);
    293293
    294294/** Compare function of psS32 data.
     
    298298 *                   than, equal to, or less than the second.
    299299 */
    300 int psCompareDescendingS32(const void* a, const void* b);
     300int psCompareDescendingS32(const void *a, const void *b);
    301301
    302302/** Compare function of psS64 data.
     
    306306 *                   than, equal to, or less than the second.
    307307 */
    308 int psCompareDescendingS64(const void* a, const void* b);
     308int psCompareDescendingS64(const void *a, const void *b);
    309309
    310310/** Compare function of psU8 data.
     
    314314 *                   than, equal to, or less than the second.
    315315 */
    316 int psCompareDescendingU8(const void* a, const void* b);
     316int psCompareDescendingU8(const void *a, const void *b);
    317317
    318318/** Compare function of psU16 data.
     
    322322 *                   than, equal to, or less than the second.
    323323 */
    324 int psCompareDescendingU16(const void* a, const void* b);
     324int psCompareDescendingU16(const void *a, const void *b);
    325325
    326326/** Compare function of psU32 data.
     
    330330 *                   than, equal to, or lessg than the second.
    331331 */
    332 int psCompareDescendingU32(const void* a, const void* b);
     332int psCompareDescendingU32(const void *a, const void *b);
    333333
    334334/** Compare function of psU64 data.
     
    338338 *                   than, equal to, or lessg than the second.
    339339 */
    340 int psCompareDescendingU64(const void* a, const void* b);
     340int psCompareDescendingU64(const void *a, const void *b);
    341341
    342342/** Compare function of psF32 data.
     
    346346 *                   than, equal to, or lessg than the second.
    347347 */
    348 int psCompareDescendingF32(const void* a, const void* b);
     348int psCompareDescendingF32(const void *a, const void *b);
    349349
    350350/** Compare function of psF64 data.
     
    354354 *                   than, equal to, or lessg than the second.
    355355 */
    356 int psCompareDescendingF64(const void* a, const void* b);
    357 
    358 
     356int psCompareDescendingF64(const void *a, const void *b);
    359357
    360358/// @}
  • trunk/psLib/src/math/psMatrix.c

    r1406 r1407  
     1
    12/** @file  psMatrix.c
    23 *
     
    2021 *  @author Ross Harman, MHPCC
    2122 *   
    22  *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
    23  *  @date $Date: 2004-08-06 22:34:05 $
     23 *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
     24 *  @date $Date: 2004-08-07 00:06:06 $
    2425 *
    2526 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2728
    2829/******************************************************************************/
     30
    2931/*  INCLUDE FILES                                                             */
     32
    3033/******************************************************************************/
    3134#include <string.h>
     
    4245
    4346/******************************************************************************/
     47
    4448/*  DEFINE STATEMENTS                                                         */
     49
    4550/******************************************************************************/
    4651
     
    4853
    4954/******************************************************************************/
     55
    5056/*  TYPE DEFINITIONS                                                          */
     57
    5158/******************************************************************************/
    5259
     
    5461
    5562/*****************************************************************************/
     63
    5664/*  GLOBAL VARIABLES                                                         */
     65
    5766/*****************************************************************************/
    5867
     
    6069
    6170/*****************************************************************************/
     71
    6272/*  FILE STATIC VARIABLES                                                    */
     73
    6374/*****************************************************************************/
    6475
     
    6677
    6778/*****************************************************************************/
     79
    6880/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     81
    6982/*****************************************************************************/
    7083
     
    142155
    143156/*****************************************************************************/
     157
    144158/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    145 /*****************************************************************************/
    146 
    147 psImage *psMatrixLUD(psImage *outImage, psVector *outPerm, psImage *inImage)
     159
     160/*****************************************************************************/
     161
     162psImage *psMatrixLUD(psImage * outImage, psVector * outPerm, psImage * inImage)
    148163{
    149164    int signum = 0;
     
    169184    numRows = inImage->numRows;
    170185    numCols = inImage->numCols;
    171     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     186    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    172187
    173188    // Initialize GSL data
     
    190205}
    191206
    192 psVector *psMatrixLUSolve(psVector *outVector, const psImage *inImage, const psVector *inVector, const
    193                           psVector *inPerm)
     207psVector *psMatrixLUSolve(psVector * outVector, const psImage * inImage, const psVector * inVector, const
     208                          psVector * inPerm)
    194209{
    195210    int arraySize = 0;
     
    219234    numRows = inImage->numRows;
    220235    numCols = inImage->numCols;
    221     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     236    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    222237
    223238    // Initialize GSL data
     
    243258}
    244259
    245 psImage *psMatrixInvert(psImage *outImage, const psImage *inImage, float *restrict det)
     260psImage *psMatrixInvert(psImage * outImage, const psImage * inImage, float *restrict det)
    246261{
    247262    int signum = 0;
     
    254269
    255270    // Error checks
    256     if(det == NULL) {
     271    if (det == NULL) {
    257272        psError(__func__, "Invalid operation: determinant argument is NULL.");
    258273        return outImage;
     
    269284    numRows = inImage->numRows;
    270285    numCols = inImage->numCols;
    271     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     286    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    272287
    273288    // Allocate GSL structs
     
    297312}
    298313
    299 float* psMatrixDeterminant(const psImage *restrict inImage)
     314float *psMatrixDeterminant(const psImage * restrict inImage)
    300315{
    301316    int signum = 0;
     
    315330    numRows = inImage->numRows;
    316331    numCols = inImage->numCols;
    317     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     332    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    318333
    319334    // Allocate GSL structs
     
    328343
    329344    // Calculate determinant
    330     det = (float*)psAlloc(sizeof(float));
     345    det = (float *)psAlloc(sizeof(float));
    331346    gsl_linalg_LU_decomp(lu, perm, &signum);
    332347    *det = (float)gsl_linalg_LU_det(lu, signum);
     
    339354}
    340355
    341 psImage* psMatrixMultiply(psImage *outImage, psImage *inImage1, psImage *inImage2)
     356psImage *psMatrixMultiply(psImage * outImage, psImage * inImage1, psImage * inImage2)
    342357{
    343358    int arraySize = 0;
     
    364379    numRows = inImage1->numRows;
    365380    numCols = inImage1->numCols;
    366     arraySize = PSELEMTYPE_SIZEOF(outImage->type.type)*numRows*numCols;
     381    arraySize = PSELEMTYPE_SIZEOF(outImage->type.type) * numRows * numCols;
    367382
    368383    // Initialize GSL data
     
    381396}
    382397
    383 psImage* psMatrixTranspose(psImage *outImage, const psImage *inImage)
     398psImage *psMatrixTranspose(psImage * outImage, const psImage * inImage)
    384399{
    385400    int arraySize = 0;
     
    400415    numRows = inImage->numRows;
    401416    numCols = inImage->numCols;
    402     arraySize = PSELEMTYPE_SIZEOF(inImage->type.type)*numRows*numCols;
     417    arraySize = PSELEMTYPE_SIZEOF(inImage->type.type) * numRows * numCols;
    403418
    404419    // Initialize GSL data
     
    418433}
    419434
    420 psImage *psMatrixEigenvectors(psImage *outImage, psImage *inImage)
     435psImage *psMatrixEigenvectors(psImage * outImage, psImage * inImage)
    421436{
    422437    int numRows = 0;
     
    462477}
    463478
    464 psVector *psMatrixToVector(psVector *outVector, psImage *inImage)
     479psVector *psMatrixToVector(psVector * outVector, psImage * inImage)
    465480{
    466481    int size = 0;
     
    471486    PS_CHECK_SIZE_IMAGE(inImage, outVector);
    472487
    473     if(inImage->numRows == 1) {
     488    if (inImage->numRows == 1) {
    474489        // Create transposed row vector
    475490        PS_CHECK_ALLOC_VECTOR(outVector, inImage->numCols, inImage->type.type);
    476491        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    }
    486500
    487501    PS_CHECK_NULL_VECTOR(outVector, outVector);
    488502
    489 
    490503    // More checks
    491     if(outVector->type.dimen == PS_DIMEN_VECTOR) {
     504    if (outVector->type.dimen == PS_DIMEN_VECTOR) {
    492505        PS_CHECK_DIMEN_AND_TYPE(outVector, PS_DIMEN_VECTOR, outVector);
    493506
    494         if(outVector->n == 0) {
     507        if (outVector->n == 0) {
    495508            outVector->n = inImage->numRows;
    496509        }
    497510
    498         if(outVector->n != inImage->numRows) {
     511        if (outVector->n != inImage->numRows) {
    499512            psError(__func__, "Image and vector sizes differ: (%d vs %d).", inImage->numRows, outVector->n);
    500513            return outVector;
    501514        }
    502515
    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;
    519523        }
    520524
     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
    521533    memcpy(outVector->data.V, inImage->data.V[0], size);
    522534
     
    524536}
    525537
    526 psImage *psVectorToMatrix(psImage *outImage, psVector *inVector)
     538psImage *psVectorToMatrix(psImage * outImage, psVector * inVector)
    527539{
    528540    int size = 0;
     
    531543    PS_CHECK_NULL_VECTOR(inVector, outImage);
    532544
    533     if(inVector->type.dimen == PS_DIMEN_VECTOR) {
     545    if (inVector->type.dimen == PS_DIMEN_VECTOR) {
    534546        PS_CHECK_DIMEN_AND_TYPE(inVector, PS_DIMEN_VECTOR, outImage);
    535547        PS_CHECK_SIZE_VECTOR(inVector, outImage);
    536548        PS_CHECK_ALLOC_IMAGE(outImage, 1, inVector->n, PS_TYPE_F64)
    537 
    538549        // More checks for PS_DIMEN_VECTOR
    539         if(outImage->numCols > 1) {
     550        if (outImage->numCols > 1) {
    540551            psError(__func__, "Image has more than 1 column: numCols = %d.", outImage->numCols);
    541552            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;
    567556        }
     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    }
    568575
    569576    PS_CHECK_NULL_IMAGE(outImage, outImage);
     
    574581    return outImage;
    575582}
    576 
  • trunk/psLib/src/math/psMatrix.h

    r974 r1407  
     1
    12/** @file  psMatrix.h
    23 *
     
    2122 *  @author Ross Harman, MHPCC
    2223 *
    23  *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
    24  *  @date $Date: 2004-06-10 01:58:06 $
     24 *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
     25 *  @date $Date: 2004-08-07 00:06:06 $
    2526 *
    2627 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2829
    2930#ifndef PSMATRIX_H
    30 #define PSMATRIX_H
     31#    define PSMATRIX_H
    3132
    3233/// @addtogroup Matrix
     
    4243 *  @return  psImage*: Pointer to LU decomposed psImage.
    4344 */
    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 );
     45psImage *psMatrixLUD(psImage * outImage,        // /< Image to return, or NULL.
     46                     psVector * outPerm,        // /< Output permutation vector used by psMatrixLUSolve.
     47                     psImage * inImage  // /< Image to decompose.
     48                    );
    4949
    5050/** LU Solution of psImage matrix.
     
    5757 *  @return  psVector*: Pointer to psVector solution of matrix equation.
    5858 */
    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 psMatrixLUD function.
    64 );
     59psVector *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                         );
    6565
    6666/** Invert psImage matrix.
     
    7373 *  @return  psImage*: Pointer to inverted psImage.
    7474 */
    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 );
     75psImage *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                       );
    8079
    8180/** Calculate psImage matrix determinant.
     
    8786 *  @return  float: Determinant from psImage.
    8887 */
    89 float* psMatrixDeterminant(
    90     const psImage *restrict inMatrix    ///< Image used to calculate determinant.
    91 );
     88float *psMatrixDeterminant(const psImage * restrict inMatrix    // /< Image used to calculate determinant.
     89                          );
    9290
    9391/** Performs psImage matrix multiplication.
     
    10098 *  @return  psImage*: Pointer to resulting psImage.
    10199 */
    102 psImage *psMatrixMultiply(
    103     psImage *outImage,  ///< Matrix to return, or NULL.
    104     psImage *inImage1,  ///< First input image.
    105     psImage *inImage2   ///< Second input image.
    106 );
     100psImage *psMatrixMultiply(psImage * outImage,   // /< Matrix to return, or NULL.
     101                          psImage * inImage1,   // /< First input image.
     102                          psImage * inImage2    // /< Second input image.
     103                         );
    107104
    108105/** Transpose matrix.
     
    115112 *  @return  psImage*: Pointer to transposed psImage.
    116113 */
    117 psImage *psMatrixTranspose(
    118     psImage *outImage,      ///< Image to return, or NULL
    119     const psImage *inImage  ///< Image to transpose
    120 );
     114psImage *psMatrixTranspose(psImage * outImage,  // /< Image to return, or NULL
     115                           const psImage * inImage      // /< Image to transpose
     116                          );
    121117
    122118/** Calculate matrix eigenvectors.
     
    128124 *  @return  psImage*: Pointer to matrix of Eigenvectors.
    129125 */
    130 psImage *psMatrixEigenvectors(
    131     psImage *outImage,  ///< Eigenvectors to return, or NULL.
    132     psImage *inImage    ///< Input image.
    133 );
     126psImage *psMatrixEigenvectors(psImage * outImage,       // /< Eigenvectors to return, or NULL.
     127                              psImage * inImage // /< Input image.
     128                             );
    134129
    135130/** Convert matrix to vector.
     
    142137 *  @return  psVector*: Pointer to psVector.
    143138 */
    144 psVector *psMatrixToVector(
    145     psVector *outVector,    ///< Vector to return, or NULL.
    146     psImage *inImage        ///< Image to convert.
    147 );
     139psVector *psMatrixToVector(psVector * outVector,        // /< Vector to return, or NULL.
     140                           psImage * inImage    // /< Image to convert.
     141                          );
    148142
    149143/** Convert vector to matrix.
     
    156150 *  @return  psVector*: Pointer to psIamge.
    157151 */
    158 psImage *psVectorToMatrix(
    159     psImage *outImage,  ///< Matrix to return, or NULL.
    160     psVector *inVector  ///< Vector to convert.
    161 );
     152psImage *psVectorToMatrix(psImage * outImage,   // /< Matrix to return, or NULL.
     153                          psVector * inVector   // /< Vector to convert.
     154                         );
    162155
    163156/// @}
  • trunk/psLib/src/math/psMinimize.c

    r1406 r1407  
     1
    12/** @file  psMinimize.c
    23 *  \brief basic minimization functions
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.27 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.28 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    16 /*****************************************************************************/
     17
     18/*****************************************************************************/
     19
    1720/* INCLUDE FILES                                                             */
     21
    1822/*****************************************************************************/
    1923#include <stdlib.h>
     
    4044#include "psMinimize.h"
    4145#include "psMatrix.h"
    42 /*****************************************************************************/
     46
     47/*****************************************************************************/
     48
    4349/* DEFINE STATEMENTS                                                         */
     50
    4451/*****************************************************************************/
    4552#define MAX_LMM_ITERATIONS 100
     
    8390}
    8491
    85 
    86 /*****************************************************************************/
     92/*****************************************************************************/
     93
    8794/* TYPE DEFINITIONS                                                          */
     95
    8896/*****************************************************************************/
    8997typedef struct
    9098{
    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;
    95103    const psVector *restrict data;
    96     const psVector *restrict  errors;
     104    const psVector *restrict errors;
    97105    const psVector *restrict paramMask;
    98106    float (*evalModel) (const psVector *, const psVector *);
     
    103111typedef struct
    104112{
    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;
    108116    const psVector *restrict paramMask;
    109117    float (*evalModel) (const psVector *, const psVector *);
     
    113121
    114122/*****************************************************************************/
     123
    115124/* GLOBAL VARIABLES                                                          */
     125
    116126/*****************************************************************************/
    117127
     
    119129
    120130/*****************************************************************************/
     131
    121132/* FILE STATIC VARIABLES                                                     */
     133
    122134/*****************************************************************************/
    123135
     
    125137
    126138/*****************************************************************************/
     139
    127140/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     141
    128142/*****************************************************************************/
    129143
     
    143157 guess at the parameters, an option parameter mask, etc.
    144158 *****************************************************************************/
    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;
     159double 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;
    156168    psVector *inputParameterList = NULL;
    157169
     
    163175    if (mask != NULL) {
    164176        j = 0;
    165         for (i=0;i<mask->n;i++) {
     177        for (i = 0; i < mask->n; i++) {
    166178            if (mask->data.U8[i] != 0) {
    167179                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    171183        }
    172184    } else {
    173         for (i=0;i<initialGuess->n;i++) {
     185        for (i = 0; i < initialGuess->n; i++) {
    174186            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    175187        }
     
    181193    // Free allocated memory and return the value of the function.
    182194    psFree(inputParameterList);
    183     return(tmpf);
     195    return (tmpf);
    184196}
    185197
     
    199211 in "params" and return those derivatives in this psVector.
    200212 *****************************************************************************/
    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) =
     213void 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) =
    212222        ((psMinimizeData *) funcData)->d_evalModel;
    213223    psVector *inputParameterList = NULL;
     
    220230    if (mask != NULL) {
    221231        j = 0;
    222         for (i=0;i<mask->n;i++) {
     232        for (i = 0; i < mask->n; i++) {
    223233            if (mask->data.U8[i] != 0) {
    224234                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    228238        }
    229239    } else {
    230         for (i=0;i<initialGuess->n;i++) {
     240        for (i = 0; i < initialGuess->n; i++) {
    231241            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    232242        }
     
    235245    // Evaluate the derivative w.r.t. each parameter.
    236246    // 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++) {
    238248        tmpf = d_evalModel(inputParameterList, coord, i);
    239249        gsl_vector_set(df, i, tmpf);
     
    247257    Compute both p_psMinFunc and p_psMinFuncDeriv together.
    248258 *****************************************************************************/
    249 void p_psMinFuncFuncDeriv(const gsl_vector *params,
    250                           void *funcData,
    251                           double *f,
    252                           gsl_vector *df)
     259void p_psMinFuncFuncDeriv(const gsl_vector * params, void *funcData, double *f, gsl_vector * df)
    253260{
    254261    *f = p_psMinFunc(params, funcData);
     
    281288  expected value and divide by the error.
    282289 *****************************************************************************/
    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;
     290int 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;
    296301    psVector *inputParameterList = NULL;
    297302    psVector *tmpVecPtr = NULL;
     
    307312    if (mask != NULL) {
    308313        j = 0;
    309         for (i=0;i<mask->n;i++) {
     314        for (i = 0; i < mask->n; i++) {
    310315            if (mask->data.U8[i] != 0) {
    311316                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    315320        }
    316321    } else {
    317         for (i=0;i<initialGuess->n;i++) {
     322        for (i = 0; i < initialGuess->n; i++) {
    318323            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    319324        }
     
    321326
    322327    // 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++) {
    325330            tmpVecPtr->data.F32[j] = domain->data.F32[i][j];
    326331        }
    327332        tmpf = evalModel(tmpVecPtr, inputParameterList);
    328333
    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]);
    331335    }
    332336
     
    354358 and returned in this data structure.
    355359 *****************************************************************************/
    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;
     360int 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;
    364366    psVector *inputParameterList = NULL;
    365367    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;
    367370
    368371    size_t i;
     
    380383    if (mask != NULL) {
    381384        j = 0;
    382         for (i=0;i<mask->n;i++) {
     385        for (i = 0; i < mask->n; i++) {
    383386            if (mask->data.U8[i] != 0) {
    384387                inputParameterList->data.F32[i] = initialGuess->data.F32[i];
     
    388391        }
    389392    } else {
    390         for (i=0;i<initialGuess->n;i++) {
     393        for (i = 0; i < initialGuess->n; i++) {
    391394            inputParameterList->data.F32[i] = gsl_vector_get(params, i);
    392395        }
     
    394397
    395398    // 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++) {
    398401            tmpVecPtr->data.F32[j] = domain->data.F32[i][j];
    399402        }
    400403
    401         for (j=0;j<inputParameterList->n;j++) {
     404        for (j = 0; j < inputParameterList->n; j++) {
    402405            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]));
    404407        }
    405408    }
     
    410413}
    411414
    412 
    413 int p_psMinChi2FuncFuncDeriv(const gsl_vector *params,
    414                              void *funcData,
    415                              gsl_vector *f,
    416                              gsl_matrix *J)
     415int p_psMinChi2FuncFuncDeriv(const gsl_vector * params, void *funcData, gsl_vector * f, gsl_matrix * J)
    417416{
    418417    p_psMinChi2Func(params, funcData, f);
     
    421420    return GSL_SUCCESS;
    422421}
    423 
    424422
    425423/******************************************************************************
     
    428426returned as a psVector sums.
    429427 *****************************************************************************/
    430 void p_psBuildSums1D(double x,
    431                      int polyOrder,
    432                      psVector *sums)
    433 {
    434     int       i = 0;
    435     double    xSum = 0.0;
     428void p_psBuildSums1D(double x, int polyOrder, psVector * sums)
     429{
     430    int i = 0;
     431    double xSum = 0.0;
    436432
    437433    xSum = 1.0;
    438     for(i=0;i<=polyOrder;i++) {
     434    for (i = 0; i <= polyOrder; i++) {
    439435        sums->data.F64[i] = xSum;
    440         xSum*= x;
    441     }
    442 }
    443 
     436        xSum *= x;
     437    }
     438}
    444439
    445440/******************************************************************************
     
    448443 *****************************************************************************/
    449444psVector *psBuildImageScalingFactors(int x)
    450 
    451445{
    452446    int i = 0;                  // loop index variable.
    453447    psVector *imageScalingFactors = NULL;
    454448
    455 
    456449    imageScalingFactors = psVectorAlloc(x, PS_TYPE_F32);
    457450
    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);
    463456}
    464457
     
    481474    *flag   Set this to 1 if we must recalculate the coefficients.
    482475 *****************************************************************************/
    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
     476void 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
    493482    // 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
    497487    // polynomial.
    498     int         lastTerm = 0;           // The index location of the first
     488    int lastTerm = 0;           // The index location of the first
     489
    499490    // 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.
    501492
    502493    // 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));
    508499    }
    509500
    510501    // Invert the matrix A and put the result in y[][].  This code is taken
    511502    // 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++) {
    514505            col[i] = 0.0;
    515506        }
    516507        col[j] = 1.0;
    517508        // 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++) {
    520511            y[i][j] = col[i];
    521512        }
     
    527518    // terms and check if they are consistent with zero.
    528519
    529     numPolyTerms = (((polyOrder+1) * (polyOrder + 2)) / 2);
     520    numPolyTerms = (((polyOrder + 1) * (polyOrder + 2)) / 2);
    530521    lastTerm = numPolyTerms + 1;
    531522    firstTerm = lastTerm - polyOrder;
    532523    *flag = 1;
    533     for (i=firstTerm; i<=lastTerm; i++) {
     524    for (i = firstTerm; i <= lastTerm; i++) {
    534525        #ifdef DARWIN
    535526        error[i] = (float)sqrt(y[i][i]);
     
    539530        #endif
    540531
    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]))) {
    543533            *flag = 0;
    544534        }
     
    548538    psFree(error);
    549539    psFree(col);
    550     for(j=1;j<=N;j++) {
     540    for (j = 1; j <= N; j++) {
    551541        psFree(y[j]);
    552542    }
     
    554544}
    555545
    556 
    557 
    558 
    559 /*****************************************************************************/
     546/*****************************************************************************/
     547
    560548/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    561 /*****************************************************************************/
    562 
    563 
     549
     550/*****************************************************************************/
    564551
    565552/******************************************************************************
     
    569556parameters of that function such that the ...
    570557 *****************************************************************************/
    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)
     558psVector *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)
    577562{
    578563    int status;
     
    607592    // for the parameters.
    608593    if (paramMask != NULL) {
    609         for (i=0;i<paramMask->n;i++) {
     594        for (i = 0; i < paramMask->n; i++) {
    610595            if (paramMask->data.U8[i] != 0) {
    611596                inputData.paramCount++;
     
    613598        }
    614599    } else {
    615         inputData.paramCount= initialGuess->n;
     600        inputData.paramCount = initialGuess->n;
    616601    }
    617602
     
    622607    if (paramMask != NULL) {
    623608        j = 0;
    624         for (i=0;i<initialGuess->n;i++) {
     609        for (i = 0; i < initialGuess->n; i++) {
    625610            if (paramMask->data.U8[i] == 0) {
    626611                gsl_vector_set(x, j++, initialGuess->data.F32[i]);
     
    628613        }
    629614    } else {
    630         for (i=0;i<initialGuess->n;i++) {
     615        for (i = 0; i < initialGuess->n; i++) {
    631616            gsl_vector_set(x, i, initialGuess->data.F32[i]);
    632617        }
     
    651636
    652637        if (status == GSL_SUCCESS)
    653             printf ("Minimum found at:\n");
     638            printf("Minimum found at:\n");
    654639
    655640    } while (status == GSL_CONTINUE && iter < MAX_MINIMIZE_ITERATIONS);
     
    660645    if (paramMask != NULL) {
    661646        j = 0;
    662         for (i=0;i<initialGuess->n;i++) {
     647        for (i = 0; i < initialGuess->n; i++) {
    663648            if (paramMask->data.U8[i] == 0) {
    664649                initialGuess->data.F32[i] = gsl_vector_get(s->x, j++);
     
    668653        }
    669654    } else {
    670         for (i=0;i<initialGuess->n;i++) {
     655        for (i = 0; i < initialGuess->n; i++) {
    671656            initialGuess->data.F32[i] = gsl_vector_get(s->x, i);
    672657        }
    673658    }
    674     return(initialGuess);
    675 }
    676 
    677 
    678 
    679 
    680 
     659    return (initialGuess);
     660}
    681661
    682662/******************************************************************************
     
    684664    such that they best fit the supplied data points.
    685665 *****************************************************************************/
    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
     666psVector *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
    702680    // 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
    704683    // with masked parameters removed.
    705684    const gsl_multifit_fdfsolver_type *T;
     685
    706686    // This tells GSL to use the Levenberg-
    707687    // Marquardt algorithm for chi2
    708688    // minimization.
    709     gsl_multifit_fdfsolver *s; // GSL data structure.
     689    gsl_multifit_fdfsolver *s;  // GSL data structure.
    710690    psMinChi2Data inputData;
    711691    float chiSqOld = 0.0;
     
    721701    PS_CHECK_VECTOR_SIZE_EQUAL(data, errors);
    722702    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.");
    724704    }
    725705    if (paramMask != NULL) {
     
    743723    // for the parameters.
    744724    if (paramMask != NULL) {
    745         for (i=0;i<paramMask->n;i++) {
     725        for (i = 0; i < paramMask->n; i++) {
    746726            if (paramMask->data.U8[i] != 0) {
    747727                inputData.paramCount++;
     
    749729        }
    750730    } else {
    751         inputData.paramCount= initialGuess->n;
     731        inputData.paramCount = initialGuess->n;
    752732    }
    753733
     
    755735    // the vector inputParameterList.  If the paramMask is not NULL, then those
    756736    // parameters are masked out.
    757     xInit = (double *) psAlloc(inputData.paramCount * sizeof(double));
     737    xInit = (double *)psAlloc(inputData.paramCount * sizeof(double));
    758738    if (paramMask != NULL) {
    759739        j = 0;
    760         for (i=0;i<initialGuess->n;i++) {
     740        for (i = 0; i < initialGuess->n; i++) {
    761741            if (paramMask->data.U8[i] == 0) {
    762742                xInit[j++] = initialGuess->data.F32[i];
     
    764744        }
    765745    } else {
    766         for (i=0;i<initialGuess->n;i++) {
     746        for (i = 0; i < initialGuess->n; i++) {
    767747            xInit[i] = initialGuess->data.F32[i];
    768748        }
     
    771751    const gsl_rng_type *type;
    772752    gsl_rng *r;
     753
    773754    gsl_rng_env_setup();
    774755
     
    789770
    790771    gsl_vector_view x = gsl_vector_view_array(xInit, inputData.paramCount);
     772
    791773    T = gsl_multifit_fdfsolver_lmsder;
    792774    s = gsl_multifit_fdfsolver_alloc(T, numData, inputData.paramCount);
     
    796778    do {
    797779        iter++;
    798         for (i=0;i<initialGuess->n;i++) {
     780        for (i = 0; i < initialGuess->n; i++) {
    799781            printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i));
    800782        }
     
    802784        status = gsl_multifit_fdfsolver_iterate(s);
    803785        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++) {
    805787            printf("Iteration %d: parameter %d is %.3f\n", iter, i, gsl_vector_get(s->x, i));
    806788        }
     
    810792            psAbort(__func__, "gsl_multifit_fdfsolver_iterate(%s)\n", gsl_strerror(status));
    811793        }
    812 
    813794        // Test if the parameters changed by a small enough amount.
    814795        // NOTE: This wasn't working right when the parameters fit exactly.
    815796        // 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);
    817798
    818799        // We test for convergence if chiSquared changes by less than 1.0
     
    829810    } while (status == GSL_CONTINUE && iter < MAX_LMM_ITERATIONS);
    830811
    831 
    832812    // In the above steps we had removed the masked elements from the
    833813    // the solver.  This next code blocks puts those masked elements
     
    835815    if (paramMask != NULL) {
    836816        j = 0;
    837         for (i=0;i<initialGuess->n;i++) {
     817        for (i = 0; i < initialGuess->n; i++) {
    838818            if (paramMask->data.U8[i] == 0) {
    839819                initialGuess->data.F32[i] = gsl_vector_get(s->x, j++);
     
    843823        }
    844824    } else {
    845         for (i=0;i<initialGuess->n;i++) {
     825        for (i = 0; i < initialGuess->n; i++) {
    846826            initialGuess->data.F32[i] = gsl_vector_get(s->x, i);
    847827        }
     
    857837
    858838    // Bye bye.
    859     return(initialGuess);
    860 }
    861 
     839    return (initialGuess);
     840}
    862841
    863842/******************************************************************************
     
    868847NOTE: yErr is currently ignored.
    869848 *****************************************************************************/
    870 psPolynomial1D *
    871 psVectorFitPolynomial1D(psPolynomial1D *myPoly,
    872                         const psVector *restrict x,
    873                         const psVector *restrict y,
    874                         const psVector *restrict yErr)
     849psPolynomial1D *psVectorFitPolynomial1D(psPolynomial1D * myPoly,
     850                                        const psVector * restrict x,
     851                                        const psVector * restrict y, const psVector * restrict yErr)
    875852{
    876853    int polyOrder = myPoly->n;
     
    879856    psVector *B = NULL;
    880857    psVector *outPerm = NULL;
    881     psVector *X = NULL;   // NOTE: do we need this?
     858    psVector *X = NULL;         // NOTE: do we need this?
    882859    psVector *coeffs = NULL;
    883860    int i = 0;
     
    886863    psVector *xSums = NULL;
    887864
    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    // }
    892869
    893870    PS_CHECK_NULL_1DPOLY(myPoly);
     
    901878    PS_CHECK_VECTOR_SIZE_EQUAL(y, yErr);
    902879
    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);
    908885    outPerm = psVectorAlloc(polyOrder, PS_TYPE_F64);
    909     xSums   = psVectorAlloc(1+2*polyOrder, PS_TYPE_F64);
     886    xSums = psVectorAlloc(1 + 2 * polyOrder, PS_TYPE_F64);
    910887
    911888    // Initialize data structures.
    912     for(i=0;i<(polyOrder);i++) {
     889    for (i = 0; i < (polyOrder); i++) {
    913890        B->data.F64[i] = 0.0;
    914891        coeffs->data.F64[i] = 0.0;
    915892        outPerm->data.F64[i] = 0.0;
    916         for(j=0;j<(polyOrder);j++) {
     893        for (j = 0; j < (polyOrder); j++) {
    917894            A->data.F64[i][j] = 0.0;
    918895            ALUD->data.F64[i][j] = 0.0;
    919896        }
    920897    }
    921     for (i=0;i<X->n;i++) {
     898    for (i = 0; i < X->n; i++) {
    922899        X->data.F64[i] = x->data.F64[i];
    923900    }
    924901
    925902    // 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];
    936913            }
    937914        }
     
    941918    coeffs = psMatrixLUSolve(coeffs, ALUD, B, outPerm);
    942919
    943     for(k=0;k<(polyOrder);k++) {
     920    for (k = 0; k < (polyOrder); k++) {
    944921        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    // }
    952929
    953930    psFree(A);
     
    959936    psFree(xSums);
    960937
    961     return(myPoly);
    962 }
     938    return (myPoly);
     939}
  • trunk/psLib/src/math/psMinimize.h

    r1406 r1407  
    11#if !defined(PS_MINIMIZE_H)
    2 #define PS_MINIMIZE_H
     2#    define PS_MINIMIZE_H
    33
    4 #include "psFunctions.h"
     4#    include "psFunctions.h"
     5
    56/** \file psMinimize.h
    67 *  \brief minimization operations
     
    910
    1011/** Functions **************************************************************/
     12
    1113/** \addtogroup Stats
    1214 *  \{
     
    1416
    1517/** 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 
     18psVector *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);
    2322
    2423/** 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               );
     24psVector *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);
    3848
    3949/** 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 use the indices)
    43                         const psVector *restrict y, ///< Coordinates
    44                         const psVector *restrict yErr ///< Errors in coordinates, or NULL
    45                        );
     50psPolynomial1D *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                                       );
    4656
    47 /* \} */ // End of MathGroup Functions
     57/* \} */// End of MathGroup Functions
    4858
    4959#endif
  • trunk/psLib/src/math/psPolynomial.c

    r1406 r1407  
     1
    12/** @file  psFunctions.c
    23 *
     
    78 *  polynomials.  It also contains a Gaussian functions.
    89 *
    9  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1314 */
    14 /*****************************************************************************/
     15
     16/*****************************************************************************/
     17
    1518/*  INCLUDE FILES                                                            */
     19
    1620/*****************************************************************************/
    1721#include <stdlib.h>
     
    3135#include <gsl/gsl_rng.h>
    3236#include <gsl/gsl_randist.h>
    33 /*****************************************************************************/
     37
     38/*****************************************************************************/
     39
    3440/* DEFINE STATEMENTS                                                         */
     41
    3542/*****************************************************************************/
    3643
     
    3845
    3946/*****************************************************************************/
     47
    4048/* 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/*****************************************************************************/
     51static void polynomial1DFree(psPolynomial1D * myPoly);
     52static void polynomial2DFree(psPolynomial2D * myPoly);
     53static void polynomial3DFree(psPolynomial3D * myPoly);
     54static void polynomial4DFree(psPolynomial4D * myPoly);
     55static void dPolynomial1DFree(psDPolynomial1D * myPoly);
     56static void dPolynomial2DFree(psDPolynomial2D * myPoly);
     57static void dPolynomial3DFree(psDPolynomial3D * myPoly);
     58static void dPolynomial4DFree(psDPolynomial4D * myPoly);
     59
     60/*****************************************************************************/
     61
    5262/* GLOBAL VARIABLES                                                          */
     63
    5364/*****************************************************************************/
    5465
     
    5667
    5768/*****************************************************************************/
     69
    5870/* FILE STATIC VARIABLES                                                     */
     71
    5972/*****************************************************************************/
    6073
     
    6275
    6376/*****************************************************************************/
     77
    6478/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     79
    6580/*****************************************************************************/
    6681
     
    6883
    6984/*****************************************************************************/
     85
    7086/*  FUNCTION IMPLEMENTATION - PUBLIC                                         */
     87
    7188/*****************************************************************************/
    7289
     
    7693    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f]
    7794 *****************************************************************************/
    78 float
    79 psGaussian(float x,
    80            float mean,
    81            float sigma,
    82            bool  normal)
     95float psGaussian(float x, float mean, float sigma, bool normal)
    8396{
    8497    float tmp = 1.0;
     
    94107    }
    95108
    96     return(tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));
     109    return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma)));
    97110}
    98111
     
    107120 NOTE: There is no way to seed the random generator.
    108121 *****************************************************************************/
    109 psVector *psGaussianDev(float mean,
    110                         float sigma,
    111                         int Npts)
     122psVector *psGaussianDev(float mean, float sigma, int Npts)
    112123{
    113124    psVector *gauss = NULL;
     
    127138
    128139    // NOTE: Should I free r as well?
    129     return(gauss);
    130 }
    131 
     140    return (gauss);
     141}
    132142
    133143/*****************************************************************************
     
    140150
    141151    newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D));
    142     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial1DFree);
     152    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree);
    143153    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++) {
    148158        newPoly->coeff[i] = 0.0;
    149159        newPoly->coeffErr[i] = 0.0;
     
    151161    }
    152162
    153     return(newPoly);
     163    return (newPoly);
    154164}
    155165
     
    161171
    162172    newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D));
    163     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial2DFree);
     173    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree);
    164174    newPoly->nX = nX;
    165175    newPoly->nY = nY;
    166176
    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++) {
    177187            newPoly->coeff[x][y] = 0.0;
    178188            newPoly->coeffErr[x][y] = 0.0;
     
    181191    }
    182192
    183     return(newPoly);
     193    return (newPoly);
    184194}
    185195
     
    192202
    193203    newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D));
    194     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial3DFree);
     204    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree);
    195205    newPoly->nX = nX;
    196206    newPoly->nY = nY;
    197207    newPoly->nZ = nZ;
    198208
    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++) {
    215225                newPoly->coeff[x][y][z] = 0.0;
    216226                newPoly->coeffErr[x][y][z] = 0.0;
     
    220230    }
    221231
    222     return(newPoly);
     232    return (newPoly);
    223233}
    224234
     
    232242
    233243    newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D));
    234     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial4DFree);
     244    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree);
    235245    newPoly->nW = nW;
    236246    newPoly->nX = nX;
     
    238248    newPoly->nZ = nZ;
    239249
    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++) {
    262272                    newPoly->coeff[w][x][y][z] = 0.0;
    263273                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    268278    }
    269279
    270     return(newPoly);
    271 }
    272 
    273 static void polynomial1DFree(psPolynomial1D *myPoly)
     280    return (newPoly);
     281}
     282
     283static void polynomial1DFree(psPolynomial1D * myPoly)
    274284{
    275285    psFree(myPoly->coeff);
     
    278288}
    279289
    280 static void polynomial2DFree(psPolynomial2D *myPoly)
    281 {
    282     int x = 0;
    283 
    284     for (x=0;x<myPoly->nX;x++) {
     290static void polynomial2DFree(psPolynomial2D * myPoly)
     291{
     292    int x = 0;
     293
     294    for (x = 0; x < myPoly->nX; x++) {
    285295        psFree(myPoly->coeff[x]);
    286296        psFree(myPoly->coeffErr[x]);
     
    292302}
    293303
    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++) {
     304static 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++) {
    301311            psFree(myPoly->coeff[x][y]);
    302312            psFree(myPoly->coeffErr[x][y]);
     
    313323}
    314324
    315 static void polynomial4DFree(psPolynomial4D *myPoly)
     325static void polynomial4DFree(psPolynomial4D * myPoly)
    316326{
    317327    int w = 0;
     
    319329    int y = 0;
    320330
    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++) {
    324334                psFree(myPoly->coeff[w][x][y]);
    325335                psFree(myPoly->coeffErr[w][x][y]);
     
    343353    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    344354 *****************************************************************************/
    345 float
    346 psPolynomial1DEval(float x,
    347                    const psPolynomial1D *myPoly)
     355float psPolynomial1DEval(float x, const psPolynomial1D * myPoly)
    348356{
    349357    int loop_x = 0;
     
    355363    }
    356364
    357 
    358365    // NOTE: Do we want to flag this case?
    359366    if (myPoly->n == 0) {
    360         return(1.0);
     367        return (1.0);
    361368    }
    362369
     
    365372    }
    366373
    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
     382float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly)
    380383{
    381384    int loop_x = 0;
     
    385388    float ySum = 1.0;
    386389
    387     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     390    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    388391        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
     402float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly)
    404403{
    405404    int loop_x = 0;
     
    411410    float zSum = 1.0;
    412411
    413     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     412    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    414413        ySum = xSum;
    415         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     414        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    416415            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
     428float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly)
    435429{
    436430    int loop_w = 0;
     
    444438    float zSum = 1.0;
    445439
    446     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     440    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    447441        xSum = wSum;
    448         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     442        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    449443            ySum = xSum;
    450             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     444            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    451445                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;
    456449                }
    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}
    469459
    470460psDPolynomial1D *psDPolynomial1DAlloc(int n)
     
    474464
    475465    newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D));
    476     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial1DFree);
     466    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree);
    477467    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++) {
    482472        newPoly->coeff[i] = 0.0;
    483473        newPoly->coeffErr[i] = 0.0;
     
    485475    }
    486476
    487     return(newPoly);
     477    return (newPoly);
    488478}
    489479
     
    495485
    496486    newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D));
    497     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial2DFree);
     487    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree);
    498488    newPoly->nX = nX;
    499489    newPoly->nY = nY;
    500490
    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++) {
    511501            newPoly->coeff[x][y] = 0.0;
    512502            newPoly->coeffErr[x][y] = 0.0;
     
    515505    }
    516506
    517     return(newPoly);
     507    return (newPoly);
    518508}
    519509
     
    526516
    527517    newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D));
    528     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial3DFree);
     518    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree);
    529519    newPoly->nX = nX;
    530520    newPoly->nY = nY;
    531521    newPoly->nZ = nZ;
    532522
    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++) {
    549539                newPoly->coeff[x][y][z] = 0.0;
    550540                newPoly->coeffErr[x][y][z] = 0.0;
     
    554544    }
    555545
    556     return(newPoly);
     546    return (newPoly);
    557547}
    558548
     
    566556
    567557    newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D));
    568     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial4DFree);
     558    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree);
    569559    newPoly->nW = nW;
    570560    newPoly->nX = nX;
     
    572562    newPoly->nZ = nZ;
    573563
    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++) {
    596586                    newPoly->coeff[w][x][y][z] = 0.0;
    597587                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    602592    }
    603593
    604     return(newPoly);
    605 }
    606 
    607 static void dPolynomial1DFree(psDPolynomial1D *myPoly)
     594    return (newPoly);
     595}
     596
     597static void dPolynomial1DFree(psDPolynomial1D * myPoly)
    608598{
    609599    psFree(myPoly->coeff);
     
    612602}
    613603
    614 static void dPolynomial2DFree(psDPolynomial2D *myPoly)
    615 {
    616     int x = 0;
    617 
    618     for (x=0;x<myPoly->nX;x++) {
     604static void dPolynomial2DFree(psDPolynomial2D * myPoly)
     605{
     606    int x = 0;
     607
     608    for (x = 0; x < myPoly->nX; x++) {
    619609        psFree(myPoly->coeff[x]);
    620610        psFree(myPoly->coeffErr[x]);
     
    626616}
    627617
    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++) {
     618static 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++) {
    635625            psFree(myPoly->coeff[x][y]);
    636626            psFree(myPoly->coeffErr[x][y]);
     
    647637}
    648638
    649 static void dPolynomial4DFree(psDPolynomial4D *myPoly)
     639static void dPolynomial4DFree(psDPolynomial4D * myPoly)
    650640{
    651641    int w = 0;
     
    653643    int y = 0;
    654644
    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++) {
    658648                psFree(myPoly->coeff[w][x][y]);
    659649                psFree(myPoly->coeffErr[w][x][y]);
     
    677667    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    678668 *****************************************************************************/
    679 double
    680 psDPolynomial1DEval(double x,
    681                     const psDPolynomial1D *myPoly)
     669double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly)
    682670{
    683671    int loop_x = 0;
     
    687675    // NOTE: Do we want to flag this case?
    688676    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
     688double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly)
    705689{
    706690    int loop_x = 0;
     
    710694    double ySum = 1.0;
    711695
    712     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     696    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    713697        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
     708double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly)
    729709{
    730710    int loop_x = 0;
     
    736716    double zSum = 1.0;
    737717
    738     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     718    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    739719        ySum = xSum;
    740         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     720        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    741721            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
     734double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly)
    760735{
    761736    int loop_w = 0;
     
    769744    double zSum = 1.0;
    770745
    771     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     746    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    772747        xSum = wSum;
    773         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     748        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    774749            ySum = xSum;
    775             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     750            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    776751                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;
    781755                }
    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
    12/** @file psFunctions.h
    23*  \brief Standard Mathematical Functions.
     
    1213*  @author George Gusciora, MHPCC
    1314*
    14 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    15 *  @date $Date: 2004-08-06 22:34:05 $
     15*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     16*  @date $Date: 2004-08-07 00:06:06 $
    1617*
    1718*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#if !defined(PS_FUNCTIONS_H)
    21 #define PS_FUNCTIONS_H
    22 
    23 #include <stdbool.h>
    24 
    25 #include "psVector.h"
     22#    define PS_FUNCTIONS_H
     23
     24#    include <stdbool.h>
     25
     26#    include "psVector.h"
    2627
    2728/** \addtogroup Stats
     
    3334    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */
    3435
    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 
     36float 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                );
    4241
    4342/** Produce a vector of random numbers from a Gaussian distribution with
    4443    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 
     44psVector *psGaussianDev(float mean,     // /< The mean of the Gaussian
     45                        float sigma,    // /< The sigma of the Gaussian
     46                        int Npts);      // /< The size of the vector
    5247
    5348/** One-dimensional polynomial */
    5449typedef struct
    5550{
    56     int n;           ///< Number of terms
    57     float *coeff;    ///< Coefficients
    58     float *coeffErr; ///< Error in coefficients
    59     char *mask;      ///< Coefficient mask
     51    int n;                      // /< Number of terms
     52    float *coeff;               // /< Coefficients
     53    float *coeffErr;            // /< Error in coefficients
     54    char *mask;                 // /< Coefficient mask
    6055}
    6156psPolynomial1D;
     
    6459typedef struct
    6560{
    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
    7066}
    7167psPolynomial2D;
     
    7470typedef struct
    7571{
    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
    8078}
    8179psPolynomial3D;
     
    8482typedef struct
    8583{
    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
    9091}
    9192psPolynomial4D;
    9293
    93 
    9494/** Functions **************************************************************/
    9595
    9696/** 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
     97psPolynomial1D *psPolynomial1DAlloc(int n       // /< Number of terms
     98                                   );
     99
     100/** Constructor */
     101psPolynomial2D *psPolynomial2DAlloc(int nX, int nY      // /< Number of terms in x and y
     102                                   );
     103
     104/** Constructor */
     105psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ      // /< Number of terms in x, y and z
     106                                   );
     107
     108/** Constructor */
     109psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ      // /< Number of terms in w, x, y and
     110                                    // z
    107111                                   );
    108112
    109113/** Evaluate 1D polynomial */
    110 float
    111 psPolynomial1DEval( float x,   ///< Value at which to evaluate
    112                     const psPolynomial1D *myPoly ///< Coefficients for the polynomial
    113                   );
     114float psPolynomial1DEval(float x,       // /< Value at which to evaluate
     115                         const psPolynomial1D * myPoly  // /< Coefficients for the polynomial
     116                        );
    114117
    115118/** 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                   );
     119float 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                        );
    121123
    122124/** 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                   );
     125float 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                        );
    129130
    130131/** 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                   );
     132float 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                        );
    138138
    139139/*****************************************************************************/
     
    144144typedef struct
    145145{
    146     int n;    ///< Number of terms
    147     double *coeff;   ///< Coefficients
    148     double *coeffErr;   ///< Error in coefficients
    149     char *mask;    ///< Coefficient mask
     146    int n;                      // /< Number of terms
     147    double *coeff;              // /< Coefficients
     148    double *coeffErr;           // /< Error in coefficients
     149    char *mask;                 // /< Coefficient mask
    150150}
    151151psDPolynomial1D;
     
    154154typedef struct
    155155{
    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
    160161}
    161162psDPolynomial2D;
     
    164165typedef struct
    165166{
    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
    170173}
    171174psDPolynomial3D;
     
    174177typedef struct
    175178{
    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
    180186}
    181187psDPolynomial4D;
    182188
    183189/** 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
     190psDPolynomial1D *psDPolynomial1DAlloc(int n     // /< Number of terms
     191                                     );
     192
     193/** Constructor */
     194psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY    // /< Number of terms in x and y
     195                                     );
     196
     197/** Constructor */
     198psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ    // /< Number of terms in x, y and z
     199                                     );
     200
     201/** Constructor */
     202psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ    // /< Number of terms in w, x, y and
     203                                      // z
    194204                                     );
    195205
    196206/** 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                    );
     207double psDPolynomial1DEval(double x,    // /< Value at which to evaluate
     208                           const psDPolynomial1D * myPoly       // /< Coefficients for the polynomial
     209                          );
    201210
    202211/** 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                    );
     212double 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                          );
    208216
    209217/** 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                    );
     218double 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                          );
    216223
    217224/** 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
     225double 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
    227233
    228234#endif
  • trunk/psLib/src/math/psSpline.c

    r1406 r1407  
     1
    12/** @file  psFunctions.c
    23 *
     
    78 *  polynomials.  It also contains a Gaussian functions.
    89 *
    9  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    10  *  @date $Date: 2004-08-06 22:34:05 $
     10 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     11 *  @date $Date: 2004-08-07 00:06:06 $
    1112 *
    1213 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1314 */
    14 /*****************************************************************************/
     15
     16/*****************************************************************************/
     17
    1518/*  INCLUDE FILES                                                            */
     19
    1620/*****************************************************************************/
    1721#include <stdlib.h>
     
    3135#include <gsl/gsl_rng.h>
    3236#include <gsl/gsl_randist.h>
    33 /*****************************************************************************/
     37
     38/*****************************************************************************/
     39
    3440/* DEFINE STATEMENTS                                                         */
     41
    3542/*****************************************************************************/
    3643
     
    3845
    3946/*****************************************************************************/
     47
    4048/* 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/*****************************************************************************/
     51static void polynomial1DFree(psPolynomial1D * myPoly);
     52static void polynomial2DFree(psPolynomial2D * myPoly);
     53static void polynomial3DFree(psPolynomial3D * myPoly);
     54static void polynomial4DFree(psPolynomial4D * myPoly);
     55static void dPolynomial1DFree(psDPolynomial1D * myPoly);
     56static void dPolynomial2DFree(psDPolynomial2D * myPoly);
     57static void dPolynomial3DFree(psDPolynomial3D * myPoly);
     58static void dPolynomial4DFree(psDPolynomial4D * myPoly);
     59
     60/*****************************************************************************/
     61
    5262/* GLOBAL VARIABLES                                                          */
     63
    5364/*****************************************************************************/
    5465
     
    5667
    5768/*****************************************************************************/
     69
    5870/* FILE STATIC VARIABLES                                                     */
     71
    5972/*****************************************************************************/
    6073
     
    6275
    6376/*****************************************************************************/
     77
    6478/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     79
    6580/*****************************************************************************/
    6681
     
    6883
    6984/*****************************************************************************/
     85
    7086/*  FUNCTION IMPLEMENTATION - PUBLIC                                         */
     87
    7188/*****************************************************************************/
    7289
     
    7693    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f]
    7794 *****************************************************************************/
    78 float
    79 psGaussian(float x,
    80            float mean,
    81            float sigma,
    82            bool  normal)
     95float psGaussian(float x, float mean, float sigma, bool normal)
    8396{
    8497    float tmp = 1.0;
     
    94107    }
    95108
    96     return(tmp * exp(-((x-mean) * (x-mean)) / (2.0 * sigma * sigma)));
     109    return (tmp * exp(-((x - mean) * (x - mean)) / (2.0 * sigma * sigma)));
    97110}
    98111
     
    107120 NOTE: There is no way to seed the random generator.
    108121 *****************************************************************************/
    109 psVector *psGaussianDev(float mean,
    110                         float sigma,
    111                         int Npts)
     122psVector *psGaussianDev(float mean, float sigma, int Npts)
    112123{
    113124    psVector *gauss = NULL;
     
    127138
    128139    // NOTE: Should I free r as well?
    129     return(gauss);
    130 }
    131 
     140    return (gauss);
     141}
    132142
    133143/*****************************************************************************
     
    140150
    141151    newPoly = (psPolynomial1D *) psAlloc(sizeof(psPolynomial1D));
    142     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial1DFree);
     152    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial1DFree);
    143153    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++) {
    148158        newPoly->coeff[i] = 0.0;
    149159        newPoly->coeffErr[i] = 0.0;
     
    151161    }
    152162
    153     return(newPoly);
     163    return (newPoly);
    154164}
    155165
     
    161171
    162172    newPoly = (psPolynomial2D *) psAlloc(sizeof(psPolynomial2D));
    163     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial2DFree);
     173    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial2DFree);
    164174    newPoly->nX = nX;
    165175    newPoly->nY = nY;
    166176
    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++) {
    177187            newPoly->coeff[x][y] = 0.0;
    178188            newPoly->coeffErr[x][y] = 0.0;
     
    181191    }
    182192
    183     return(newPoly);
     193    return (newPoly);
    184194}
    185195
     
    192202
    193203    newPoly = (psPolynomial3D *) psAlloc(sizeof(psPolynomial3D));
    194     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial3DFree);
     204    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial3DFree);
    195205    newPoly->nX = nX;
    196206    newPoly->nY = nY;
    197207    newPoly->nZ = nZ;
    198208
    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++) {
    215225                newPoly->coeff[x][y][z] = 0.0;
    216226                newPoly->coeffErr[x][y][z] = 0.0;
     
    220230    }
    221231
    222     return(newPoly);
     232    return (newPoly);
    223233}
    224234
     
    232242
    233243    newPoly = (psPolynomial4D *) psAlloc(sizeof(psPolynomial4D));
    234     p_psMemSetDeallocator(newPoly,(psFreeFcn)polynomial4DFree);
     244    p_psMemSetDeallocator(newPoly, (psFreeFcn) polynomial4DFree);
    235245    newPoly->nW = nW;
    236246    newPoly->nX = nX;
     
    238248    newPoly->nZ = nZ;
    239249
    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++) {
    262272                    newPoly->coeff[w][x][y][z] = 0.0;
    263273                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    268278    }
    269279
    270     return(newPoly);
    271 }
    272 
    273 static void polynomial1DFree(psPolynomial1D *myPoly)
     280    return (newPoly);
     281}
     282
     283static void polynomial1DFree(psPolynomial1D * myPoly)
    274284{
    275285    psFree(myPoly->coeff);
     
    278288}
    279289
    280 static void polynomial2DFree(psPolynomial2D *myPoly)
    281 {
    282     int x = 0;
    283 
    284     for (x=0;x<myPoly->nX;x++) {
     290static void polynomial2DFree(psPolynomial2D * myPoly)
     291{
     292    int x = 0;
     293
     294    for (x = 0; x < myPoly->nX; x++) {
    285295        psFree(myPoly->coeff[x]);
    286296        psFree(myPoly->coeffErr[x]);
     
    292302}
    293303
    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++) {
     304static 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++) {
    301311            psFree(myPoly->coeff[x][y]);
    302312            psFree(myPoly->coeffErr[x][y]);
     
    313323}
    314324
    315 static void polynomial4DFree(psPolynomial4D *myPoly)
     325static void polynomial4DFree(psPolynomial4D * myPoly)
    316326{
    317327    int w = 0;
     
    319329    int y = 0;
    320330
    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++) {
    324334                psFree(myPoly->coeff[w][x][y]);
    325335                psFree(myPoly->coeffErr[w][x][y]);
     
    343353    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    344354 *****************************************************************************/
    345 float
    346 psPolynomial1DEval(float x,
    347                    const psPolynomial1D *myPoly)
     355float psPolynomial1DEval(float x, const psPolynomial1D * myPoly)
    348356{
    349357    int loop_x = 0;
     
    355363    }
    356364
    357 
    358365    // NOTE: Do we want to flag this case?
    359366    if (myPoly->n == 0) {
    360         return(1.0);
     367        return (1.0);
    361368    }
    362369
     
    365372    }
    366373
    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
     382float psPolynomial2DEval(float x, float y, const psPolynomial2D * myPoly)
    380383{
    381384    int loop_x = 0;
     
    385388    float ySum = 1.0;
    386389
    387     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     390    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    388391        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
     402float psPolynomial3DEval(float x, float y, float z, const psPolynomial3D * myPoly)
    404403{
    405404    int loop_x = 0;
     
    411410    float zSum = 1.0;
    412411
    413     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     412    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    414413        ySum = xSum;
    415         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     414        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    416415            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
     428float psPolynomial4DEval(float w, float x, float y, float z, const psPolynomial4D * myPoly)
    435429{
    436430    int loop_w = 0;
     
    444438    float zSum = 1.0;
    445439
    446     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     440    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    447441        xSum = wSum;
    448         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     442        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    449443            ySum = xSum;
    450             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     444            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    451445                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;
    456449                }
    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}
    469459
    470460psDPolynomial1D *psDPolynomial1DAlloc(int n)
     
    474464
    475465    newPoly = (psDPolynomial1D *) psAlloc(sizeof(psDPolynomial1D));
    476     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial1DFree);
     466    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial1DFree);
    477467    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++) {
    482472        newPoly->coeff[i] = 0.0;
    483473        newPoly->coeffErr[i] = 0.0;
     
    485475    }
    486476
    487     return(newPoly);
     477    return (newPoly);
    488478}
    489479
     
    495485
    496486    newPoly = (psDPolynomial2D *) psAlloc(sizeof(psDPolynomial2D));
    497     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial2DFree);
     487    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial2DFree);
    498488    newPoly->nX = nX;
    499489    newPoly->nY = nY;
    500490
    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++) {
    511501            newPoly->coeff[x][y] = 0.0;
    512502            newPoly->coeffErr[x][y] = 0.0;
     
    515505    }
    516506
    517     return(newPoly);
     507    return (newPoly);
    518508}
    519509
     
    526516
    527517    newPoly = (psDPolynomial3D *) psAlloc(sizeof(psDPolynomial3D));
    528     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial3DFree);
     518    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial3DFree);
    529519    newPoly->nX = nX;
    530520    newPoly->nY = nY;
    531521    newPoly->nZ = nZ;
    532522
    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++) {
    549539                newPoly->coeff[x][y][z] = 0.0;
    550540                newPoly->coeffErr[x][y][z] = 0.0;
     
    554544    }
    555545
    556     return(newPoly);
     546    return (newPoly);
    557547}
    558548
     
    566556
    567557    newPoly = (psDPolynomial4D *) psAlloc(sizeof(psDPolynomial4D));
    568     p_psMemSetDeallocator(newPoly,(psFreeFcn)dPolynomial4DFree);
     558    p_psMemSetDeallocator(newPoly, (psFreeFcn) dPolynomial4DFree);
    569559    newPoly->nW = nW;
    570560    newPoly->nX = nX;
     
    572562    newPoly->nZ = nZ;
    573563
    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++) {
    596586                    newPoly->coeff[w][x][y][z] = 0.0;
    597587                    newPoly->coeffErr[w][x][y][z] = 0.0;
     
    602592    }
    603593
    604     return(newPoly);
    605 }
    606 
    607 static void dPolynomial1DFree(psDPolynomial1D *myPoly)
     594    return (newPoly);
     595}
     596
     597static void dPolynomial1DFree(psDPolynomial1D * myPoly)
    608598{
    609599    psFree(myPoly->coeff);
     
    612602}
    613603
    614 static void dPolynomial2DFree(psDPolynomial2D *myPoly)
    615 {
    616     int x = 0;
    617 
    618     for (x=0;x<myPoly->nX;x++) {
     604static void dPolynomial2DFree(psDPolynomial2D * myPoly)
     605{
     606    int x = 0;
     607
     608    for (x = 0; x < myPoly->nX; x++) {
    619609        psFree(myPoly->coeff[x]);
    620610        psFree(myPoly->coeffErr[x]);
     
    626616}
    627617
    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++) {
     618static 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++) {
    635625            psFree(myPoly->coeff[x][y]);
    636626            psFree(myPoly->coeffErr[x][y]);
     
    647637}
    648638
    649 static void dPolynomial4DFree(psDPolynomial4D *myPoly)
     639static void dPolynomial4DFree(psDPolynomial4D * myPoly)
    650640{
    651641    int w = 0;
     
    653643    int y = 0;
    654644
    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++) {
    658648                psFree(myPoly->coeff[w][x][y]);
    659649                psFree(myPoly->coeffErr[w][x][y]);
     
    677667    Polynomial coefficients will be accessed in [w][x][y][z] fashion.
    678668 *****************************************************************************/
    679 double
    680 psDPolynomial1DEval(double x,
    681                     const psDPolynomial1D *myPoly)
     669double psDPolynomial1DEval(double x, const psDPolynomial1D * myPoly)
    682670{
    683671    int loop_x = 0;
     
    687675    // NOTE: Do we want to flag this case?
    688676    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
     688double psDPolynomial2DEval(double x, double y, const psDPolynomial2D * myPoly)
    705689{
    706690    int loop_x = 0;
     
    710694    double ySum = 1.0;
    711695
    712     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     696    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    713697        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
     708double psDPolynomial3DEval(double x, double y, double z, const psDPolynomial3D * myPoly)
    729709{
    730710    int loop_x = 0;
     
    736716    double zSum = 1.0;
    737717
    738     for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     718    for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    739719        ySum = xSum;
    740         for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     720        for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    741721            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
     734double psDPolynomial4DEval(double w, double x, double y, double z, const psDPolynomial4D * myPoly)
    760735{
    761736    int loop_w = 0;
     
    769744    double zSum = 1.0;
    770745
    771     for (loop_w=0;loop_w<myPoly->nW;loop_w++) {
     746    for (loop_w = 0; loop_w < myPoly->nW; loop_w++) {
    772747        xSum = wSum;
    773         for (loop_x=0;loop_x<myPoly->nX;loop_x++) {
     748        for (loop_x = 0; loop_x < myPoly->nX; loop_x++) {
    774749            ySum = xSum;
    775             for (loop_y=0;loop_y<myPoly->nY;loop_y++) {
     750            for (loop_y = 0; loop_y < myPoly->nY; loop_y++) {
    776751                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;
    781755                }
    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
    12/** @file psFunctions.h
    23*  \brief Standard Mathematical Functions.
     
    1213*  @author George Gusciora, MHPCC
    1314*
    14 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    15 *  @date $Date: 2004-08-06 22:34:05 $
     15*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     16*  @date $Date: 2004-08-07 00:06:06 $
    1617*
    1718*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#if !defined(PS_FUNCTIONS_H)
    21 #define PS_FUNCTIONS_H
    22 
    23 #include <stdbool.h>
    24 
    25 #include "psVector.h"
     22#    define PS_FUNCTIONS_H
     23
     24#    include <stdbool.h>
     25
     26#    include "psVector.h"
    2627
    2728/** \addtogroup Stats
     
    3334    evaluated Gaussian is: \f[ exp(-\frac{(x-mean)^2}{2\sigma^2}) \f] */
    3435
    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 
     36float 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                );
    4241
    4342/** Produce a vector of random numbers from a Gaussian distribution with
    4443    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 
     44psVector *psGaussianDev(float mean,     // /< The mean of the Gaussian
     45                        float sigma,    // /< The sigma of the Gaussian
     46                        int Npts);      // /< The size of the vector
    5247
    5348/** One-dimensional polynomial */
    5449typedef struct
    5550{
    56     int n;           ///< Number of terms
    57     float *coeff;    ///< Coefficients
    58     float *coeffErr; ///< Error in coefficients
    59     char *mask;      ///< Coefficient mask
     51    int n;                      // /< Number of terms
     52    float *coeff;               // /< Coefficients
     53    float *coeffErr;            // /< Error in coefficients
     54    char *mask;                 // /< Coefficient mask
    6055}
    6156psPolynomial1D;
     
    6459typedef struct
    6560{
    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
    7066}
    7167psPolynomial2D;
     
    7470typedef struct
    7571{
    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
    8078}
    8179psPolynomial3D;
     
    8482typedef struct
    8583{
    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
    9091}
    9192psPolynomial4D;
    9293
    93 
    9494/** Functions **************************************************************/
    9595
    9696/** 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
     97psPolynomial1D *psPolynomial1DAlloc(int n       // /< Number of terms
     98                                   );
     99
     100/** Constructor */
     101psPolynomial2D *psPolynomial2DAlloc(int nX, int nY      // /< Number of terms in x and y
     102                                   );
     103
     104/** Constructor */
     105psPolynomial3D *psPolynomial3DAlloc(int nX, int nY, int nZ      // /< Number of terms in x, y and z
     106                                   );
     107
     108/** Constructor */
     109psPolynomial4D *psPolynomial4DAlloc(int nW, int nX, int nY, int nZ      // /< Number of terms in w, x, y and
     110                                    // z
    107111                                   );
    108112
    109113/** Evaluate 1D polynomial */
    110 float
    111 psPolynomial1DEval( float x,   ///< Value at which to evaluate
    112                     const psPolynomial1D *myPoly ///< Coefficients for the polynomial
    113                   );
     114float psPolynomial1DEval(float x,       // /< Value at which to evaluate
     115                         const psPolynomial1D * myPoly  // /< Coefficients for the polynomial
     116                        );
    114117
    115118/** 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                   );
     119float 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                        );
    121123
    122124/** 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                   );
     125float 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                        );
    129130
    130131/** 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                   );
     132float 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                        );
    138138
    139139/*****************************************************************************/
     
    144144typedef struct
    145145{
    146     int n;    ///< Number of terms
    147     double *coeff;   ///< Coefficients
    148     double *coeffErr;   ///< Error in coefficients
    149     char *mask;    ///< Coefficient mask
     146    int n;                      // /< Number of terms
     147    double *coeff;              // /< Coefficients
     148    double *coeffErr;           // /< Error in coefficients
     149    char *mask;                 // /< Coefficient mask
    150150}
    151151psDPolynomial1D;
     
    154154typedef struct
    155155{
    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
    160161}
    161162psDPolynomial2D;
     
    164165typedef struct
    165166{
    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
    170173}
    171174psDPolynomial3D;
     
    174177typedef struct
    175178{
    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
    180186}
    181187psDPolynomial4D;
    182188
    183189/** 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
     190psDPolynomial1D *psDPolynomial1DAlloc(int n     // /< Number of terms
     191                                     );
     192
     193/** Constructor */
     194psDPolynomial2D *psDPolynomial2DAlloc(int nX, int nY    // /< Number of terms in x and y
     195                                     );
     196
     197/** Constructor */
     198psDPolynomial3D *psDPolynomial3DAlloc(int nX, int nY, int nZ    // /< Number of terms in x, y and z
     199                                     );
     200
     201/** Constructor */
     202psDPolynomial4D *psDPolynomial4DAlloc(int nW, int nX, int nY, int nZ    // /< Number of terms in w, x, y and
     203                                      // z
    194204                                     );
    195205
    196206/** 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                    );
     207double psDPolynomial1DEval(double x,    // /< Value at which to evaluate
     208                           const psDPolynomial1D * myPoly       // /< Coefficients for the polynomial
     209                          );
    201210
    202211/** 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                    );
     212double 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                          );
    208216
    209217/** 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                    );
     218double 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                          );
    216223
    217224/** 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
     225double 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
    227233
    228234#endif
  • trunk/psLib/src/math/psStats.c

    r1406 r1407  
     1
    12/** @file  psStats.c
    23 *  \brief basic statistical operations
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.51 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.52 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2122#include <float.h>
    2223#include <math.h>
     24
    2325/*****************************************************************************/
     26
    2427/* INCLUDE FILES                                                             */
     28
    2529/*****************************************************************************/
    2630#include "psMemory.h"
     
    3539
    3640/*****************************************************************************/
     41
    3742/* DEFINE STATEMENTS                                                         */
     43
    3844/*****************************************************************************/
    3945// 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.
    4147#define CLIPPED_NUM_ITER_LB 1
    4248#define CLIPPED_NUM_ITER_UB 10
     
    4854#define MAX_ITERATIONS 10
    4955
    50 void p_psVectorRobustStats( const psVector *restrict myVector,
    51                             const psVector *restrict maskVector,
    52                             unsigned int maskVal,
    53                             psStats *stats );
     56void p_psVectorRobustStats(const psVector * restrict myVector,
     57                           const psVector * restrict maskVector, unsigned int maskVal, psStats * stats);
    5458
    5559/** Preprocessor macro to generate error on an incorrect type */
     
    8387printf("\n"); \
    8488
     89
    8590/*****************************************************************************/
     91
    8692/* TYPE DEFINITIONS                                                          */
     93
    8794/*****************************************************************************/
    8895
    8996/*****************************************************************************/
     97
    9098/* GLOBAL VARIABLES                                                          */
     99
    91100/*****************************************************************************/
    92101
     
    94103
    95104/*****************************************************************************/
     105
    96106/* FILE STATIC VARIABLES                                                     */
     107
    97108/*****************************************************************************/
    98109
     
    100111
    101112/*****************************************************************************/
     113
    102114/* FUNCTION IMPLEMENTATION - LOCAL                                           */
     115
    103116/*****************************************************************************/
    104117
    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 ) ) {
     118bool 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)) {
    110122    case PS_STAT_SAMPLE_MEAN:
    111123        *value = stats->sampleMean;
     
    163175 *****************************************************************************/
    164176
    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 ] );
     177void 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]);
    175184        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]);
    177186    }
    178187}
     
    195204 *****************************************************************************/
    196205
    197 
    198206/******************************************************************************
    199207p_psVectorSampleMean(myVector, maskVector, maskVal, stats): calculates the
     
    210218 *****************************************************************************/
    211219
    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
     220void 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
    222228
    223229    // If PS_STAT_USE_RANGE is requested, then we enter a slightly different
    224230    // loop.
    225     if ( stats->options & PS_STAT_USE_RANGE ) {
     231    if (stats->options & PS_STAT_USE_RANGE) {
    226232        rangeMin = stats->min;
    227233        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++) {
    230236                // 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];
    235240                    count++;
    236241                }
    237242            }
    238             mean /= ( float ) count;
     243            mean /= (float)count;
    239244        } 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];
    244248                    count++;
    245249                }
    246250            }
    247             mean /= ( float ) count;
     251            mean /= (float)count;
    248252        }
    249253    } 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];
    254258                    count++;
    255259                }
    256260            }
    257             mean /= ( float ) count;
     261            mean /= (float)count;
    258262        } 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;
    263267        }
    264268    }
     
    278282    NULL
    279283 *****************************************************************************/
    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
     284void 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
    289291
    290292    // 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) {
    292294        rangeMin = stats->min;
    293295        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];
    301302                    }
    302303                }
    303304            }
    304305        } 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];
    310310                }
    311311            }
    312312        }
    313313    } 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];
    319319                    }
    320320                }
    321321            }
    322322        } 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];
    326326                }
    327327            }
     
    343343    NULL
    344344 *****************************************************************************/
    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 ) {
     345void 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) {
    356354        rangeMin = stats->min;
    357355        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];
    365362                    }
    366363                }
    367364            }
    368365        } 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];
    374370                }
    375371            }
    376372        }
    377373    } 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];
    383379                    }
    384380                }
    385381            }
    386382        } 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];
    390386                }
    391387            }
     
    408404    NULL
    409405 *****************************************************************************/
    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 ) {
     406int 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) {
    421415        rangeMin = stats->min;
    422416        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)) {
    428421                    numData++;
    429422                }
    430423            }
    431424        } 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)) {
    435427                    numData++;
    436428                }
     
    440432        rangeMin = stats->min;
    441433        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])) {
    445437                    numData++;
    446438                }
     
    450442        }
    451443    }
    452     return ( numData );
    453 }
    454 
    455 
     444    return (numData);
     445}
    456446
    457447/******************************************************************************
     
    466456    NULL
    467457 *****************************************************************************/
    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 
     458void 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
    481468
    482469    // Determine if the number of data points exceed a threshold which will
     
    485472    // regardless of the vector size.
    486473    /*
    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; } */
    506489
    507490    // Determine how many data points fit inside this min/max range
    508491    // 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);
    510493
    511494    // Allocate temporary vectors for the data.
    512     unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     495    unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    513496    unsortedVector->n = unsortedVector->nalloc;
    514497
    515     sortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     498    sortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    516499    sortedVector->n = sortedVector->nalloc;
    517500
    518501    // 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) {
    520503        rangeMin = stats->min;
    521504        rangeMax = stats->max;
     
    524507        // into the temporary vectors.
    525508        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];
    532514                }
    533515            }
    534516        } 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];
    539520                }
    540521            }
     
    543524        // Store all non-masked data points into the temporary vectors.
    544525        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];
    549530                }
    550531            }
    551532        } 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];
    554535            }
    555536        }
    556537    }
    557538    // Sort the temporary vectors.
    558     psVectorSort( sortedVector, unsortedVector );
     539    psVectorSort(sortedVector, unsortedVector);
    559540
    560541    // Calculate the median exactly.
    561542    // 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]);
    565546    } else {
    566         stats->sampleMedian = sortedVector->data.F32[ nValues / 2 ];
     547        stats->sampleMedian = sortedVector->data.F32[nValues / 2];
    567548    }
    568549
    569550    // Free the temporary data structures.
    570     psFree( unsortedVector );
    571     psFree( sortedVector );
     551    psFree(unsortedVector);
     552    psFree(sortedVector);
    572553}
    573554
     
    584565    XXX: use a static variable for gaussianCoefs[] and compute them once.
    585566 *****************************************************************************/
    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 ) {
     567psVector *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) {
    598578            // If sigma does not equal zero, then we use Gaussian smoothing.
    599579            #ifdef  DARWIN
    600             denom = ( float ) sqrt( 2.0 * M_PI * sigma * sigma );
     580            denom = (float)sqrt(2.0 * M_PI * sigma * sigma);
    601581            #else
    602582
    603             denom = sqrtf( 2.0 * M_PI * sigma * sigma );
     583            denom = sqrtf(2.0 * M_PI * sigma * sigma);
    604584            #endif
    605585
    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);
    609589
    610590            // NOTE: Gaussian smoothing just isn't working with low sigma
     
    612592            // all zero, except for the middle coefficient, which is exactly
    613593            // 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]);
    616596        } 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);
    625603        }
    626604    }
    627605
    628606    // 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);
    639617}
    640618
     
    650628    NULL
    651629 *****************************************************************************/
    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
     630void 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
    664640
    665641    // Determine how many data points fit inside this min/max range
    666642    // 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);
    668644
    669645    // Allocate temporary vectors for the data.
    670     unsortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     646    unsortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    671647    unsortedVector->n = unsortedVector->nalloc;
    672     sortedVector = psVectorAlloc( nValues, PS_TYPE_F32 );
     648    sortedVector = psVectorAlloc(nValues, PS_TYPE_F32);
    673649    sortedVector->n = sortedVector->nalloc;
    674650
    675651    // 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) {
    677653        rangeMin = stats->min;
    678654        rangeMax = stats->max;
     
    680656        // into the temporary vectors.
    681657        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];
    688663                }
    689664            }
    690665        } 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];
    695669                }
    696670            }
     
    699673        // Store all non-masked data points into the temporary vectors.
    700674        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];
    705679                }
    706680            }
    707681        } 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];
    710684            }
    711685        }
     
    713687
    714688    // Sort the temporary vectors.
    715     psVectorSort( sortedVector, unsortedVector );
     689    psVectorSort(sortedVector, unsortedVector);
    716690
    717691    // 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];
    720694
    721695    // Free the temporary data structures.
    722     psFree( unsortedVector );
    723     psFree( sortedVector );
    724 }
    725 
     696    psFree(unsortedVector);
     697    psFree(sortedVector);
     698}
    726699
    727700/******************************************************************************
     
    737710 
    738711 *****************************************************************************/
    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
     712void 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
    753724
    754725    // This procedure requires the mean.  If it has not been already
    755726    // 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);
    758729    }
    759730    mean = stats->sampleMean;
    760731
    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);
    769739                    sumDiffs += diff;
    770740                    countInt++;
     
    772742            }
    773743        } 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);
    779748                    sumDiffs += diff;
    780749                    countInt++;
     
    784753        }
    785754    } 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);
    791760                    sumDiffs += diff;
    792761                    countInt++;
     
    794763            }
    795764        } 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);
    799768                sumDiffs += diff;
    800769                countInt++;
     
    803772        }
    804773    }
    805     countFloat = ( float ) countInt;
     774    countFloat = (float)countInt;
    806775
    807776    #ifdef DARWIN
    808777
    809     stats->sampleStdev = ( float ) sqrt( ( sumSquares - ( sumDiffs *
    810                                            sumDiffs / countFloat ) ) / ( countFloat - 1 ) );
     778    stats->sampleStdev = (float)sqrt((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1));
    811779    #else
    812780
    813     stats->sampleStdev = sqrtf( ( sumSquares - ( sumDiffs *
    814                                   sumDiffs / countFloat ) ) / ( countFloat - 1 ) );
     781    stats->sampleStdev = sqrtf((sumSquares - (sumDiffs * sumDiffs / countFloat)) / (countFloat - 1));
    815782    #endif
    816783}
     
    828795    NULL
    829796 *****************************************************************************/
    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
     797void 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
    842807
    843808    // 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    }
    850812    // 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    }
    857816    // We allocate a temporary mask vector since during the iterative
    858817    // steps that follow, we will be masking off additional data points.
    859818    // 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);
    861820    tmpMask->n = myVector->n;
    862821
    863822    // If we were called with a mask vector, then initialize the temporary
    864823    // 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    }
    871829    // 1. Compute the sample median.
    872830    // NOTE: This seems odd.  Verify with IfA that we want to calculate the
    873831    // median here, not the mean.
    874     p_psVectorSampleMedian( myVector, maskVector, maskVal, stats );
     832    p_psVectorSampleMedian(myVector, maskVector, maskVal, stats);
    875833
    876834    // 2. Compute the sample standard deviation.
    877     p_psVectorSampleStdev( myVector, maskVector, maskVal, stats );
     835    p_psVectorSampleStdev(myVector, maskVector, maskVal, stats);
    878836
    879837    // 3. Use the sample median as the first estimator of the mean X.
     
    889847
    890848    // 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++) {
    893851            // 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;
    897854            }
    898855            // 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);
    901858
    902859            // c) Use the new mean for x
     
    912869
    913870    // 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) {
    915872        stats->clippedMean = clippedMean;
    916873    }
    917 
    918874    // 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) {
    920876        stats->clippedStdev = clippedStdev;
    921877    }
    922878
    923     psFree( tmpMask );
     879    psFree(tmpMask);
    924880}
    925881
     
    928884elements of a vector to a range between 0.0 and 1.0.
    929885 *****************************************************************************/
    930 void p_psNormalizeVector( psVector *myData )
    931 {
    932     float min = ( float ) HUGE;
    933     float max = ( float ) - HUGE;
     886void p_psNormalizeVector(psVector * myData)
     887{
     888    float min = (float)HUGE;
     889    float max = (float)-HUGE;
    934890    float range = 0.0;
    935891    int i = 0;
    936892
    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];
    943899        }
    944900    }
    945901
    946902    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}
    952907
    953908/*****************************************************************************
     
    956911specified data point.
    957912 *****************************************************************************/
    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 );
     913float 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);
    969924}
    970925
     
    973928calculates the specified partial derivative of the above Gaussian function.
    974929 *****************************************************************************/
    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 ];
     930float 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];
    982935    float tmp = 0.0;
    983936
    984     if ( whichParam == 0 ) {
     937    if (whichParam == 0) {
    985938        // 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}
    999950
    1000951/*****************************************************************************
     
    1003954specified data point.
    1004955 *****************************************************************************/
    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 ];
     956float 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];
    1012962    float tmp = 0.0;
    1013963
    1014     tmp = ( A * x * x ) + ( B * x ) + C;
    1015     return ( tmp );
     964    tmp = (A * x * x) + (B * x) + C;
     965    return (tmp);
    1016966}
    1017967
     
    1020970calculates the specified partial derivative of the above quadratic function.
    1021971 *****************************************************************************/
    1022 float p_psQuadraticDeriv( const psVector *restrict myParams,
    1023                           const psVector *restrict myCoords,
    1024                           int whichParamDeriv )
    1025 {
    1026     float x = myCoords->data.F32[ 0 ];
     972float p_psQuadraticDeriv(const psVector * restrict myParams,
     973                         const psVector * restrict myCoords, int whichParamDeriv)
     974{
     975    float x = myCoords->data.F32[0];
    1027976    float tmp = 0.0;
    1028977
    1029     if ( whichParamDeriv == 0 ) {
     978    if (whichParamDeriv == 0) {
    1030979        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);
    1040987}
    1041988
     
    1049996decreasing within that range.
    1050997 *****************************************************************************/
    1051 float p_ps1DPolyMedian( psPolynomial1D *myPoly,
    1052                         float rangeLow,
    1053                         float rangeHigh,
    1054                         float getThisValue )
     998float p_ps1DPolyMedian(psPolynomial1D * myPoly, float rangeLow, float rangeHigh, float getThisValue)
    1055999{
    10561000    int numIterations = 0;
     
    10591003    float f = 0.0;
    10601004
    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);
    10671011        }
    10681012        oldMidpoint = midpoint;
    10691013
    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) {
    10771021            rangeHigh = midpoint;
    10781022        } else {
     
    10811025        numIterations++;
    10821026    }
    1083     return ( midpoint );
     1027    return (midpoint);
    10841028}
    10851029
     
    10921036XXX: This function is currently not being used.
    10931037 *****************************************************************************/
    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 ) );
     1038float 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));
    11321067    } 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);
    11421076}
    11431077
     
    11661100    NULL
    11671101*****************************************************************************/
    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;
     1102void p_psVectorRobustStats(const psVector * restrict myVector,
     1103                           const psVector * restrict maskVector, unsigned int maskVal, psStats * stats)
     1104{
     1105    psHistogram *robustHistogram = NULL;
    11741106    psVector *robustHistogramVector = NULL;
    1175     float binSize = 0.0;                        // Size of the histogram bins
    1176     int LQBinNum = -1;                          // Bin num for lower quartile
    1177     int UQBinNum = -1;                          // Bin num for upper quartile
    1178     int i = 0;                                  // Loop index variable
     1107    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
    11791111    int maxBinNum = 0;
    11801112    float maxBinCount = 0.0;
    11811113    float dL = 0.0;
    11821114    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;
    11921125    float myMean = 0.0;
    11931126    float myStdev = 0.0;
     
    11961129    float sumSquares = 0.0;
    11971130    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);
    12021135    psVector *cumulativeRobustSumsFullRange = NULL;
    12031136    psVector *cumulativeRobustSumsDlRange = NULL;
     
    12101143    // by computing the clipped standard deviation of the vector, and dividing
    12111144    // that by 10.0;
    1212     p_psVectorClippedStats( myVector, maskVector, maskVal, tmpStats );
     1145    p_psVectorClippedStats(myVector, maskVector, maskVal, tmpStats);
    12131146    binSize = tmpStats->clippedStdev / 10.0f;
    12141147
    12151148    // If stats->clippedStdev == 0.0, then all data elements have the same
    12161149    // 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) {
    12191152            stats->robustMean = stats->clippedMean;
    12201153        }
    1221         if ( stats->options & PS_STAT_ROBUST_MEDIAN ) {
     1154        if (stats->options & PS_STAT_ROBUST_MEDIAN) {
    12221155            stats->robustMedian = stats->clippedMean;
    12231156        }
    1224         if ( stats->options & PS_STAT_ROBUST_MODE ) {
     1157        if (stats->options & PS_STAT_ROBUST_MODE) {
    12251158            stats->robustMode = stats->clippedMean;
    12261159        }
    1227         if ( stats->options & PS_STAT_ROBUST_STDEV ) {
     1160        if (stats->options & PS_STAT_ROBUST_STDEV) {
    12281161            stats->robustStdev = 0.0;
    12291162        }
    1230         if ( stats->options & PS_STAT_ROBUST_QUARTILE ) {
     1163        if (stats->options & PS_STAT_ROBUST_QUARTILE) {
    12311164            stats->robustUQ = stats->clippedMean;
    12321165            stats->robustLQ = stats->clippedMean;
     
    12351168        stats->robustNfit = 0.0;
    12361169        stats->robustN50 = 0.0;
    1237         psFree( tmpStats );
    1238         return ;
    1239     }
    1240 
     1170        psFree(tmpStats);
     1171        return;
     1172    }
    12411173    // 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    }
    12491180    // Create the histogram structure.  NOTE: we can not specify the bin size
    12501181    // precisely since the argument to psHistogramAlloc() is the number of
    12511182    // bins, not the binSize.  Also, if we get here, we know that
    12521183    // 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);
    12571186
    12581187    // Populate the histogram array.
    1259     psVectorHistogram( robustHistogram, myVector, maskVector, maskVal );
     1188    psVectorHistogram(robustHistogram, myVector, maskVector, maskVal);
    12601189
    12611190    // Smooth the histogram.
    12621191    // 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);
    12651193
    12661194    // The following was necessary to fit a gaussian to the data, since
     
    12741202    // index position i is equal to the sum of bins 0:i.  This will be used
    12751203    // 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];
    12841211
    12851212    // Determine the bin number containing the lower quartile point.
    12861213    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)) {
    12891216            LQBinNum = i;
    12901217            break;
     
    12941221    // Determine the bin number containing the upper quartile point.
    12951222    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)) {
    12981225            UQBinNum = i;
    12991226            break;
     
    13011228    }
    13021229
    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
    13071234    /**************************************************************************
    13081235    Determine the mode in the range LQ:UQ.
     
    13101237    // Determine the bin with the peak value in the range LQ to UQ.
    13111238    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) {
    13161243            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];
    13201247    }
    13211248
    13221249    // 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);
    13261253
    13271254    /**************************************************************************
    13281255    Determine the mean/stdev for the bins in the range mode-dL to mode+dL
    13291256    **************************************************************************/
    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;
    13331260    }
    13341261    sumNfit = 0.0;
    13351262    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];
    13431269        }
    13441270    }
     
    13481274    // that bin (this is a non-exact approximation).
    13491275    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];
    13561281        }
    13571282    }
     
    13611286    // mode-dL to mode+dL.  We use the midpoint of each bin as the mean for
    13621287    // 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));
    13721297
    13731298    /**************************************************************************
    13741299    Set the appropriate members in the output stats struct.
    13751300    **************************************************************************/
    1376     if ( stats->options & PS_STAT_ROBUST_MEAN ) {
     1301    if (stats->options & PS_STAT_ROBUST_MEAN) {
    13771302        stats->robustMean = myMean;
    13781303    }
    13791304
    1380     if ( stats->options & PS_STAT_ROBUST_MODE ) {
     1305    if (stats->options & PS_STAT_ROBUST_MODE) {
    13811306        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) {
    13871311        stats->robustStdev = myStdev;
    13881312    }
    1389 
    13901313    // To determine the median (and later, the lower/upper quartile), we fit
    13911314    // a quadratic to the three bins surrounding the bin containing the median.
     
    13941317    // this bin.  We then solve the quadratic for
    13951318
    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];
    14111334
    14121335            // Ensure that cumulativeMedian/2 is actually within the range of the bins
    14131336            // we are using.
    14141337            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");
    14191341            }
    14201342            // XXX: yErr is not currently used by psVectorFitPolynomial1D().  We
    14211343            // 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;
    14251347
    14261348            // Determine the coefficients of the polynomial.
    1427             myPoly = psVectorFitPolynomial1D( myPoly, x, y, yErr );
     1349            myPoly = psVectorFitPolynomial1D(myPoly, x, y, yErr);
    14281350            // Call p_ps1DPolyMedian(), which does a binary search on the
    14291351            // polynomial, looking for the value x such that
    14301352            // 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);
    14331354        } else {
    14341355            // If the mode is the first/last histogram bin, then simply use
    14351356            // 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    }
    14411361    // The lower/upper quartile calculations are very similar to the median
    14421362    // calculations.  We fit a quadratic to the array containing the
     
    14441364    // f(x) equals the lower/upper quartile exactly.
    14451365    //
    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);
    14781394
    14791395        } else {
    14801396            // If the LQ is the first/last histogram bin, then simply use
    14811397            // 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);
    15151429        } else {
    15161430            // If the UQ is the first/last histogram bin, then simply use
    15171431            // 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]);
    15201434        }
    15211435    }
     
    15231437    stats->robustN50 = sumN50;
    15241438
    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}
    15361448
    15371449/*
     
    15821494*/
    15831495
    1584 
    15851496/*****************************************************************************/
     1497
    15861498/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     1499
    15871500/*****************************************************************************/
    15881501
    1589 static void histogramFree( psHistogram *myHist );
     1502static void histogramFree(psHistogram * myHist);
    15901503
    15911504/******************************************************************************
    15921505    psStatsAlloc(): This routine must create a new psStats data structure.
    15931506 *****************************************************************************/
    1594 psStats *psStatsAlloc( psStatsOptions options )
    1595 {
    1596     psStats * newStruct = NULL;
    1597 
    1598     newStruct = ( psStats * ) psAlloc( sizeof( psStats ) );
     1507psStats *psStatsAlloc(psStatsOptions options)
     1508{
     1509    psStats *newStruct = NULL;
     1510
     1511    newStruct = (psStats *) psAlloc(sizeof(psStats));
    15991512    newStruct->sampleMean = NAN;
    16001513    newStruct->sampleMedian = NAN;
     
    16201533    newStruct->options = options;
    16211534
    1622     return ( newStruct );
     1535    return (newStruct);
    16231536}
    16241537
     
    16351548    The histogram structure
    16361549 *****************************************************************************/
    1637 psHistogram *psHistogramAlloc( float lower,
    1638                                float upper,
    1639                                int n )
    1640 {
    1641     int i = 0;                          // Loop index variable
     1550psHistogram *psHistogramAlloc(float lower, float upper, int n)
     1551{
     1552    int i = 0;                  // Loop index variable
    16421553    psHistogram *newHist = NULL;        // The new histogram structure
    1643     float binSize = 0.0;                // The histogram bin size
     1554    float binSize = 0.0;        // The histogram bin size
    16441555
    16451556    // 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    }
    16531563    // 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    }
    16581567    // Allocate memory for the new histogram structure.  If there are N
    16591568    // 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);
    16631572    newHist->bounds->n = newHist->bounds->nalloc;
    16641573
    16651574    // Calculate the bounds for each bin.
    1666     binSize = ( upper - lower ) / ( float ) n;
    1667     // NOTE: Is the following necessary?  It prevents the max data point
     1575    binSize = (upper - lower) / (float)n;
     1576    // NOTE: Is the following necessary? It prevents the max data point
    16681577    // from being in a non-existant bin.
    16691578    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);
    16721581    }
    16731582
    16741583    // Allocate the bins, and initialize them to zero.
    1675     newHist->nums = psVectorAlloc( n, PS_TYPE_U32 );
     1584    newHist->nums = psVectorAlloc(n, PS_TYPE_U32);
    16761585    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;
    16791588    }
    16801589
     
    16841593    newHist->uniform = true;
    16851594
    1686     return ( newHist );
     1595    return (newHist);
    16871596}
    16881597
     
    16961605    The histogram structure
    16971606 *****************************************************************************/
    1698 psHistogram *psHistogramAllocGeneric( const psVector *restrict bounds )
    1699 {
    1700     psHistogram * newHist = NULL;        // The new histogram structure
    1701     int i;                              // Loop index variable
     1607psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds)
     1608{
     1609    psHistogram *newHist = NULL;        // The new histogram structure
     1610    int i;                      // Loop index variable
    17021611
    17031612    // NOTE: Verify that this is the correct action.
    1704     if ( bounds == NULL ) {
     1613    if (bounds == NULL) {
    17051614        // psAbort(__func__, "psHistogram requested with NULL bounds");
    1706         return ( NULL );
    1707     }
    1708 
     1615        return (NULL);
     1616    }
    17091617    // NOTE: Verify that this is the correct action.
    1710     if ( bounds->n <= 1 ) {
     1618    if (bounds->n <= 1) {
    17111619        // 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) {
    17161624        // psAbort(__func__, "psHistogram request a bound which is not type F32");
    1717         return ( NULL );
    1718     }
    1719 
     1625        return (NULL);
     1626    }
    17201627    // 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);
    17241631    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];
    17271634    }
    17281635
    17291636    // Allocate the bins, and initialize them to zero.  If there are N bounds,
    17301637    // 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);
    17321639    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;
    17351642    }
    17361643
     
    17401647    newHist->uniform = false;
    17411648
    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
     1652static void histogramFree(psHistogram * myHist)
     1653{
     1654    psFree(myHist->bounds);
     1655    psFree(myHist->nums);
     1656}
    17511657
    17521658/*****************************************************************************
     
    17641670    The histogram structure "out".
    17651671 *****************************************************************************/
    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
     1672psHistogram *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
    17761681
    17771682    // 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    }
    17821686    // 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    }
    17931694    // 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");
    18111709        }
    18121710    }
     
    18151713
    18161714    numBins = out->nums->n;
    1817     for ( i = 0;i < in->n;i++ ) {
     1715    for (i = 0; i < in->n; i++) {
    18181716        // 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)))) {
    18211718            // Check if this pixel is below the minimum value, and if so
    18221719            // 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]) {
    18241721                out->minNum++;
    18251722                // Check if this pixel is above the maximum value, and if so
    18261723                // 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.
    18301744                } 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])++;
    18571751                        }
    18581752                    }
    18591753                }
    1860         }
    1861     }
    1862     return ( out );
     1754            }
     1755        }
     1756    }
     1757    return (out);
    18631758}
    18641759
     
    18721767the various stat functions.
    18731768 *****************************************************************************/
    1874 psVector *p_psConvertToF32( psStats *stats,
    1875                             psVector *in,
    1876                             psVector *mask,
    1877                             unsigned int maskVal )
     1769psVector *p_psConvertToF32(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal)
    18781770{
    18791771    int i = 0;
    18801772    psVector *tmp = NULL;
    18811773
    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}
    19081796
    19091797/******************************************************************************
     
    19241812macro-ize everything and add PS_TYPE_U16 and PS_TYPE_F64.
    19251813 *****************************************************************************/
    1926 psStats *psVectorStats( psStats *stats,
    1927                         psVector *in,
    1928                         psVector *mask,
    1929                         unsigned int maskVal )
    1930 {
    1931     psVector * inF32;
     1814psStats *psVectorStats(psStats * stats, psVector * in, psVector * mask, unsigned int maskVal)
     1815{
     1816    psVector *inF32;
    19321817    int mustFreeTmp = 1;
    19331818
    19341819    // 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) {
    19441829        inF32 = in;
    19451830        mustFreeTmp = 0;
    19461831    }
    1947 
    19481832    // 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    }
    19631843    // ************************************************************************
    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    }
    19681847    // ************************************************************************
    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    }
    19731851    // ************************************************************************
    19741852    // 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    }
    19811858    // ************************************************************************
    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    }
    19861862    // Since the various robust stats quantities share much computation, they
    19871863    // are grouped together in a single private function:
    19881864    // 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    }
    20021875    // ************************************************************************
    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    }
    20071879    // ************************************************************************
    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
    12/** @file  psStats.h
    23 *  \brief basic statistical operations
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    1617#if !defined(PS_STATS_H)
    17 #define PS_STATS_H
     18#    define PS_STATS_H
    1819
    19 #include "psVector.h"
     20#    include "psVector.h"
    2021
    2122/// @addtogroup Stats
     
    2627 *****************************************************************************/
    2728typedef 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     = 0x008000
     29    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
    4445} psStatsOptions;
    45 
    4646
    4747/** This is the generic statistics structure.  It contails the data members
     
    5050typedef struct
    5151{
    52     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
     52    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
    6464    double XXX;
    65     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
     65    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
    7575}
    7676psStats;
    7777
    78 
    7978/** 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              );
     79psStats *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                      );
    8686
    8787/** A constructor for the stats structure.*/
    88 psStats *psStatsAlloc(psStatsOptions options); ///< Statistics to measure
     88psStats *psStatsAlloc(psStatsOptions options);  // /< Statistics to measure
    8989
    9090/******************************************************************************
    9191    Histogram functions and data structures.
    9292 *****************************************************************************/
     93
    9394/** The basic histogram structure which contains bounds and bins. */
    9495typedef struct
    9596{
    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 minimum
    99     int maxNum;                      ///< Number above the maximum
    100     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?
    101102}
    102103psHistogram;
    103104
    104 
    105105/** 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 
     106psHistogram *psHistogramAlloc(float lower,      // /< Lower limit for the bins
     107                              float upper,      // /< Upper limit for the bins
     108                              int n);   // /< Number of bins
    111109
    112110/** Generic constructor \ingroup MathGroup */
    113 psHistogram * psHistogramAllocGeneric(const psVector *restrict bounds); ///< Bounds for the bins
     111psHistogram *psHistogramAllocGeneric(const psVector * restrict bounds); // /< Bounds for the bins
    114112
    115113/** Calculate a histogram \ingroup MathGroup **/
    116 psHistogram *psVectorHistogram (psHistogram *out,   ///< Histogram data
    117                                 const psVector *restrict in,       ///< Vector to analyse
    118                                 const psVector *restrict mask,     ///< Mask dat for input vector
    119                                 unsigned int maskVal);       ///< Mask value
     114psHistogram *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
    120118
    121 bool p_psGetStatValue(
    122     const psStats* stats,
    123     double* value
    124 );
     119bool p_psGetStatValue(const psStats * stats, double *value);
    125120
    126121/// @}
    127122
    128123#endif
    129 
  • trunk/psLib/src/mathtypes/psImage.c

    r1406 r1407  
     1
    12/** @file  psImage.c
    23 *
     
    910 *  @author Ross Harman, MHPCC
    1011 *
    11  *  @version $Revision: 1.37 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.38 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225
     
    2932#include "psImage.h"
    3033
    31 static void imageFree(psImage* image);
     34static void imageFree(psImage * image);
    3235
    3336/*****************************************************************************/
     37
    3438/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     39
    3540/*****************************************************************************/
    3641
    37 psImage *psImageAlloc(unsigned int numCols, unsigned int numRows,
    38                       const psElemType type)
     42psImage *psImageAlloc(unsigned int numCols, unsigned int numRows, const psElemType type)
    3943{
    4044    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;
    4556
    4657    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);
    4960        return NULL;
    5061    }
    5162
    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     if(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;
    8091    image->parent = NULL;
    8192    image->nChildren = 0;
     
    8596}
    8697
    87 static void imageFree(psImage* image)
     98static void imageFree(psImage * image)
    8899{
    89100    if (image == NULL) {
     
    92103
    93104    if (image->type.type == PS_TYPE_PTR) {
    94         // 2-D array of pointers -- must dereference
     105        // 2-D array of pointers -- must
     106        // dereference
    95107        unsigned int oldNumRows = image->numRows;
    96108        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++) {
    100112            rowPtr = image->data.PTR[row];
    101             for (unsigned int col=0;col<oldNumCols;col++) {
     113            for (unsigned int col = 0; col < oldNumCols; col++) {
    102114                psMemDecrRefCounter(rowPtr[col]);
    103115            }
     
    112124}
    113125
    114 psImage* psImageRecycle(psImage* old,
    115                         unsigned int numCols,
    116                         unsigned int numRows,
    117                         const psElemType type)
     126psImage *psImageRecycle(psImage * old, unsigned int numCols, unsigned int numRows, const psElemType type)
    118127{
    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.
    121137
    122138    if (old == NULL) {
    123         old = psImageAlloc(numCols,numRows,type);
     139        old = psImageAlloc(numCols, numRows, type);
    124140        return old;
    125141    }
    126142
    127143    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.");
    129145        return NULL;
    130146    }
    131147
    132148    if (old->type.type == PS_TYPE_PTR) {
    133         // 2-D array of pointers -- must dereference
     149        // 2-D array of pointers -- must
     150        // dereference
    134151        unsigned int oldNumRows = old->numRows;
    135152        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++) {
    139156            rowPtr = old->data.PTR[row];
    140             for (unsigned int col=0;col<oldNumCols;col++) {
     157            for (unsigned int col = 0; col < oldNumCols; col++) {
    141158                psMemDecrRefCounter(rowPtr[col]);
    142159                rowPtr[col] = NULL;
     
    146163
    147164    /* 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) {
    150166        return old;
    151167    }
    152 
    153168    // 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 *));
    156171
    157172    // 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;
    165180
    166181    return old;
    167182}
    168183
    169 int psImageFreeChildren(psImage* image)
     184int psImageFreeChildren(psImage * image)
    170185{
    171186    int i = 0;
     
    181196    children = image->children;
    182197
    183     for(i=0; i<nChildren; i++) {
     198    for (i = 0; i < nChildren; i++) {
    184199        if (children[i] != NULL) {
    185200            numFreed++;
     
    191206    image->nChildren = 0;
    192207    image->children = NULL;
    193 
    194208
    195209    return numFreed;
     
    202216linear interpolation is performed on the image.
    203217 *****************************************************************************/
    204 psF32 psImagePixelInterpolate(
    205     const psImage *input,
    206     float x,
    207     float y,
    208     psF32 unexposedValue,
    209     psImageInterpolateMode mode)
     218psF32 psImagePixelInterpolate(const psImage * input,
     219                              float x, float y, psF32 unexposedValue, psImageInterpolateMode mode)
    210220{
    211221
    212222    if (input == NULL) {
    213         psError(__func__,"Image can not be NULL.");
     223        psError(__func__, "Image can not be NULL.");
    214224        return unexposedValue;
    215225    }
    216 
    217226    #define PSIMAGE_PIXEL_INTERPOLATE_CASE(TYPE) \
    218227case PS_TYPE_##TYPE: \
     
    243252        PSIMAGE_PIXEL_INTERPOLATE_CASE(C64);
    244253    default:
    245         psError(__func__,"Unsupported image datatype (%d)",input->type.type);
     254        psError(__func__, "Unsupported image datatype (%d)", input->type.type);
    246255    }
    247256
     
    303312PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C32)
    304313PSIMAGE_PIXEL_INTERPOLATE_FLAT_COMPLEX(C64)
    305 
    306314#define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR(TYPE) \
    307315inline psF64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \
     
    359367    return(pixel); \
    360368}
    361 
    362369#define PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(TYPE) \
    363370inline psC64 p_psImagePixelInterpolateBILINEAR_##TYPE(const psImage *input, \
     
    428435PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C32)
    429436PSIMAGE_PIXEL_INTERPOLATE_BILINEAR_COMPLEX(C64)
    430 
    431 
  • trunk/psLib/src/mathtypes/psImage.h

    r1406 r1407  
     1
    12/** @file  psImage.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.27 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.28 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1718 */
    18 # ifndef PS_IMAGE_H
    19 # define PS_IMAGE_H
     19#ifndef PS_IMAGE_H
     20#    define PS_IMAGE_H
    2021
    21 #include <complex.h>
     22#    include <complex.h>
    2223
    23 #include "psType.h"
     24#    include "psType.h"
    2425
    2526/// @addtogroup Image
     
    3940typedef struct psImage
    4041{
    41     const psType type;                  ///< Image data type and dimension.
    42     const unsigned int numCols;         ///< Number of columns in image
    43     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.
    4647
    4748    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.
    6667}
    6768psImage;
    6869
    6970/*****************************************************************************/
     71
    7072/* FUNCTION PROTOTYPES                                                       */
     73
    7174/*****************************************************************************/
    72 
    7375
    7476/** Create an image of the specified size and type.
     
    8082 *
    8183 */
    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 );
     84psImage *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                     );
    8788
    8889/** Resize a given image to the given size/type.
     
    9192 *
    9293 */
    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 
     94psImage *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                       );
    10099
    101100/** Frees all children of a psImage.
     
    104103 *
    105104 */
    106 int psImageFreeChildren(
    107     psImage* image
    108     /**< psImage in which all children shall be deallocated */
    109 );
     105int psImageFreeChildren(psImage * image
    110106
    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                       );
    118109
    119 #define p_psImagePixelInterpolateFcns(TYPE) \
     110psF32 psImagePixelInterpolate(const psImage * input,
     111                              float x, float y, psF32 unexposedValue, psImageInterpolateMode mode);
     112
     113#    define p_psImagePixelInterpolateFcns(TYPE) \
    120114inline psF64 p_psImagePixelInterpolateFLAT_##TYPE( \
    121115        const psImage *input, \
     
    131125                                                     );
    132126
    133 #define p_psImagePixelInterpolateComplexFcns(TYPE) \
     127#    define p_psImagePixelInterpolateComplexFcns(TYPE) \
    134128inline psC64 p_psImagePixelInterpolateFLAT_##TYPE( \
    135129        const psImage *input, \
     
    157151p_psImagePixelInterpolateComplexFcns(C32)
    158152p_psImagePixelInterpolateComplexFcns(C64)
    159 
    160153/// @}
    161 
    162154#endif
  • trunk/psLib/src/mathtypes/psScalar.c

    r1406 r1407  
     1
    12/** @file  psScalar.c
    23 *
     
    89 *  @author Ross Harman, MHPCC
    910 *
    10  *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    1922#include "psMemory.h"
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873psScalar *psScalarAlloc(psC64 value, psElemType dataType)
     
    6176
    6277    // 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__);
    6681    }
    6782
     
    7186    switch (dataType) {
    7287    case PS_TYPE_S8:
    73         scalar->data.S8 = (psS8)value;
     88        scalar->data.S8 = (psS8) value;
    7489        break;
    7590    case PS_TYPE_U8:
    76         scalar->data.U8 = (psU8)value;
     91        scalar->data.U8 = (psU8) value;
    7792        break;
    7893    case PS_TYPE_S16:
    79         scalar->data.S16 = (psS16)value;
     94        scalar->data.S16 = (psS16) value;
    8095        break;
    8196    case PS_TYPE_U16:
    82         scalar->data.U16 = (psU16)value;
     97        scalar->data.U16 = (psU16) value;
    8398        break;
    8499    case PS_TYPE_S32:
    85         scalar->data.S32 = (psS32)value;
     100        scalar->data.S32 = (psS32) value;
    86101        break;
    87102    case PS_TYPE_U32:
    88         scalar->data.U32 = (psU32)value;
     103        scalar->data.U32 = (psU32) value;
    89104        break;
    90105    case PS_TYPE_S64:
    91         scalar->data.S64 = (psS64)value;
     106        scalar->data.S64 = (psS64) value;
    92107        break;
    93108    case PS_TYPE_U64:
    94         scalar->data.U64 = (psU64)value;
     109        scalar->data.U64 = (psU64) value;
    95110        break;
    96111    case PS_TYPE_F32:
    97         scalar->data.F32 = (psF32)value;
     112        scalar->data.F32 = (psF32) value;
    98113        break;
    99114    case PS_TYPE_F64:
    100         scalar->data.F64 = (psF64)value;
     115        scalar->data.F64 = (psF64) value;
    101116        break;
    102117    case PS_TYPE_C32:
    103         scalar->data.C32 = (psC32)value;
     118        scalar->data.C32 = (psC32) value;
    104119        break;
    105120    case PS_TYPE_C64:
    106         scalar->data.C64 = (psC64)value;
     121        scalar->data.C64 = (psC64) value;
    107122        break;
    108123    default:
     
    110125    }
    111126
    112 
    113127    return scalar;
    114128}
    115129
    116 void psScalarFree(psScalar *restrict scalar)
     130void psScalarFree(psScalar * restrict scalar)
    117131{
    118132    if (scalar == NULL) {
     
    122136    psFree(scalar);
    123137}
    124 
    125 
  • trunk/psLib/src/mathtypes/psScalar.h

    r1406 r1407  
     1
    12/** @file  psScalar.h
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_SCALAR_H
    19 #define PS_SCALAR_H
     20#    define PS_SCALAR_H
    2021
    21 #include "psType.h"
     22#    include "psType.h"
    2223
    2324/// @addtogroup Scalar
     
    3132typedef struct
    3233{
    33     psType type;                       ///< Type of data.
     34    psType type;                // /< Type of data.
    3435
    3536    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.
    4950}
    5051psScalar;
    5152
    5253/*****************************************************************************/
     54
    5355/* FUNCTION PROTOTYPES                                                       */
     56
    5457/*****************************************************************************/
    5558
     
    6265 *
    6366 */
    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 
     67psScalar *psScalarAlloc(psC64 value,    // /< Data to be put into psScalar.
     68                        psElemType dataType     // /< Type of data to be held by psScalar.
     69                       );
    6970
    7071/** Deallocate a scalar.
     
    7576 *
    7677 */
    77 void psScalarFree(
    78     psScalar *restrict scalar  ///< Scalar to free.
    79 );
     78void psScalarFree(psScalar * restrict scalar    // /< Scalar to free.
     79                 );
    8080
    8181/// @}
  • trunk/psLib/src/mathtypes/psVector.c

    r1406 r1407  
     1
    12/** @file  psVector.c
    23*
     
    89*  @author Ross Harman, MHPCC
    910*
    10 *  @version $Revision: 1.20 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.21 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
    18 /******************************************************************************/
    19 #include <string.h>        // for memcpy
     20
     21/******************************************************************************/
     22#include <string.h>                        // for memcpy
    2023#include <stdlib.h>
    2124#include <math.h>
     
    2831
    2932/******************************************************************************/
     33
    3034/*  DEFINE STATEMENTS                                                         */
     35
    3136/******************************************************************************/
    3237
     
    3439
    3540/******************************************************************************/
     41
    3642/*  TYPE DEFINITIONS                                                          */
     43
    3744/******************************************************************************/
    3845
     
    4047
    4148/*****************************************************************************/
     49
    4250/*  GLOBAL VARIABLES                                                         */
     51
    4352/*****************************************************************************/
    4453
     
    4655
    4756/*****************************************************************************/
     57
    4858/*  FILE STATIC VARIABLES                                                    */
     59
    4960/*****************************************************************************/
    5061
     
    5263
    5364/*****************************************************************************/
     65
    5466/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    55 /*****************************************************************************/
    56 static void vectorFree( psVector *restrict psVec );
    57 
    58 /*****************************************************************************/
     67
     68/*****************************************************************************/
     69static void vectorFree(psVector * restrict psVec);
     70
     71/*****************************************************************************/
     72
    5973/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    60 /*****************************************************************************/
    61 psVector* psVectorAlloc( unsigned int nalloc, psElemType elemType )
    62 {
    63     psVector * psVec = NULL;
     74
     75/*****************************************************************************/
     76psVector *psVectorAlloc(unsigned int nalloc, psElemType elemType)
     77{
     78    psVector *psVec = NULL;
    6479    int elementSize = 0;
    6580
    6681    // 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);
    6984        return NULL;
    7085    }
    7186
    72     elementSize = PSELEMTYPE_SIZEOF( elemType );
     87    elementSize = PSELEMTYPE_SIZEOF(elemType);
    7388
    7489    // 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);
    7792
    7893    psVec->type.dimen = PS_DIMEN_VECTOR;
     
    8297
    8398    // Create vector data array
    84     psVec->data.V = psAlloc( nalloc * elementSize );
     99    psVec->data.V = psAlloc(nalloc * elementSize);
    85100
    86101    return psVec;
    87102}
    88103
    89 psVector *psVectorRealloc( unsigned int nalloc, psVector *restrict in )
     104psVector *psVectorRealloc(unsigned int nalloc, psVector * restrict in)
    90105{
    91106    int elementSize = 0;
     
    93108
    94109    // 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);
    97112        return NULL;
    98113    }
    99114
    100     if ( in == NULL ) {
    101         psError( __func__, "Null input vector\n" );
     115    if (in == NULL) {
     116        psError(__func__, "Null input vector\n");
    102117        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;
    114123        }
     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    }
    115128
    116129    return in;
    117130}
    118131
    119 psVector *psVectorRecycle( psVector *restrict in, unsigned int nalloc, psElemType type )
     132psVector *psVectorRecycle(psVector * restrict in, unsigned int nalloc, psElemType type)
    120133{
    121134    psElemType elemType;
    122135
    123     if ( in == NULL ) {
    124         return psVectorAlloc( nalloc, type );
     136    if (in == NULL) {
     137        return psVectorAlloc(nalloc, type);
    125138    }
    126139
    127140    elemType = in->type.type;
    128141
    129     if ( in->nalloc == nalloc && elemType == type ) {
     142    if (in->nalloc == nalloc && elemType == type) {
    130143        // it is proper size/type already
    131144        return in;
    132145    }
    133 
    134146    // 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);
    138150        return NULL;
    139151    }
    140152
    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));
    143154
    144155    in->type.type = type;
     
    149160}
    150161
    151 psVector *psVectorSort( psVector *restrict outVector, const psVector *restrict inVector )
     162psVector *psVectorSort(psVector * restrict outVector, const psVector * restrict inVector)
    152163{
    153164    int inN = 0;
     
    158169    psElemType inType = 0;
    159170
    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__);
    162173        return outVector;
    163174    }
     
    166177    inN = inVector->n;
    167178    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);
    172183        outVector->n = inVector->n;
    173184    }
     
    176187    outVec = outVector->data.V;
    177188
    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    }
    200210    // Copy input vector values into output vector
    201     memcpy( outVec, inVec, elSize * outN );
     211    memcpy(outVec, inVec, elSize * outN);
    202212
    203213    // Sort output vector
    204     switch ( inType ) {
     214    switch (inType) {
    205215    case PS_TYPE_U8:
    206         qsort( outVec, inN, elSize, psCompareU8 );
     216        qsort(outVec, inN, elSize, psCompareU8);
    207217        break;
    208218    case PS_TYPE_U16:
    209         qsort( outVec, inN, elSize, psCompareU16 );
     219        qsort(outVec, inN, elSize, psCompareU16);
    210220        break;
    211221    case PS_TYPE_U32:
    212         qsort( outVec, inN, elSize, psCompareU32 );
     222        qsort(outVec, inN, elSize, psCompareU32);
    213223        break;
    214224    case PS_TYPE_U64:
    215         qsort( outVec, inN, elSize, psCompareU64 );
     225        qsort(outVec, inN, elSize, psCompareU64);
    216226        break;
    217227    case PS_TYPE_S8:
    218         qsort( outVec, inN, elSize, psCompareS8 );
     228        qsort(outVec, inN, elSize, psCompareS8);
    219229        break;
    220230    case PS_TYPE_S16:
    221         qsort( outVec, inN, elSize, psCompareS16 );
     231        qsort(outVec, inN, elSize, psCompareS16);
    222232        break;
    223233    case PS_TYPE_S32:
    224         qsort( outVec, inN, elSize, psCompareS32 );
     234        qsort(outVec, inN, elSize, psCompareS32);
    225235        break;
    226236    case PS_TYPE_S64:
    227         qsort( outVec, inN, elSize, psCompareS64 );
     237        qsort(outVec, inN, elSize, psCompareS64);
    228238        break;
    229239    case PS_TYPE_F32:
    230         qsort( outVec, inN, elSize, psCompareF32 );
     240        qsort(outVec, inN, elSize, psCompareF32);
    231241        break;
    232242    case PS_TYPE_F64:
    233         qsort( outVec, inN, elSize, psCompareF64 );
     243        qsort(outVec, inN, elSize, psCompareF64);
    234244        break;
    235245    default:
    236         psError( __func__, " : Line %d - Invalid psType\n", __LINE__ );
     246        psError(__func__, " : Line %d - Invalid psType\n", __LINE__);
    237247    }
    238248
     
    251261}
    252262
    253 psVector *psVectorSortIndex( psVector *restrict outVector, const psVector *restrict inVector )
     263psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector)
    254264{
    255265    int inN = 0;
     
    263273    psElemType inType = 0;
    264274
    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__);
    267277        return outVector;
    268278    }
     
    272282    inType = inVector->type.type;
    273283
    274     if ( outVector == NULL ) {
    275         outVector = psVectorAlloc( inN, PS_TYPE_U32 );
     284    if (outVector == NULL) {
     285        outVector = psVectorAlloc(inN, PS_TYPE_U32);
    276286        outVector->n = inN;
    277287    }
     
    280290    outVec = outVector->data.V;
    281291
    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);
    295305    tmpVector->n = inN;
    296     tmpVector = psVectorSort( tmpVector, inVector );
     306    tmpVector = psVectorSort(tmpVector, inVector);
    297307
    298308    // Sort output vector
    299     switch ( inType ) {
     309    switch (inType) {
    300310    case PS_TYPE_U8:
    301         SORT_INDICES( U8 );
     311        SORT_INDICES(U8);
    302312        break;
    303313    case PS_TYPE_U16:
    304         SORT_INDICES( U16 );
     314        SORT_INDICES(U16);
    305315        break;
    306316    case PS_TYPE_U32:
    307         SORT_INDICES( U32 );
     317        SORT_INDICES(U32);
    308318        break;
    309319    case PS_TYPE_U64:
    310         SORT_INDICES( U64 );
     320        SORT_INDICES(U64);
    311321        break;
    312322    case PS_TYPE_S8:
    313         SORT_INDICES( S8 );
     323        SORT_INDICES(S8);
    314324        break;
    315325    case PS_TYPE_S16:
    316         SORT_INDICES( S16 );
     326        SORT_INDICES(S16);
    317327        break;
    318328    case PS_TYPE_S32:
    319         SORT_INDICES( S32 );
     329        SORT_INDICES(S32);
    320330        break;
    321331    case PS_TYPE_S64:
    322         SORT_INDICES( S64 );
     332        SORT_INDICES(S64);
    323333        break;
    324334    case PS_TYPE_F32:
    325         SORT_INDICES( F32 );
     335        SORT_INDICES(F32);
    326336        break;
    327337    case PS_TYPE_F64:
    328         SORT_INDICES( F64 );
     338        SORT_INDICES(F64);
    329339        break;
    330340    default:
    331         psError( __func__, " : Line %d - Invalid psType\n", __LINE__ );
     341        psError(__func__, " : Line %d - Invalid psType\n", __LINE__);
    332342    }
    333343
    334344    // Free temp memory
    335     psFree( tmpVector );
     345    psFree(tmpVector);
    336346
    337347    return outVector;
    338348}
    339349
    340 static void vectorFree( psVector *restrict psVec )
    341 {
    342     if ( psVec == NULL ) {
    343         return ;
    344     }
    345 
    346     psFree( psVec->data.V );
    347 }
     350static 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
    12/** @file  psVector.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_VECTOR_H
    20 #define PS_VECTOR_H
     21#    define PS_VECTOR_H
    2122
    22 #include "psType.h"
     23#    include "psType.h"
    2324
    2425/// @addtogroup Vector
     
    3233typedef struct
    3334{
    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.
    3738
    3839    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.
    5354}
    5455psVector;
    5556
    5657/*****************************************************************************/
     58
    5759/* FUNCTION PROTOTYPES                                                       */
     60
    5861/*****************************************************************************/
    5962
     
    6568 *
    6669 */
    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 );
     70psVector *psVectorAlloc(unsigned int nalloc,    // /< Total number of elements to make available.
     71                        psElemType dataType     // /< Type of data to be held by vector.
     72                       );
    7173
    7274/** Reallocate a vector.
     
    7880 *
    7981 */
    80 psVector *psVectorRealloc(
    81     unsigned int nalloc,                ///< Total number of elements to make available.
    82     psVector *restrict psVec            ///< Vector to reallocate.
    83 );
     82psVector *psVectorRealloc(unsigned int nalloc,  // /< Total number of elements to make available.
     83                          psVector * restrict psVec     // /< Vector to reallocate.
     84                         );
    8485
    8586/** Recycle a vector.
     
    9192 *
    9293 */
    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 );
     94psVector *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                         );
    100100
    101101/** Sort an array of floats.
     
    107107 */
    108108
    109 psVector *psVectorSort(
    110     psVector *restrict outVector,  ///< the output vector to recycle, or NULL if new vector desired.
    111     const psVector *restrict inVector ///< the vector to sort.
    112 );
     109psVector *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                      );
    113113
    114114/** Creates an array of indices based on sort odred of float array.
     
    120120 */
    121121
    122 psVector *psVectorSortIndex(
    123     psVector *restrict outVector,
    124     const psVector *restrict inVector
    125 );
    126 
     122psVector *psVectorSortIndex(psVector * restrict outVector, const psVector * restrict inVector);
    127123
    128124/// @}
  • trunk/psLib/src/pslib.h

    r1392 r1407  
     1
    12/** @file  pslib.h
    23*
     
    89*  @author Eric Van Alst, MHPCC
    910*
    10 *  @version $Revision: 1.18 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-05 17:52:05 $
     11*  @version $Revision: 1.19 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617#ifndef PS_LIB_H
    17 #define PS_LIB_H
     18#    define PS_LIB_H
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225
     
    3538 */
    3639
    37 #include "fitsio.h"
     40#    include "fitsio.h"
    3841
    39 #include "psMemory.h"
     42#    include "psMemory.h"
    4043
    4144/// @defgroup LogTrace Tracing and Logging
    4245/// @ingroup SysUtils
    43 #include "psLogMsg.h"
    44 #include "psTrace.h"
     46#    include "psLogMsg.h"
     47#    include "psTrace.h"
    4548
    4649/// @defgroup ErrorHandling Error Handling
    4750/// @ingroup SysUtils
    48 #include "psAbort.h"
    49 #include "psError.h"
     51#    include "psAbort.h"
     52#    include "psError.h"
    5053
    51 #include "psString.h"
     54#    include "psString.h"
    5255
    5356/// @}
     
    5760/// @{
    5861
    59 #include "psType.h"
     62#    include "psType.h"
    6063
    6164/// @defgroup LinkedList Linked List
    6265/// @ingroup DataContainer
    63 #include "psList.h"
     66#    include "psList.h"
    6467
    6568/// @defgroup HashTable Hash Table
    6669/// @ingroup DataContainer
    67 #include "psHash.h"
     70#    include "psHash.h"
    6871
    6972/// @defgroup Scalar Scalar
    7073/// @ingroup DataContainer
    71 #include "psScalar.h"
     74#    include "psScalar.h"
    7275
    7376/// @defgroup Vector Vector Container
    7477/// @ingroup DataContainer
    75 #include "psVector.h"
     78#    include "psVector.h"
    7679
    7780/// @defgroup Array Array Container
    7881/// @ingroup DataContainer
    79 #include "psArray.h"
     82#    include "psArray.h"
    8083
    8184/// @defgroup Image Image Container
    8285/// @ingroup DataContainer
    8386/// @{
    84 #include "psImage.h"
    85 #include "psImageExtraction.h"
    86 #include "psImageManip.h"
     87#    include "psImage.h"
     88#    include "psImageExtraction.h"
     89#    include "psImageManip.h"
    8790
    8891/// @defgroup ImageIO Image File I/O Functions
    8992/// @ingroup Image
    90 #include "psImageIO.h"
    91 
     93#    include "psImageIO.h"
    9294
    9395/// @defgroup ImageStats Image Statistical Functions
    9496/// @ingroup Image
    95 #include "psImageStats.h"
     97#    include "psImageStats.h"
    9698
    9799/// @}
     
    99101/// @defgroup BitSet Bit Set Container
    100102/// @ingroup DataContainer
    101 #include "psBitSet.h"
     103#    include "psBitSet.h"
    102104
    103105/// @}
     
    109111/// @defgroup Compare Comparison Functions
    110112/// @ingroup DataManip
    111 #include "psCompare.h"
     113#    include "psCompare.h"
    112114
    113115/// @defgroup Stats Statistic Functions
    114116/// @ingroup DataManip
    115 #include "psStats.h"
     117#    include "psStats.h"
    116118
    117119/// @defgroup Matrix Matrix Operations
    118120/// @ingroup DataManip
    119 #include "psMatrix.h"
     121#    include "psMatrix.h"
    120122
    121123/// @defgroup MatrixVectorArithmetic Matrix Vector Arithmetic Operations
    122124/// @ingroup DataManip
    123 #include "psMatrixVectorArithmetic.h"
     125#    include "psMatrixVectorArithmetic.h"
    124126
    125127/// @defgroup Transform Fourier Transform Operations
    126128/// @ingroup DataManip
    127 #include "psFFT.h"
     129#    include "psFFT.h"
    128130
    129 #include "psFunctions.h"
    130 #include "psMinimize.h"
     131#    include "psFunctions.h"
     132#    include "psMinimize.h"
    131133
    132134/// @}
     
    138140/// @defgroup CoordinateTransform Coordinate Functions
    139141/// @ingroup Astronomy
    140 #include "psCoord.h"
     142#    include "psCoord.h"
    141143
    142144/// @defgroup Photometry Photometry
    143145/// @ingroup Astronomy
    144 #include "psPhotometry.h"
     146#    include "psPhotometry.h"
    145147
    146148/// @defgroup Time Time Functions
    147149/// @ingroup Astronomy
    148 #include "psTime.h"
     150#    include "psTime.h"
    149151
    150152/// @defgroup Metadata Metadata Functions
    151153/// @ingroup Astronomy
    152 #include "psMetadata.h"
     154#    include "psMetadata.h"
    153155
    154156/// @}
    155157
    156158#endif
    157 
  • trunk/psLib/src/sys/psAbort.c

    r1406 r1407  
     1
    12/** @file  psAbort.c
    23 *
     
    910 *  @author Eric Van Alst, MHPCC
    1011 *   
    11  *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1617
    1718/******************************************************************************/
     19
    1820/*  INCLUDE FILES                                                             */
     21
    1922/******************************************************************************/
    2023#include <stdarg.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873
    59 void psAbort(const char *name, const char *fmt,... )
     74void psAbort(const char *name, const char *fmt, ...)
    6075{
    61     va_list    argPtr;     // variable list arguement pointer
     76    va_list argPtr;             // variable list arguement pointer
    6277
    6378    // Get the variable list parameters to pass to logging function
     
    7388    abort();
    7489}
    75 
  • trunk/psLib/src/sys/psAbort.h

    r974 r1407  
     1
    12/** @file  psAbort.h
    23 *
     
    1112 *  @author Eric Van Alst, MHPCC
    1213 *
    13  *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-06-10 01:58:06 $
     14 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_ABORT_H
    20 #define PS_ABORT_H
    21 
     21#    define PS_ABORT_H
    2222
    2323// Doxygen grouping tags
     24
    2425/** @addtogroup ErrorHandling
    2526 *  @{
     
    3637 *
    3738 */
    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 );
     39void 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            );
    4343
    44 /* @} */  // Doxygen - End of SystemGroup Functions
     44/* @} */// Doxygen - End of SystemGroup Functions
    4545
    4646#endif
    47 
  • trunk/psLib/src/sys/psError.c

    r1406 r1407  
     1
    12/** @file  psError.c
    23 *
     
    1011 *  @author Eric Van Alst, MHPCC
    1112 *   
    12  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819/******************************************************************************/
     20
    1921/*  INCLUDE FILES                                                             */
     22
    2023/******************************************************************************/
    2124#include <stdarg.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATIONS - LOCAL                                         */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATIONS - PUBLIC                                         */
     71
    5772/*****************************************************************************/
    5873
    59 void psError(const char *name,const char *fmt, ...)
     74void psError(const char *name, const char *fmt, ...)
    6075{
    61     va_list    argPtr;        // variable list arguement pointer
     76    va_list argPtr;             // variable list arguement pointer
    6277
    63     // Get the variable list parameters  to pass to logging function
     78    // Get the variable list parameters to pass to logging function
    6479    va_start(argPtr, fmt);
    6580
     
    7085    va_end(argPtr);
    7186}
    72 
  • trunk/psLib/src/sys/psError.h

    r974 r1407  
     1
    12/** @file  psError.h
    23 *
     
    1213 *  @author Eric Van Alst, MHPCC
    1314 *
    14  *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-06-10 01:58:06 $
     15 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PS_ERROR_H
    21 #define PS_ERROR_H
     22#    define PS_ERROR_H
    2223
    2324/** @addtogroup ErrorHandling
     
    3435 *
    3536 */
    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 );
     37void 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            );
    4141
    42 /* @} */  // End of SysUtils Functions
     42/* @} */// End of SysUtils Functions
    4343
    4444#endif
    45 
  • trunk/psLib/src/sys/psLogMsg.c

    r1406 r1407  
     1
    12/** @file  psLogMsg.c
    23 *  @brief Procedures for logging messages.
     
    1112 *  @author George Gusciora, MHPCC
    1213 *
    13  *  @version $Revision: 1.23 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.24 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    4445
    4546#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 above
    48 static bool logTime = true;            // Flag to include time info
    49 static bool logHost = true;            // Flag to include host info
    50 static bool logLevel = true;           // Flag to include level info
    51 static bool logName = true;            // Flag to include name info
    52 static bool logMsg = true;             // Flag to include message info
     47static FILE *logDest = (FILE *) 1;      // flag to initialize to stderr before using.
     48static int globalLogLevel = PS_LOG_INFO;        // log all messages at this or above
     49static bool logTime = true;     // Flag to include time info
     50static bool logHost = true;     // Flag to include host info
     51static bool logLevel = true;    // Flag to include level info
     52static bool logName = true;     // Flag to include name info
     53static bool logMsg = true;      // Flag to include message info
    5354
    5455/*****************************************************************************
     
    6768
    6869    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);
    7171        level = (level < MIN_LOG_LEVEL) ? MIN_LOG_LEVEL : MAX_LOG_LEVEL;
    7272    }
    73 
    7473    // Set new global log level
    7574    globalLogLevel = level;
     
    7877    return oldLevel;
    7978}
    80 
    8179
    8280/*****************************************************************************
     
    9189 An integer specifying the old log destination.
    9290 *****************************************************************************/
    93 int psLogSetDestination(const char* dest)
     91int psLogSetDestination(const char *dest)
    9492{
    9593    char protocol[5];
     
    9795
    9896    // if logDest has not been initialized, do so before using it
    99     if (logDest==(FILE*)1) {
     97    if (logDest == (FILE *) 1) {
    10098        logDest = stderr;
    10199    }
    102100
    103     if (dest == NULL || strcmp(dest,"none")==0) {
     101    if (dest == NULL || strcmp(dest, "none") == 0) {
    104102        if (logDest != NULL && logDest != stderr && logDest != stdout) {
    105103            fclose(logDest);
     
    109107    }
    110108
    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);
    113111        return 1;
    114112    }
    115113
    116     if (strcmp(protocol,"dest") == 0) {
    117         if (strcmp(location,"stderr") == 0) {
     114    if (strcmp(protocol, "dest") == 0) {
     115        if (strcmp(location, "stderr") == 0) {
    118116            if (logDest != NULL && logDest != stderr && logDest != stdout) {
    119117                fclose(logDest);
     
    122120            return 0;
    123121        }
    124         if (strcmp(location,"stdout") == 0) {
     122        if (strcmp(location, "stdout") == 0) {
    125123            if (logDest != NULL && logDest != stderr && logDest != stdout) {
    126124                fclose(logDest);
     
    129127            return 0;
    130128        }
    131         psError(__func__,"The location, %s, for protocol 'dest' is invalid.",location);
     129        psError(__func__, "The location, %s, for protocol 'dest' is invalid.", location);
    132130        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);
    148146    return 1;
    149147}
     
    181179        fmt = "THLNM";
    182180    }
    183 
    184181    // Step through each character in the format string.  For each letter
    185182    // in that string, set/unset the appropriate logging.
     
    214211
    215212    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
    226219#endif
     220
    227221/*****************************************************************************
    228222    psVLogMsg(): This routine sends the message, which is a printf style
     
    239233 NULL.
    240234 *****************************************************************************/
    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()
     235void psLogMsgV(const char *name, int level, const char *fmt, va_list ap)
     236{
     237    static int first = 1;       // Flag for calling gethostname()
    247238    static char hostname[HOST_NAME_MAX + 1];
     239
    248240    // Buffer for hostname.
    249     char clevel=0;                      // letter-name for level
    250     char head[MAX_LOG_LINE_LENGTH+2];  // the added two are for the ending | and \0
    251     char *head_ptr = head;              // where we've got to in head
     241    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
    252244    int maxLength = MAX_LOG_LINE_LENGTH;
    253     time_t clock = time(NULL);          // The current time.
     245    time_t clock = time(NULL);  // The current time.
    254246    struct tm *utc = gmtime(&clock);    // The current gm time.
    255247
    256248    // if logDest has not been initialized, do so before using it
    257     if (logDest==(FILE*)1) {
     249    if (logDest == (FILE *) 1) {
    258250        logDest = stderr;
    259251    }
    260 
    261252    // If logging is off, or if the level is too high, return immediately.
    262253    if ((level > globalLogLevel) || (logDest == NULL)) {
    263254        return;
    264255    }
    265 
    266256    // If I have not been here yet, determine my hostname and save it.
    267257    if (first) {
     
    297287
    298288    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);
    301290        level = (level < 0) ? 0 : 9;
    302291        break;
     
    307296        maxLength -= snprintf(head_ptr, maxLength, "%4d:%02d:%02d %02d:%02d:%02dZ",
    308297                              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;
    310299        head_ptr += strlen(head_ptr);
    311300    }
     
    336325    if (head_ptr > head) {
    337326        *head_ptr++ = '|';
    338     } else
    339         if (!logMsg) { // no output desired
    340             return;
    341         }
     327    } else if (!logMsg) {                  // no output desired
     328        return;
     329    }
    342330    *head_ptr = '\0';
    343331
     
    352340    }
    353341}
    354 
    355342
    356343/*****************************************************************************
     
    369356 NULL
    370357 *****************************************************************************/
    371 void psLogMsg(const char *name,
    372               int level,
    373               const char *fmt,
    374               ...)
     358void psLogMsg(const char *name, int level, const char *fmt, ...)
    375359{
    376360    va_list ap;
  • trunk/psLib/src/sys/psLogMsg.h

    r1406 r1407  
     1
    12/** @file  psLogMsg.h
    23 *  @brief Procedures for logging messages.
     
    1112 *  @author George Gusciora, MHPCC
    1213 *
    13  *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1718 */
    1819#if !defined(PS_LOG_MSG_H)
    19 #define PS_LOG_MSG_H
    20 #include <stdarg.h>
     20#    define PS_LOG_MSG_H
     21#    include <stdarg.h>
    2122
    2223/** @addtogroup LogTrace
     
    2930/// In future versions, this procedure will take a character string as an
    3031/// argument which can specify more general log destinations.
    31 int psLogSetDestination(const char* dest   ///< Specifies where to send messages.
     32int psLogSetDestination(const char *dest        // /< Specifies where to send messages.
    3233                       );
    33 
    3434
    3535/// This procedure sets the message level for future log messages.  Subsequent
     
    3838/// Ie. higher values set by this procedure will cause more log messages to
    3939/// be displayed.
    40 int psLogSetLevel(int level          ///< Specifies the system log level
     40int psLogSetLevel(int level     // /< Specifies the system log level
    4141                 );
    42 
    4342
    4443/// This procedure sets the log format for future log messages.  The argument
     
    4746/// Deleting a letter from the string will cause the associated information
    4847/// to not be logged.
    49 void psLogSetFormat(const char *fmt ///< Specifies the system log format
     48void psLogSetFormat(const char *fmt     // /< Specifies the system log format
    5049                   );
    51 
    5250
    5351/// This procedure logs a message to the destination set by a prior
     
    5553/// specified by a prior call to psLogSetLevel().  The message is specified
    5654/// with a printf-stype string an arguments.
    57 void psLogMsg(const char *name,     ///< name of the log source
    58               int myLevel,          ///< severity level of this log message
    59               const char *fmt, ...  ///< printf-style format command
     55void 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
    6058             );
    61 
    6259
    6360/// This procedure is functionally equivalent to psLogMsg(), except that
    6461/// it takes a va_list as the message parameter, not a printf-style string.
    65 void psLogMsgV(const char *name, ///< name of the log source
    66                int myLevel,      ///< severity level of this log message
    67                const char *fmt,  ///< printf-style format command
    68                va_list ap        ///< varargs argument list
     62void 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
    6966              );
    7067
     
    7471    PS_LOG_ERROR,
    7572    PS_LOG_WARN,
    76     PS_LOG_INFO };
     73    PS_LOG_INFO
     74};
    7775
    7876///< Destinations for log messages
     
    8078    PS_LOG_NONE,
    8179    PS_LOG_TO_STDERR,
    82     PS_LOG_TO_STDOUT };
     80    PS_LOG_TO_STDOUT
     81};
    8382
    8483/// @}
  • trunk/psLib/src/sys/psMemory.c

    r1406 r1407  
     1
    12/** @file  psMemory.c
    23*
     
    89*  @author Robert Lupton, Princeton University
    910*
    10 *  @version $Revision: 1.32 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.33 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1415*/
    1516
    16 #define PS_ALLOW_MALLOC                 // we're allowed to call malloc()
     17#define PS_ALLOW_MALLOC                    // we're allowed to call malloc()
    1718
    1819#include <stdlib.h>
     
    2627#include "psLogMsg.h"
    2728
    28 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header
    29 
    30 #define P_PS_LARGE_BLOCK_SIZE 65536    // size where under, we try to recycle
    31 
    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
     33static int checkMemBlock(const psMemBlock * m, const char *funcName);
    3334static psMemBlock *lastMemBlockAllocated = NULL;
    3435static pthread_mutex_t memBlockListMutex = PTHREAD_MUTEX_INITIALIZER;
     
    3839
    3940static 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_SIZE
    43     };
     41static int recycleBinSize[14] = {
     42                                    8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE
     43                                };
     44
    4445// 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     };
     46static psMemBlock *recycleMemBlockList[13] = {
     47            NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
     48        };
    4949
    5050#ifdef PS_MEM_DEBUG
    51 static psMemBlock* deadBlockList;    // a place to put dead memBlocks in debug mode.
     51static psMemBlock *deadBlockList;       // a place to put dead memBlocks in debug mode.
    5252#endif
     53
    5354/**
    5455 * Unique ID for allocated blocks
     
    5960 *  Default memExhausted callback.
    6061 */
    61 static void *memExhaustedCallbackDefault( size_t size )
    62 {
    63     void * ptr = NULL;
    64 
    65     pthread_mutex_lock( &recycleMemBlockListMutex );
     62static void *memExhaustedCallbackDefault(size_t size)
     63{
     64    void *ptr = NULL;
     65
     66    pthread_mutex_lock(&recycleMemBlockListMutex);
    6667    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);
    7376        }
    7477        level--;
    7578    }
    76     pthread_mutex_unlock( &recycleMemBlockListMutex );
     79    pthread_mutex_unlock(&recycleMemBlockListMutex);
    7780
    7881    return ptr;
     
    8184static psMemExhaustedCallback memExhaustedCallback = memExhaustedCallbackDefault;
    8285
    83 psMemExhaustedCallback psMemExhaustedCallbackSet( psMemExhaustedCallback func )
     86psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func)
    8487{
    8588    psMemExhaustedCallback old = memExhaustedCallback;
    8689
    87     if ( func != NULL ) {
     90    if (func != NULL) {
    8891        memExhaustedCallback = func;
    8992    } else {
     
    9497}
    9598
    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 );
     99static 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);
    107109    }
    108110}
    109111static psMemProblemCallback memProblemCallback = memProblemCallbackDefault;
    110112
    111 psMemProblemCallback psMemProblemCallbackSet( psMemProblemCallback func )
     113psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func)
    112114{
    113115    psMemProblemCallback old = memProblemCallback;
    114116
    115     if ( func != NULL ) {
     117    if (func != NULL) {
    116118        memProblemCallback = func;
    117119    } else {
     
    121123    return old;
    122124}
     125
    123126/*
    124127 * And now the I-want-to-be-informed callbacks
     
    126129 * Call the callbacks when these IDs are allocated/freed
    127130 */
    128 psMemoryId p_psMemAllocateID = 0;  // notify user this block is allocated
     131psMemoryId p_psMemAllocateID = 0;       // notify user this block is allocated
    129132psMemoryId p_psMemFreeID = 0;   // notify user this block is freed
    130133
    131 psMemoryId psMemAllocateCallbackSetID( psMemoryId id )
     134psMemoryId psMemAllocateCallbackSetID(psMemoryId id)
    132135{
    133136    psMemoryId old = p_psMemAllocateID;
     137
    134138    p_psMemAllocateID = id;
    135139
     
    137141}
    138142
    139 psMemoryId psMemFreeCallbackSetID( psMemoryId id )
     143psMemoryId psMemFreeCallbackSetID(psMemoryId id)
    140144{
    141145    psMemoryId old = p_psMemFreeID;
     146
    142147    p_psMemFreeID = id;
    143148
     
    151156 * isn't resignalled)
    152157 */
    153 static psMemoryId memAllocateCallbackDefault( const psMemBlock *ptr )
    154 {
    155     static psMemoryId incr = 0;  // "p_psMemAllocateID += incr"
     158static psMemoryId memAllocateCallbackDefault(const psMemBlock * ptr)
     159{
     160    static psMemoryId incr = 0; // "p_psMemAllocateID += incr"
    156161
    157162    return incr;
    158163}
    159164
    160 static psMemoryId memFreeCallbackDefault( const psMemBlock *ptr )
    161 {
    162     static psMemoryId incr = 0;  // "p_psMemFreeID += incr"
     165static psMemoryId memFreeCallbackDefault(const psMemBlock * ptr)
     166{
     167    static psMemoryId incr = 0; // "p_psMemFreeID += incr"
    163168
    164169    return incr;
     
    171176static psMemFreeCallback memFreeCallback = memFreeCallbackDefault;
    172177
    173 psMemAllocateCallback psMemAllocateCallbackSet( psMemAllocateCallback func )
     178psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func)
    174179{
    175180    psMemFreeCallback old = memAllocateCallback;
    176181
    177     if ( func != NULL ) {
     182    if (func != NULL) {
    178183        memAllocateCallback = func;
    179184    } else {
     
    184189}
    185190
    186 psMemFreeCallback psMemFreeCallbackSet( psMemFreeCallback func )
     191psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func)
    187192{
    188193    psMemFreeCallback old = memFreeCallback;
    189194
    190     if ( func != NULL ) {
     195    if (func != NULL) {
    191196        memFreeCallback = func;
    192197    } else {
     
    200205 * Return memory ID counter for next block to be allocated
    201206 */
    202 psMemoryId psMemGetId( void )
     207psMemoryId psMemGetId(void)
    203208{
    204209    psMemoryId id;
    205     pthread_mutex_lock( &memIdMutex );
     210
     211    pthread_mutex_lock(&memIdMutex);
    206212    id = memid + 1;
    207     pthread_mutex_unlock( &memIdMutex );
     213    pthread_mutex_unlock(&memIdMutex);
    208214
    209215    return id;
     
    216222 */
    217223
    218 static int checkMemBlock( const psMemBlock *m, const char* funcName )
     224static int checkMemBlock(const psMemBlock * m, const char *funcName)
    219225{
    220226    // n.b. since this is called by psMemCheckCorruption while the memblock list is mutex locked,
    221227    // we shouldn't call such things as p_psAlloc/p_psFree here.
    222228
    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.");
    225231        return 1;
    226232    }
    227233
    228     if ( m->refCounter == 0 ) {
     234    if (m->refCounter == 0) {
    229235        // 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);
    232237        return 1;
    233238    }
    234239
    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);
    238242        return 1;
    239243    }
    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);
    243246        return 1;
    244247    }
     
    247250}
    248251
    249 int psMemCheckCorruption( bool abort_on_error )
    250 {
    251     int nbad = 0;                       // number of bad blocks
     252int psMemCheckCorruption(bool abort_on_error)
     253{
     254    int nbad = 0;               // number of bad blocks
    252255
    253256    // 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__)) {
    258261            nbad++;
    259262
    260             memProblemCallback( iter, __func__, __LINE__ );
    261 
    262             if ( abort_on_error ) {
     263            memProblemCallback(iter, __func__, __LINE__);
     264
     265            if (abort_on_error) {
    263266                // 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");
    266269                return nbad;
    267270            }
     
    270273
    271274    // release the lock on the memblock list
    272     pthread_mutex_unlock( &memBlockListMutex );
     275    pthread_mutex_unlock(&memBlockListMutex);
    273276    return nbad;
    274277}
    275278
    276 void *p_psAlloc( size_t size, const char *file, int lineno )
    277 {
    278 
    279     psMemBlock * ptr = NULL;
     279void *p_psAlloc(size_t size, const char *file, int lineno)
     280{
     281
     282    psMemBlock *ptr = NULL;
    280283
    281284    // 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) {
    283286        // find the bin we need.
    284287        int level = 0;
    285         while ( size > recycleBinSize[ level ] ) {
     288
     289        while (size > recycleBinSize[level]) {
    286290            level++;
    287291        }
    288292        // 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;
    300304                }
    301305                size = ptr->userMemorySize;
    302306            }
    303307
    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);
    316319            }
    317320        }
     
    320323        ptr->endblock = P_PS_MEMMAGIC;
    321324        ptr->userMemorySize = size;
    322         pthread_mutex_init( &ptr->refCounterMutex, NULL );
    323     }
    324 
     325        pthread_mutex_init(&ptr->refCounterMutex, NULL);
     326    }
    325327    // 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);
    329331
    330332    ptr->file = file;
    331333    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;
    334336    ptr->previousBlock = NULL;
    335337
    336     ptr->refCounter = 1;                // one user so far
     338    ptr->refCounter = 1;                   // one user so far
    337339
    338340    // need exclusive access of the memory block list now...
    339     pthread_mutex_lock( &memBlockListMutex );
     341    pthread_mutex_lock(&memBlockListMutex);
    340342
    341343    // insert the new block to the front of the memBlock linked-list
    342344    ptr->nextBlock = lastMemBlockAllocated;
    343     if ( ptr->nextBlock != NULL ) {
     345    if (ptr->nextBlock != NULL) {
    344346        ptr->nextBlock->previousBlock = ptr;
    345347    }
    346348    lastMemBlockAllocated = ptr;
    347349
    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    }
    355356    // And return the user the memory that they allocated
    356     return ptr + 1;   // user memory
    357 }
    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
     360void *p_psRealloc(void *vptr, size_t size, const char *file, int lineno)
     361{
     362    if (vptr == NULL) {
     363        return p_psAlloc(size, file, lineno);
    363364    } else {
    364         psMemBlock *ptr = ( ( psMemBlock * ) vptr ) - 1;
     365        psMemBlock *ptr = ((psMemBlock *) vptr) - 1;
    365366        bool isBlockLast = false;
    366367
    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);
    382382        }
    383383
    384384        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) {
    388388            lastMemBlockAllocated = ptr;
    389389        }
    390 
    391390        // the block location may have changed, so fix the linked list addresses.
    392         if ( ptr->nextBlock != NULL ) {
     391        if (ptr->nextBlock != NULL) {
    393392            ptr->nextBlock->previousBlock = ptr;
    394393        }
    395         if ( ptr->previousBlock != NULL ) {
     394        if (ptr->previousBlock != NULL) {
    396395            ptr->previousBlock->nextBlock = ptr;
    397396        }
    398397
    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 memory
    407     }
    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
     409void p_psFree(void *vptr, const char *file, int lineno)
     410{
     411    (void)p_psMemDecrRefCounter(vptr, file, lineno);    // this handles the free, if required.
    413412}
    414413
     
    416415 * Check for memory leaks.
    417416 */
    418 int psMemCheckLeaks( psMemoryId id0, psMemBlock ***arr, FILE *fd )
     417int psMemCheckLeaks(psMemoryId id0, psMemBlock *** arr, FILE * fd)
    419418{
    420419    int nleak = 0;
    421420    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)) {
    428427            nleak++;
    429428
    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");
    433432                }
    434433
    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) {
    443442        return nleak;
    444443    }
    445444
    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 all
     445    *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
    453452                break;
    454453            }
     
    456455    }
    457456
    458     pthread_mutex_unlock( &memBlockListMutex );
     457    pthread_mutex_unlock(&memBlockListMutex);
    459458
    460459    return nleak;
     
    465464 */
    466465// return refCounter
    467 psReferenceCount psMemGetRefCounter( void *vptr )
    468 {
    469     psMemBlock * ptr;
     466psReferenceCount psMemGetRefCounter(void *vptr)
     467{
     468    psMemBlock *ptr;
    470469    unsigned int refCount;
    471470
    472     if ( vptr == NULL ) {
     471    if (vptr == NULL) {
    473472        return 0;
    474473    }
    475474
    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);
    483482    refCount = ptr->refCounter;
    484     pthread_mutex_unlock( &ptr->refCounterMutex );
     483    pthread_mutex_unlock(&ptr->refCounterMutex);
    485484
    486485    return refCount;
    487486}
     487
    488488// increment and return refCounter
    489 void* p_psMemIncrRefCounter( void *vptr, const char *file, int lineno )
    490 {
    491     psMemBlock * ptr;
    492 
    493     if ( vptr == NULL ) {
     489void *p_psMemIncrRefCounter(void *vptr, const char *file, int lineno)
     490{
     491    psMemBlock *ptr;
     492
     493    if (vptr == NULL) {
    494494        return vptr;
    495495    }
    496496
    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);
    504504    ptr->refCounter++;
    505     pthread_mutex_unlock( &ptr->refCounterMutex );
     505    pthread_mutex_unlock(&ptr->refCounterMutex);
    506506
    507507    return vptr;
     
    509509
    510510// decrement and return refCounter
    511 void* p_psMemDecrRefCounter( void *vptr, const char *file, int lineno )
    512 {
    513     if ( vptr == NULL ) {
     511void *p_psMemDecrRefCounter(void *vptr, const char *file, int lineno)
     512{
     513    if (vptr == NULL) {
    514514        return NULL;
    515515    }
    516516
    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);
    521521        return NULL;
    522522    }
    523523
    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);
    530530
    531531    } else {
    532         pthread_mutex_unlock( &ptr->refCounterMutex );
     532        pthread_mutex_unlock(&ptr->refCounterMutex);
    533533
    534534        // 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);
    544544
    545545        // cut the memBlock out of the memBlock list
    546         if ( ptr->nextBlock != NULL ) {
     546        if (ptr->nextBlock != NULL) {
    547547            ptr->nextBlock->previousBlock = ptr->previousBlock;
    548548        }
    549         if ( ptr->previousBlock != NULL ) {
     549        if (ptr->previousBlock != NULL) {
    550550            ptr->previousBlock->nextBlock = ptr->nextBlock;
    551551        }
    552         if ( lastMemBlockAllocated == ptr ) {
     552        if (lastMemBlockAllocated == ptr) {
    553553            lastMemBlockAllocated = ptr->nextBlock;
    554554        }
    555555
    556         pthread_mutex_unlock( &memBlockListMutex );
    557 
     556        pthread_mutex_unlock(&memBlockListMutex);
    558557
    559558        // do we need to recycle?
    560         if ( ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE ) {
     559        if (ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) {
    561560
    562561            int level = 1;
    563             while ( ptr->userMemorySize >= recycleBinSize[ level ] ) {
     562
     563            while (ptr->userMemorySize >= recycleBinSize[level]) {
    564564                level++;
    565565            }
     
    569569            ptr->previousBlock = NULL;
    570570
    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);
    578578
    579579        } else {
    580580            // memory is larger than I want to recycle.
    581581            #ifdef PS_MEM_DEBUG
    582             ( void ) p_psRealloc( vptr, 0, file, lineno );
     582            (void)p_psRealloc(vptr, 0, file, lineno);
    583583            ptr->previousBlock = NULL;
    584584            ptr->nextBlock = deadBlockList;
    585             if ( deadBlockList != NULL ) {
     585            if (deadBlockList != NULL) {
    586586                deadBlockList->previous = ptr;
    587587            }
     
    589589            #else
    590590
    591             pthread_mutex_destroy( &ptr->refCounterMutex );
    592             free( ptr );
     591            pthread_mutex_destroy(&ptr->refCounterMutex);
     592            free(ptr);
    593593            #endif
    594594
    595595        }
    596596
    597         vptr = NULL;    // since we freed it, make sure we return NULL.
     597        vptr = NULL;                       // since we freed it, make sure we return NULL.
    598598    }
    599599
     
    601601}
    602602
    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__ );
     603void 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__);
    613613    }
    614614
     
    616616
    617617}
    618 psFreeFcn p_psMemGetDeallocator( void* vptr )
    619 {
    620     if ( vptr == NULL ) {
     618psFreeFcn p_psMemGetDeallocator(void *vptr)
     619{
     620    if (vptr == NULL) {
    621621        return NULL;
    622622    }
    623623
    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__);
    628628    }
    629629
  • trunk/psLib/src/sys/psMemory.h

    r1406 r1407  
    11#if !defined(PS_MEMORY_H)
    2 #define PS_MEMORY_H
     2#    define PS_MEMORY_H
     3
    34/** @file  psMemory.h
    45 *
     
    1415 *  @ingroup MemoryManagement
    1516 *
    16  *  @version $Revision: 1.23 $ $Name: not supported by cvs2svn $
    17  *  @date $Date: 2004-08-06 22:34:05 $
     17 *  @version $Revision: 1.24 $ $Name: not supported by cvs2svn $
     18 *  @date $Date: 2004-08-07 00:06:06 $
    1819 *
    1920 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    2021 */
    2122
    22 #include <stdio.h>                      // needed for FILE
    23 #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.
    2526
    2627/** @addtogroup MemoryManagement
     
    5354
    5455/// typedef for deallocator.
    55 typedef void (*psFreeFcn)(void* ptr);
     56typedef void (*psFreeFcn) (void *ptr);
    5657
    5758/** Book-keeping data for storage allocator.
     
    6263typedef struct psMemBlock
    6364{
    64     const void* startblock;            ///< initialised to p_psMEMMAGIC
    65     struct psMemBlock* previousBlock;  ///< previous block in allocation list
    66     struct psMemBlock* nextBlock;      ///< next block allocation list
    67     psFreeFcn freeFcn;                 ///< deallocator.  If NULL, use generic deallocation.
    68     size_t  userMemorySize;            ///< the size of the user-portion of the memory block
    69     const psMemoryId id;               ///< a unique ID for this allocation
    70     const char* file;                  ///< set from __FILE__ in e.g. p_psAlloc
    71     const int lineno;                  ///< set from __LINE__ in e.g. p_psAlloc
    72     pthread_mutex_t   refCounterMutex; ///< mutex to ensure exclusive access to reference counter
    73     psReferenceCount refCounter;       ///< how many times pointer is referenced
    74     const void* endblock;              ///< initialised to p_psMEMMAGIC
     65    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
    7576}
    7677psMemBlock;
     
    8182 *  @ingroup memCallback
    8283 */
    83 typedef psMemoryId (*psMemAllocateCallback)(
    84     const psMemBlock *ptr           ///< the psMemBlock just allocated
    85 );
     84typedef psMemoryId(*psMemAllocateCallback) (const psMemBlock * ptr      // /< the psMemBlock just allocated
     85                                           );
    8686
    8787/** prototype of memory free callback used by memory functions
     
    9090 *  @ingroup memCallback
    9191 */
    92 typedef psMemoryId (*psMemFreeCallback)(
    93     const psMemBlock *ptr           ///< the psMemBlock being freed
    94 );
     92typedef psMemoryId(*psMemFreeCallback) (const psMemBlock * ptr  // /< the psMemBlock being freed
     93                                       );
    9594
    9695/** prototype of a callback used in error conditions
     
    101100 *  @ingroup memCallback
    102101 */
    103 typedef void (*psMemProblemCallback)(
    104     const psMemBlock *ptr,          ///< the pointer to the problematic memory block.
    105     const char *file,               ///< the file in which the problem originated
    106     int lineno                      ///< the line number in which the problem originated
    107 );
     102typedef 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                                     );
    108107
    109108/** prototype of a callback function used when memory runs out
     
    115114 *  @ingroup memCallback
    116115 */
    117 typedef void *(*psMemExhaustedCallback)(
    118     size_t size                     //< the size of buffer required
    119 );
     116typedef void *(*psMemExhaustedCallback) (size_t size    // < the size of buffer required
     117                                        );
    120118
    121119/** Memory allocation.  This operates much like malloc(), but is guaranteed to return a non-NULL value.
     
    124122 *  @see psFree
    125123 */
    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
     125void *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
     133void p_psMemSetDeallocator(void *ptr, psFreeFcn freeFcn);
     134psFreeFcn p_psMemGetDeallocator(void *ptr);
    139135
    140136/// 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
    144139
    145140/** Memory re-allocation.  This operates much like realloc(), but is guaranteed to return a non-NULL value.
     
    148143 *  @see psAlloc, psFree
    149144 */
    150 #ifdef DOXYGEN
    151 void* psRealloc(void *ptr               ///< Pointer to re-allocate
    152                 size_t size,            ///< Size required
     145#    ifdef DOXYGEN
     146void *psRealloc(void *ptr       // /< Pointer to re-allocate
     147                size_t size,    // /< Size required
    153148               );
    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
     166void 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
    159172                 );
    160173
    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 #endif
    165 
    166 
    167 /** Free memory.  This operates much like free().
    168  *
    169  *  @see psAlloc, psRealloc
    170  */
    171 #ifdef DOXYGEN
    172 void psFree(void *ptr,                  ///< Pointer to free, if NULL, function returns immediately.
    173            );
    174 #else
    175 void p_psFree(void *ptr,                ///< Pointer to free
    176               const char *file,         ///< File of call
    177               int lineno                ///< Line number of call
    178              );
    179 
    180174/// Free memory.  psFree sends file and line number to p_psFree.
    181 #define psFree(size) p_psFree(size, __FILE__, __LINE__)
    182 
    183 #endif
     175#        define psFree(size) p_psFree(size, __FILE__, __LINE__)
     176
     177#    endif
    184178
    185179/** Check for memory leaks.  This scans for allocated memory buffers not freed with an ID not less than id0.
     
    197191 *  @ingroup memTracing
    198192 */
    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 );
     193int 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                   );
    204197
    205198/** Check for memory corruption.  Scans all currently allocated memory buffers and checks for corruptions,
     
    208201 *  @ingroup memTracing
    209202 */
    210 int psMemCheckCorruption(
    211     bool abort_on_error              ///< Abort on detecting corruption?
    212 );
     203int psMemCheckCorruption(bool abort_on_error    // /< Abort on detecting corruption?
     204                        );
    213205
    214206/** Return reference counter
     
    216208 *  @ingroup memRefCount
    217209 */
    218 psReferenceCount psMemGetRefCounter(
    219     void *vptr                      ///< Pointer to get refCounter for
    220 );
     210psReferenceCount psMemGetRefCounter(void *vptr  // /< Pointer to get refCounter for
     211                                   );
    221212
    222213/** Increment reference counter and return the pointer
     
    224215 *  @ingroup memRefCount
    225216 */
    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
     218void *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
    238228
    239229/** Decrement reference counter and return the pointer
     
    241231 *  @ingroup memRefCount
    242232 */
    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
     234void *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
    255244
    256245/** Set callback for problems
    257246 *  @ingroup memCallback
    258247 */
    259 psMemProblemCallback psMemProblemCallbackSet(
    260     psMemProblemCallback func       ///< Function to run
    261 );
     248psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func  // /< Function to run
     249                                            );
    262250
    263251/** Set callback for out-of-memory
     
    265253 *  @ingroup memCallback
    266254 */
    267 psMemExhaustedCallback psMemExhaustedCallbackSet(
    268     psMemExhaustedCallback func     ///< Function to run
    269 );
     255psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func    // /< Function to run
     256                                                );
    270257
    271258/** Set call back for when a particular memory block is allocated
     
    273260 *  @ingroup memCallback
    274261 */
    275 psMemAllocateCallback psMemAllocateCallbackSet(
    276     psMemAllocateCallback func          ///< Function to run
    277 );
     262psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func       // /< Function to run
     263                                              );
    278264
    279265/** Set call back for when a particular memory block is freed
     
    281267 *  @ingroup memCallback
    282268 */
    283 psMemFreeCallback psMemFreeCallbackSet(
    284     psMemFreeCallback func              ///< Function to run
    285 );
     269psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func   // /< Function to run
     270                                      );
    286271
    287272/** get next memory ID
     
    295280 *  @ingroup memCallback
    296281 */
    297 psMemoryId psMemAllocateCallbackSetID(
    298     psMemoryId id                       ///< ID to set
    299 );
     282psMemoryId psMemAllocateCallbackSetID(psMemoryId id     // /< ID to set
     283                                     );
    300284
    301285/** set p_psMemFreeID to id
     
    303287 *  @ingroup memCallback
    304288 */
    305 psMemoryId psMemFreeCallbackSetID(
    306     psMemoryId id                       ///< ID to set
    307 );
     289psMemoryId psMemFreeCallbackSetID(psMemoryId id // /< ID to set
     290                                 );
    308291
    309292//@} End of Memory Management Functions
    310293
    311 #ifndef DOXYGEN
     294#    ifndef DOXYGEN
    312295
    313296/*
    314297 * Ensure that any program using malloc/realloc/free will fail to compile
    315298 */
    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
    12/** @file  psString.c
    23 *
     
    89 *  @author Eric Van Alst, MHPCC
    910 *   
    10  *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    1922#include <stdlib.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873
    59 char *psStringCopy(
    60     const char*  str
    61 )
     74char *psStringCopy(const char *str)
    6275{
    6376    // Allocate memory using psAlloc function
     
    6780}
    6881
    69 char *psStringNCopy(
    70     const char*  str,
    71     int          nChar
    72 )
     82char *psStringNCopy(const char *str, int nChar)
    7383{
    7484    char *returnValue = NULL;
    7585
    7686    // Check the number of characters to copy is non-negative
    77     if ( nChar < 0 ) {
     87    if (nChar < 0) {
    7888        // 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);
    8190        return NULL;
    8291    }
     
    8493    // Copy input string to memory allocated up to nChar characters
    8594    // 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);
    8796
    8897    // 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';
    91100    }
    92 
    93101    // Return the string pointer
    94102    return returnValue;
    95103}
    96 
    97 
  • trunk/psLib/src/sys/psString.h

    r974 r1407  
     1
    12/** @file  psString.h
    23 *
     
    1011 *  @author Eric Van Alst, MHPCC
    1112 *
    12  *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-06-10 01:58:06 $
     13 *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_STRING_H
    19 #define PS_STRING_H
     20#    define PS_STRING_H
    2021
    2122/******************************************************************************/
     23
    2224/*  DEFINE STATEMENTS                                                         */
     25
    2326/******************************************************************************/
    2427
    2528/** This macro will convert the arguement to a quoted string */
    26 #define PS_STRING(S)  #S
     29#    define PS_STRING(S)  #S
    2730
    2831/******************************************************************************/
     32
    2933/*  TYPE DEFINITIONS                                                          */
     34
    3035/******************************************************************************/
    3136
     
    3338
    3439/*****************************************************************************/
     40
    3541/* FUNCTION PROTOTYPES                                                       */
     42
    3643/*****************************************************************************/
    3744
    3845// Doxygen group tags
     46
    3947/** @addtogroup SysUtils
    4048 *  @{
     
    4957 *
    5058 */
    51 char *psStringCopy(
    52     const char *str      /**< Input string of characters to copy */
    53 );
    5459
     60char *psStringCopy(const char *str
     61                   /**< Input string of characters to copy */
     62                  );
    5563
    5664/** Copies the input string up to the specified number of characters
     
    6775 *
    6876 */
     77
    6978/*@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 );
    7479
    75 /* @} */  // Doxygen - End of SystemGroup Functions
     80char *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
    7688
    7789#endif
    78 
  • trunk/psLib/src/sys/psTrace.c

    r1406 r1407  
     1
    12/** @file psTrace.c
    23 *  \brief basic run-time trace facilities
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
     17
    1618/*****************************************************************************
    1719    NOTES:
     
    3436#ifndef PS_NO_TRACE
    3537
    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 component
    46 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
     47static p_psComponent *p_psCroot = NULL; // The root of the trace component
     48static FILE *p_psTraceFP = NULL;        // File destination for messages.
     49
     50static void componentFree(p_psComponent * comp);
     51static p_psComponent *componentAlloc(const char *name, int level);
    5052
    5153/*****************************************************************************
    5254componentAlloc(): allocate memory for a new node, and initialize members.
    5355 *****************************************************************************/
    54 static p_psComponent *componentAlloc(const char *name,
    55                                      int level)
     56static p_psComponent *componentAlloc(const char *name, int level)
    5657{
    5758    p_psComponent *comp = psAlloc(sizeof(p_psComponent));
    58     p_psMemSetDeallocator(comp,(psFreeFcn)componentFree);
     59
     60    p_psMemSetDeallocator(comp, (psFreeFcn) componentFree);
    5961    comp->name = psStringCopy(name);
    6062    comp->level = level;
     
    6466}
    6567
    66 
    6768/*****************************************************************************
    6869componentFree(): free the current node in the root tree, and all children
    6970nodes as well.
    7071 *****************************************************************************/
    71 static void componentFree(p_psComponent *comp)
     72static void componentFree(p_psComponent * comp)
    7273{
    7374    if (comp == NULL) {
     
    8586}
    8687
    87 
    8888/*****************************************************************************
    8989initTrace(): simply initialize the component root tree.
     
    9696}
    9797
    98 
    9998/*****************************************************************************
    10099Set all trace levels to zero.
    101100 *****************************************************************************/
    102 void p_psTraceReset(p_psComponent *currentNode)
     101void p_psTraceReset(p_psComponent * currentNode)
    103102{
    104103    int i = 0;
     
    109108
    110109    currentNode->level = 0;
    111     for (i=0;i<currentNode->n;i++) {
     110    for (i = 0; i < currentNode->n; i++) {
    112111        if (NULL == currentNode->subcomp[i]) {
    113112            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);
    116114        } else {
    117115            p_psTraceReset(currentNode->subcomp[i]);
     
    129127}
    130128
    131 
    132129/*****************************************************************************
    133130Free all nodes in the component tree.
     
    137134    psFree(p_psCroot);
    138135}
    139 
    140136
    141137/*****************************************************************************
     
    145141to ANSI-C.
    146142 *****************************************************************************/
    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
     143static 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
    154149    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.
    158153    if (strcmp(".", addNodeName) == 0) {
    159154        p_psCroot->level = level;
     
    162157
    163158    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);
    166160        exit(1);
    167161    }
     
    188182        if (nodeExists == 0) {
    189183            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}
    199191
    200192/*****************************************************************************
     
    210202*****************************************************************************/
    211203int psTraceSetLevel(const char *comp,   // component of interest
    212                     int level)          // desired trace level
     204                    int level)  // desired trace level
    213205{
    214206    // If the root component tree does not exist, then initialize it.
     
    216208        initTrace();
    217209    }
    218 
    219210    // Add the new component to the component tree.
    220211    componentAdd(comp, level);
     
    223214    return 0;
    224215}
    225 
    226216
    227217/*****************************************************************************
     
    241231static int doGetTraceLevel(const char *aname)
    242232{
    243     char       name[strlen(aname) + 1]; // need a writeable copy: for strsep()
    244     char      *pname=name;
    245     char      *firstComponent = NULL;   // first component of name
     233    char name[strlen(aname) + 1];      // need a writeable copy: for strsep()
     234    char *pname = name;
     235    char *firstComponent = NULL;        // first component of name
    246236    p_psComponent *currentNode = p_psCroot;
    247     int        i = 0;
     237    int i = 0;
    248238
    249239    if (NULL == currentNode) {
    250         return(PS_UNKNOWN_TRACE_LEVEL);
     240        return (PS_UNKNOWN_TRACE_LEVEL);
    251241    }
    252242
    253243    if (strcmp(".", aname) == 0) {
    254         return(p_psCroot->level);
     244        return (p_psCroot->level);
    255245    }
    256246
    257247    if (aname[0] != '.') {
    258         return(PS_UNKNOWN_TRACE_LEVEL);
     248        return (PS_UNKNOWN_TRACE_LEVEL);
    259249    }
    260250
     
    266256            if (NULL == currentNode->subcomp[i]) {
    267257                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);
    270259            }
    271260
     
    273262                currentNode = currentNode->subcomp[i];
    274263                if (pname == NULL) {
    275                     return(currentNode->level);
     264                    return (currentNode->level);
    276265                }
    277266            }
    278267        }
    279268    }
    280     return(PS_UNKNOWN_TRACE_LEVEL);
    281 }
    282 
     269    return (PS_UNKNOWN_TRACE_LEVEL);
     270}
    283271
    284272/*****************************************************************************
     
    297285{
    298286    if (p_psCroot == NULL) {
    299         return(PS_UNKNOWN_TRACE_LEVEL);
    300     }
    301 
     287        return (PS_UNKNOWN_TRACE_LEVEL);
     288    }
    302289    // Search the component root tree, determine the trace level.
    303     return(doGetTraceLevel(name));
    304 }
    305 
     290    return (doGetTraceLevel(name));
     291}
    306292
    307293/*****************************************************************************
     
    317303 null
    318304 *****************************************************************************/
    319 static void doPrintTraceLevels(const p_psComponent *comp,
    320                                int depth)
     305static void doPrintTraceLevels(const p_psComponent * comp, int depth)
    321306{
    322307    int i = 0;
     
    327312    } else {
    328313        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, ".");
    331315        } 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);
    334317        }
    335318    }
    336319
    337320    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}
    342324
    343325/*****************************************************************************
     
    359341    doPrintTraceLevels(p_psCroot, 0);
    360342}
    361 
    362343
    363344/*****************************************************************************
     
    376357 *****************************************************************************/
    377358void p_psTrace(const char *comp,        // component being traced
    378                int level,               // desired trace level
    379                ...)                     // arguments
     359               int level,       // desired trace level
     360               ...)             // arguments
    380361{
    381362    char *fmt = NULL;
     
    384365
    385366    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    }
    390369    // Only display this message if it's trace level is less than the level
    391370    // of it's associatedcomponent.
     
    413392        va_end(ap);
    414393    }
    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
     397void psTraceSetDestination(FILE * fp)
    420398{
    421399    p_psTraceFP = fp;
  • trunk/psLib/src/sys/psTrace.h

    r1393 r1407  
     1
    12/** @file psTrace.h
    23 *  \brief basic run-time trace facilities
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-05 19:38:52 $
     12 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    1617#if !defined(PS_TRACE_H)
    17 #define PS_TRACE_H 1
     18#    define PS_TRACE_H 1
    1819
    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
    2222
    2323/** \addtogroup LogTrace
     
    2929//#define PS_NO_TRACE 1   ///< to turn off all tracing
    3030
    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
    4145
    42 /** Basic structure for the component tree.  A component is a string of the
    43     form aaa.bbb.ccc, and may itself contain further subcomponents.  The
    44     Component structure doesn't in fact contain it's full name, but only the
    45     last part. */
    46 typedef struct p_psComponent
    47 {
    48     const char *name;                     // last part of name of component
    49     int level;                            // trace level for this component
    50     int n;                                // number of subcomponents
    51     struct p_psComponent **subcomp;           // next level of subcomponents
    52 }
     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        }
    5357p_psComponent;
    5458
    55 #ifndef DOXYGEN
     59#        ifndef DOXYGEN
    5660/// Send a trace message
    57 void p_psTrace(const char *facil,  ///< facilty of interest
    58                int myLevel,  ///< desired trace level
    59                ...)   ///< trace message arguments
     61void p_psTrace(const char *facil,       // /< facilty of interest
     62               int myLevel,     // /< desired trace level
     63               ...)             // /< trace message arguments
    6064;
    61 #endif
     65#        endif
    6266
    6367/// Set trace level
    64 int psTraceSetLevel(const char *facil, ///< facilty of interest
    65                     int level)  ///< desired trace level
     68int psTraceSetLevel(const char *facil,     // /< facilty of interest
     69                    int level)     // /< desired trace level
    6670;
    6771
    6872/// Get the trace level
    69 int psTraceGetLevel(const char *facil) ///< facilty of interest
     73int psTraceGetLevel(const char *facil)     // /< facilty of interest
    7074;
    7175
    7276/// Set all trace levels to zero (do not free nodes in the component tree).
    73 void psTraceReset()
    74 ;
     77void psTraceReset();
    7578
    7679/// Free all nodes in the component tree.
    77 void psTraceFree()
    78 ;
     80void psTraceFree();
    7981
    8082/// print trace levels
    81 void psTracePrintLevels(void)
    82 ;
     83void psTracePrintLevels(void);
    8384
    8485/// Set the destination of future trace messages.
    85 void psTraceSetDestination(FILE *fp);
     86void psTraceSetDestination(FILE * fp);
    8687
     88/* \} */// End of SystemGroup Functions
    8789
    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
    9292
    9393#endif
    94 
  • trunk/psLib/src/sys/psType.h

    r1385 r1407  
     1
    12/** @file  psType.h
    23*
     
    1011*  @author Ross Harman, MHPCC
    1112*
    12 *  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-04 23:37:39 $
     13*  @version $Revision: 1.17 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_TYPE_H
    19 #define PS_TYPE_H
     20#    define PS_TYPE_H
    2021
    21 #include <complex.h>
    22 #include <stdint.h>
    23 #include <float.h>
     22#    include <complex.h>
     23#    include <stdint.h>
     24#    include <float.h>
    2425
    2526/// @addtogroup DataContainer
     
    2728
    2829/******************************************************************************/
     30
    2931/*  TYPE DEFINITIONS                                                          */
     32
    3033/******************************************************************************/
    3134
     
    3740 */
    3841
    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 
     42typedef uint8_t psU8;           // /< 8-bit unsigned int
     43typedef uint16_t psU16;         // /< 16-bit unsigned int
     44typedef uint32_t psU32;         // /< 32-bit unsigned int
     45typedef uint64_t psU64;         // /< 64-bit unsigned int
     46typedef int8_t psS8;            // /< 8-bit signed int
     47typedef int16_t psS16;          // /< 16-bit signed int
     48typedef int32_t psS32;          // /< 32-bit signed int
     49typedef int64_t psS64;          // /< 64-bit signed int
     50typedef float psF32;            // /< 32-bit floating point
     51typedef double psF64;           // /< 64-bit floating point
     52typedef complex float psC32;    // /< complex with 32-bit floating point Real and Imagary numbers
     53typedef complex double psC64;   // /< complex with 64-bit floating point Real and Imagary numbers
     54typedef void *psPTR;            // /< void pointer
    5355
    5456typedef 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.
    6872} psElemType;
    6973
    70 #define PS_TYPE_MASK PS_TYPE_U8         ///< the psElemType to use for mask image
    71 #define PS_TYPE_MASK_DATA U8            ///< the data member to use for mask image
    72 #define PS_TYPE_MASK_NAME "psU8"
    73 typedef psU8 psMaskType;                ///< the C datatype for a mask image
     74#    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"
     77typedef psU8 psMaskType;        // /< the C datatype for a mask image
    7478
    75 #define PS_MIN_S8        INT8_MIN
    76 #define PS_MIN_S16       INT16_MIN
    77 #define PS_MIN_S32       INT32_MIN
    78 #define PS_MIN_S64       INT64_MIN
    79 #define PS_MIN_U8        0
    80 #define PS_MIN_U16       0
    81 #define PS_MIN_U32       0
    82 #define PS_MIN_U64       0
    83 #define PS_MIN_F32       -FLT_MAX
    84 #define PS_MIN_F64       -DBL_MAX
    85 #define PS_MIN_C32       -FLT_MAX
    86 #define PS_MIN_C64       -DBL_MAX
     79#    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
    8791
    88 #define PS_MAX_S8        INT8_MAX
    89 #define PS_MAX_S16       INT16_MAX
    90 #define PS_MAX_S32       INT32_MAX
    91 #define PS_MAX_S64       INT64_MAX
    92 #define PS_MAX_U8        UINT8_MAX
    93 #define PS_MAX_U16       UINT16_MAX
    94 #define PS_MAX_U32       UINT32_MAX
    95 #define PS_MAX_U64       UINT64_MAX
    96 #define PS_MAX_F32       FLT_MAX
    97 #define PS_MAX_F64       DBL_MAX
    98 #define PS_MAX_C32       FLT_MAX
    99 #define PS_MAX_C64       DBL_MAX
     92#    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
    100104
    101105/// Macro to get the bad pixel reason code (stored as part of mask value)
    102 #define PS_BADPIXEL_BITMASK 0x0f
    103 #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)
    104108
    105 #define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)
     109#    define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)
    106110
    107111/// 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) \
    109113{ \
    110114    maskValue = (psMaskType)((reasonCode & PS_BADPIXEL_BITMASK) | (maskValue & ~PS_BADPIXEL_BITMASK)); \
     
    112116
    113117/// 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)
    115119/// 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)
    117121/// 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)
    119123/// 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)
    121125/// 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) )
    123127
    124128/** Dimensions of a data type.
     
    128132 */
    129133typedef 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.
    135139} psDimen;
    136140
     
    143147typedef struct
    144148{
    145     psElemType type;    ///< Primitive type.
    146     psDimen dimen;      ///< Dimensionality.
     149    psElemType type;            // /< Primitive type.
     150    psDimen dimen;              // /< Dimensionality.
    147151}
    148152psType;
  • trunk/psLib/src/sysUtils/psAbort.c

    r1406 r1407  
     1
    12/** @file  psAbort.c
    23 *
     
    910 *  @author Eric Van Alst, MHPCC
    1011 *   
    11  *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1617
    1718/******************************************************************************/
     19
    1820/*  INCLUDE FILES                                                             */
     21
    1922/******************************************************************************/
    2023#include <stdarg.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873
    59 void psAbort(const char *name, const char *fmt,... )
     74void psAbort(const char *name, const char *fmt, ...)
    6075{
    61     va_list    argPtr;     // variable list arguement pointer
     76    va_list argPtr;             // variable list arguement pointer
    6277
    6378    // Get the variable list parameters to pass to logging function
     
    7388    abort();
    7489}
    75 
  • trunk/psLib/src/sysUtils/psAbort.h

    r974 r1407  
     1
    12/** @file  psAbort.h
    23 *
     
    1112 *  @author Eric Van Alst, MHPCC
    1213 *
    13  *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-06-10 01:58:06 $
     14 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_ABORT_H
    20 #define PS_ABORT_H
    21 
     21#    define PS_ABORT_H
    2222
    2323// Doxygen grouping tags
     24
    2425/** @addtogroup ErrorHandling
    2526 *  @{
     
    3637 *
    3738 */
    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 );
     39void 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            );
    4343
    44 /* @} */  // Doxygen - End of SystemGroup Functions
     44/* @} */// Doxygen - End of SystemGroup Functions
    4545
    4646#endif
    47 
  • trunk/psLib/src/sysUtils/psError.c

    r1406 r1407  
     1
    12/** @file  psError.c
    23 *
     
    1011 *  @author Eric Van Alst, MHPCC
    1112 *   
    12  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819/******************************************************************************/
     20
    1921/*  INCLUDE FILES                                                             */
     22
    2023/******************************************************************************/
    2124#include <stdarg.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATIONS - LOCAL                                         */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATIONS - PUBLIC                                         */
     71
    5772/*****************************************************************************/
    5873
    59 void psError(const char *name,const char *fmt, ...)
     74void psError(const char *name, const char *fmt, ...)
    6075{
    61     va_list    argPtr;        // variable list arguement pointer
     76    va_list argPtr;             // variable list arguement pointer
    6277
    63     // Get the variable list parameters  to pass to logging function
     78    // Get the variable list parameters to pass to logging function
    6479    va_start(argPtr, fmt);
    6580
     
    7085    va_end(argPtr);
    7186}
    72 
  • trunk/psLib/src/sysUtils/psError.h

    r974 r1407  
     1
    12/** @file  psError.h
    23 *
     
    1213 *  @author Eric Van Alst, MHPCC
    1314 *
    14  *  @version $Revision: 1.4 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-06-10 01:58:06 $
     15 *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PS_ERROR_H
    21 #define PS_ERROR_H
     22#    define PS_ERROR_H
    2223
    2324/** @addtogroup ErrorHandling
     
    3435 *
    3536 */
    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 );
     37void 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            );
    4141
    42 /* @} */  // End of SysUtils Functions
     42/* @} */// End of SysUtils Functions
    4343
    4444#endif
    45 
  • trunk/psLib/src/sysUtils/psHash.c

    r1406 r1407  
     1
    12/** @file  psHash.c
    23*
     
    1011*  @author George Gusciora, MHPCC
    1112*
    12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-06 22:34:05 $
     13*  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    2526#include "psAbort.h"
    2627
    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 );
     28static psHashBucket *hashBucketAlloc(const char *key, void *data, psHashBucket * next);
     29static void hashBucketFree(psHashBucket * bucket);
     30static void *doHashWork(psHash * table, const char *key, void *data, bool remove
     31                           );
     32static void hashFree(psHash * table);
    3333
    3434/******************************************************************************
     
    4040    The linked list
    4141 *****************************************************************************/
    42 psList *psHashKeyList( psHash *table )
    43 {
    44     int i = 0;                          // Loop index variable
     42psList *psHashKeyList(psHash * table)
     43{
     44    int i = 0;                  // Loop index variable
    4545    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) {
    4949        return NULL;
    5050    }
    51 
    5251    // Create the linked list
    53     myLinkList = psListAlloc( NULL );
     52    myLinkList = psListAlloc(NULL);
    5453
    5554    // Loop through every bucket in the hash table.  If that bucket is not
    5655    // 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) {
    5958            // Since a bucket contains a linked list of keys/data, we must
    6059            // step trough each key in that linked list:
    6160
    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);
    6564                ptr = ptr->next;
    6665            }
     
    6968
    7069    // Return the linked list
    71     return ( myLinkList );
    72 }
    73 
    74 
     70    return (myLinkList);
     71}
    7572
    7673/******************************************************************************
     
    8481    the new hash bucket.
    8582 *****************************************************************************/
    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 
     83static psHashBucket *hashBucketAlloc(const char *key, void *data, psHashBucket * next)
     84{
     85    if (key == NULL) {
     86        psAbort(__func__, "psHashBucket() called with NULL key.");
     87    }
    9488    // 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);
    9792
    9893    // Initialize the bucket.
    99     bucket->key = psStringCopy( key );
    100 
    101     if ( data == NULL ) {
     94    bucket->key = psStringCopy(key);
     95
     96    if (data == NULL) {
    10297        // NOTE: Should we flag a warning message?
    10398        bucket->data = NULL;
    10499    } else {
    105         bucket->data = psMemIncrRefCounter( data );
     100        bucket->data = psMemIncrRefCounter(data);
    106101    }
    107102
     
    110105    return bucket;
    111106}
    112 
    113107
    114108/******************************************************************************
     
    120114    NONE
    121115 *****************************************************************************/
    122 static void hashBucketFree( psHashBucket *bucket )
    123 {
    124     if ( bucket == NULL ) {
    125         return ;
    126     }
    127 
     116static void hashBucketFree(psHashBucket * bucket)
     117{
     118    if (bucket == NULL) {
     119        return;
     120    }
    128121    // A bucket is actually a linked list of buckets.  We recursively step
    129122    // 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}
    137129
    138130/******************************************************************************
     
    144136    The new hash table.
    145137 *****************************************************************************/
    146 psHash *psHashAlloc( int nbucket )   // initial number of buckets
    147 {
    148     int i = 0;   // loop index variable
     138psHash *psHashAlloc(int nbucket)        // initial number of buckets
     139{
     140    int i = 0;                  // loop index variable
     141
    149142    // 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);
    152146
    153147    // Allocate memory for the buckets.
    154     table->buckets = psAlloc( nbucket * sizeof( psHashBucket * ) );
     148    table->buckets = psAlloc(nbucket * sizeof(psHashBucket *));
    155149    table->nbucket = nbucket;
    156150
    157     psTrace( "utils.hash", 1, "Creating %d-element hash table\n", nbucket );
     151    psTrace("utils.hash", 1, "Creating %d-element hash table\n", nbucket);
    158152
    159153    // Initialize all buckets to NULL.
    160     for ( i = 0; i < nbucket; i++ )
     154    for (i = 0; i < nbucket; i++)
    161155    {
    162         table->buckets[ i ] = NULL;
     156        table->buckets[i] = NULL;
    163157    }
    164158
     
    166160    return table;
    167161}
    168 
    169 
    170162
    171163/******************************************************************************
     
    179171    NONE
    180172 *****************************************************************************/
    181 static void hashFree( psHash *table )
    182 {
    183     int i = 0;                          // Loop index variable.
    184 
    185     if ( table == NULL ) {
    186         return ;
    187     }
    188 
     173static void hashFree(psHash * table)
     174{
     175    int i = 0;                  // Loop index variable.
     176
     177    if (table == NULL) {
     178        return;
     179    }
    189180    // Loop through each bucket in the hash table.  If that bucket is not
    190181    // 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++) {
    192183
    193184        // 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]);
    196187        }
    197188    }
    198189
    199190    // Free the bucket structure, then the hash table.
    200     psFree( table->buckets );
     191    psFree(table->buckets);
    201192}
    202193
     
    220211there is little common code between those functions.
    221212  *****************************************************************************/
    222 static void *doHashWork( psHash *table, const char *key, void *data, bool remove
     213static void *doHashWork(psHash * table, const char *key, void *data, bool remove
    223214                           )
    224215{
    225     long int hash = 1;                  // This will contain an integer value
     216    long int hash = 1;          // This will contain an integer value
     217
    226218    // "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
    230223    // thru the linked list for a bucket.
    231224
     
    233226    // function, but I'm checking it anyway since future coders might change
    234227    // 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    }
    240232    // 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);
    245237
    246238    // This hash algorithm is from Sedgewick.  NOTE: must reread to ensure that
    247239    // 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);
    251243    }
    252244
    253245    // NOTE: This should not be necessary, but for now, I'm checking bounds
    254246    // 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    }
    259250    // ptr will have the correct hash bucket.
    260     ptr = table->buckets[ hash ];
     251    ptr = table->buckets[hash];
    261252
    262253    // We know the correct hash bucket, now we need to know what to do.
     
    264255    // or a remove operation on the hash table.
    265256
    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                }
    272283                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;
    295285            }
     286            return NULL;                   // not in hash
     287        }
    296288        else {
    297289            // If we get here, then a retrieve operation is requested.  So,
    298290            // we step trough the linked list at this bucket, and return the
    299291            // 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) {
    302294                    return ptr->data;
    303295                }
    304296                ptr = ptr->next;
    305297            }
    306             return NULL;   // not in hash
     298            return NULL;                   // not in hash
    307299        }
    308300    } else {
     
    312304        // the hash table and look for a duplicate entry for this key.
    313305
    314         while ( ptr != NULL ) {
    315             if ( strcmp( key, ptr->key ) == 0 ) {
     306        while (ptr != NULL) {
     307            if (strcmp(key, ptr->key) == 0) {
    316308                // We have found this key in the hash table.
    317309
    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);
    320311
    321312                // NOTE: I have changed this behavior from the originally
     
    323314                // the new data was not inserted into the hash table.
    324315
    325                 psFree( ptr->data );
    326 
    327                 ptr->data = psMemIncrRefCounter( data );
     316                psFree(ptr->data);
     317
     318                ptr->data = psMemIncrRefCounter(data);
    328319                return data;
    329320            }
     
    333324        // table.  So, we insert this data at the head of that linked list.
    334325
    335         table->buckets[ hash ] = hashBucketAlloc( key,
    336                                  data,
    337                                  table->buckets[ hash ] );
     326        table->buckets[hash] = hashBucketAlloc(key, data, table->buckets[hash]);
    338327        return data;
    339328    }
     
    351340    boolean value defining success or failure
    352341 *****************************************************************************/
    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 );
     342bool 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);
    366355}
    367356
     
    377366    The data associated with that key.
    378367 *****************************************************************************/
    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 );
     368void *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);
    391379}
    392380
     
    401389    boolean value defining success or failure
    402390 *****************************************************************************/
    403 bool psHashRemove( psHash *table, const char *key )
    404 {
    405     void * data = NULL;
     391bool psHashRemove(psHash * table, const char *key)
     392{
     393    void *data = NULL;
    406394    bool retVal = false;
    407395
    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);
    418406        retVal = true;
    419407    } else {
  • trunk/psLib/src/sysUtils/psHash.h

    r1406 r1407  
     1
    12/** @file  psHash.h
    23 *  @brief Contains support for basic hashing functions.
     
    1011 *  @author George Gusciora, MHPCC
    1112 *   
    12  *  @version $Revision: 1.18 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.19 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617 */
    1718#if !defined(PS_HASH_H)
    18 #define PS_HASH_H
     19#    define PS_HASH_H
    1920
    2021/** \addtogroup HashTable
    2122 *  \{
    2223 */
    23 #include<stdbool.h>
     24#    include<stdbool.h>
    2425
    25 #include "psList.h"
     26#    include "psList.h"
    2627
    2728/** A bucket that holds an item of data. */
    2829typedef struct psHashBucket
    2930{
    30     char *key;                          ///< key for this item of data
    31     void *data;                         ///< the data itself
    32     struct psHashBucket *next;          ///< list of other possible keys
     31    char *key;                  // /< key for this item of data
     32    void *data;                 // /< the data itself
     33    struct psHashBucket *next;  // /< list of other possible keys
    3334}
    3435psHashBucket;
    3536
    3637//typedef struct HashTable psHash; ///< Opaque type for a hash table
     38
    3739/** The hash-table itself. */
    3840typedef struct psHash
    3941{
    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.
    4244}
    4345psHash;
    4446
    4547/// Allocate hash buckets in table.
    46 psHash *psHashAlloc(int nbucket       ///< The number of buckets to allocate.
     48psHash *psHashAlloc(int nbucket // /< The number of buckets to allocate.
    4749                   );
    4850
    4951/// Insert entry into table.
    50 bool psHashAdd(psHash *table,               ///< table to insert in
    51                const char *key,             ///< key to use
    52                void *data                   ///< data to insert
     52bool psHashAdd(psHash * table,  // /< table to insert in
     53               const char *key, // /< key to use
     54               void *data       // /< data to insert
    5355              );
    5456
    5557/// Lookup key in table.
    56 void *psHashLookup(psHash *table,      ///< table to lookup key in
    57                    const char *key     ///< key to lookup
     58void *psHashLookup(psHash * table,      // /< table to lookup key in
     59                   const char *key      // /< key to lookup
    5860                  );
    5961
    6062/// Remove key from table.
    61 bool psHashRemove(psHash *table,      ///< table to lookup key in
    62                   const char *key     ///< key to lookup
     63bool psHashRemove(psHash * table,       // /< table to lookup key in
     64                  const char *key       // /< key to lookup
    6365                 );
    6466
    6567/// List all keys in table.
    66 psList *psHashKeyList(psHash *table  ///< table to list keys from.
     68psList *psHashKeyList(psHash * table    // /< table to list keys from.
    6769                     );
    6870
    69 /* \} */ // End of DataGroup Functions
     71/* \} */// End of DataGroup Functions
    7072
    7173#endif
  • trunk/psLib/src/sysUtils/psLogMsg.c

    r1406 r1407  
     1
    12/** @file  psLogMsg.c
    23 *  @brief Procedures for logging messages.
     
    1112 *  @author George Gusciora, MHPCC
    1213 *
    13  *  @version $Revision: 1.23 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.24 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    4445
    4546#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 above
    48 static bool logTime = true;            // Flag to include time info
    49 static bool logHost = true;            // Flag to include host info
    50 static bool logLevel = true;           // Flag to include level info
    51 static bool logName = true;            // Flag to include name info
    52 static bool logMsg = true;             // Flag to include message info
     47static FILE *logDest = (FILE *) 1;      // flag to initialize to stderr before using.
     48static int globalLogLevel = PS_LOG_INFO;        // log all messages at this or above
     49static bool logTime = true;     // Flag to include time info
     50static bool logHost = true;     // Flag to include host info
     51static bool logLevel = true;    // Flag to include level info
     52static bool logName = true;     // Flag to include name info
     53static bool logMsg = true;      // Flag to include message info
    5354
    5455/*****************************************************************************
     
    6768
    6869    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);
    7171        level = (level < MIN_LOG_LEVEL) ? MIN_LOG_LEVEL : MAX_LOG_LEVEL;
    7272    }
    73 
    7473    // Set new global log level
    7574    globalLogLevel = level;
     
    7877    return oldLevel;
    7978}
    80 
    8179
    8280/*****************************************************************************
     
    9189 An integer specifying the old log destination.
    9290 *****************************************************************************/
    93 int psLogSetDestination(const char* dest)
     91int psLogSetDestination(const char *dest)
    9492{
    9593    char protocol[5];
     
    9795
    9896    // if logDest has not been initialized, do so before using it
    99     if (logDest==(FILE*)1) {
     97    if (logDest == (FILE *) 1) {
    10098        logDest = stderr;
    10199    }
    102100
    103     if (dest == NULL || strcmp(dest,"none")==0) {
     101    if (dest == NULL || strcmp(dest, "none") == 0) {
    104102        if (logDest != NULL && logDest != stderr && logDest != stdout) {
    105103            fclose(logDest);
     
    109107    }
    110108
    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);
    113111        return 1;
    114112    }
    115113
    116     if (strcmp(protocol,"dest") == 0) {
    117         if (strcmp(location,"stderr") == 0) {
     114    if (strcmp(protocol, "dest") == 0) {
     115        if (strcmp(location, "stderr") == 0) {
    118116            if (logDest != NULL && logDest != stderr && logDest != stdout) {
    119117                fclose(logDest);
     
    122120            return 0;
    123121        }
    124         if (strcmp(location,"stdout") == 0) {
     122        if (strcmp(location, "stdout") == 0) {
    125123            if (logDest != NULL && logDest != stderr && logDest != stdout) {
    126124                fclose(logDest);
     
    129127            return 0;
    130128        }
    131         psError(__func__,"The location, %s, for protocol 'dest' is invalid.",location);
     129        psError(__func__, "The location, %s, for protocol 'dest' is invalid.", location);
    132130        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);
    148146    return 1;
    149147}
     
    181179        fmt = "THLNM";
    182180    }
    183 
    184181    // Step through each character in the format string.  For each letter
    185182    // in that string, set/unset the appropriate logging.
     
    214211
    215212    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
    226219#endif
     220
    227221/*****************************************************************************
    228222    psVLogMsg(): This routine sends the message, which is a printf style
     
    239233 NULL.
    240234 *****************************************************************************/
    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()
     235void psLogMsgV(const char *name, int level, const char *fmt, va_list ap)
     236{
     237    static int first = 1;       // Flag for calling gethostname()
    247238    static char hostname[HOST_NAME_MAX + 1];
     239
    248240    // Buffer for hostname.
    249     char clevel=0;                      // letter-name for level
    250     char head[MAX_LOG_LINE_LENGTH+2];  // the added two are for the ending | and \0
    251     char *head_ptr = head;              // where we've got to in head
     241    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
    252244    int maxLength = MAX_LOG_LINE_LENGTH;
    253     time_t clock = time(NULL);          // The current time.
     245    time_t clock = time(NULL);  // The current time.
    254246    struct tm *utc = gmtime(&clock);    // The current gm time.
    255247
    256248    // if logDest has not been initialized, do so before using it
    257     if (logDest==(FILE*)1) {
     249    if (logDest == (FILE *) 1) {
    258250        logDest = stderr;
    259251    }
    260 
    261252    // If logging is off, or if the level is too high, return immediately.
    262253    if ((level > globalLogLevel) || (logDest == NULL)) {
    263254        return;
    264255    }
    265 
    266256    // If I have not been here yet, determine my hostname and save it.
    267257    if (first) {
     
    297287
    298288    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);
    301290        level = (level < 0) ? 0 : 9;
    302291        break;
     
    307296        maxLength -= snprintf(head_ptr, maxLength, "%4d:%02d:%02d %02d:%02d:%02dZ",
    308297                              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;
    310299        head_ptr += strlen(head_ptr);
    311300    }
     
    336325    if (head_ptr > head) {
    337326        *head_ptr++ = '|';
    338     } else
    339         if (!logMsg) { // no output desired
    340             return;
    341         }
     327    } else if (!logMsg) {                  // no output desired
     328        return;
     329    }
    342330    *head_ptr = '\0';
    343331
     
    352340    }
    353341}
    354 
    355342
    356343/*****************************************************************************
     
    369356 NULL
    370357 *****************************************************************************/
    371 void psLogMsg(const char *name,
    372               int level,
    373               const char *fmt,
    374               ...)
     358void psLogMsg(const char *name, int level, const char *fmt, ...)
    375359{
    376360    va_list ap;
  • trunk/psLib/src/sysUtils/psLogMsg.h

    r1406 r1407  
     1
    12/** @file  psLogMsg.h
    23 *  @brief Procedures for logging messages.
     
    1112 *  @author George Gusciora, MHPCC
    1213 *
    13  *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-08-06 22:34:05 $
     14 *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1718 */
    1819#if !defined(PS_LOG_MSG_H)
    19 #define PS_LOG_MSG_H
    20 #include <stdarg.h>
     20#    define PS_LOG_MSG_H
     21#    include <stdarg.h>
    2122
    2223/** @addtogroup LogTrace
     
    2930/// In future versions, this procedure will take a character string as an
    3031/// argument which can specify more general log destinations.
    31 int psLogSetDestination(const char* dest   ///< Specifies where to send messages.
     32int psLogSetDestination(const char *dest        // /< Specifies where to send messages.
    3233                       );
    33 
    3434
    3535/// This procedure sets the message level for future log messages.  Subsequent
     
    3838/// Ie. higher values set by this procedure will cause more log messages to
    3939/// be displayed.
    40 int psLogSetLevel(int level          ///< Specifies the system log level
     40int psLogSetLevel(int level     // /< Specifies the system log level
    4141                 );
    42 
    4342
    4443/// This procedure sets the log format for future log messages.  The argument
     
    4746/// Deleting a letter from the string will cause the associated information
    4847/// to not be logged.
    49 void psLogSetFormat(const char *fmt ///< Specifies the system log format
     48void psLogSetFormat(const char *fmt     // /< Specifies the system log format
    5049                   );
    51 
    5250
    5351/// This procedure logs a message to the destination set by a prior
     
    5553/// specified by a prior call to psLogSetLevel().  The message is specified
    5654/// with a printf-stype string an arguments.
    57 void psLogMsg(const char *name,     ///< name of the log source
    58               int myLevel,          ///< severity level of this log message
    59               const char *fmt, ...  ///< printf-style format command
     55void 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
    6058             );
    61 
    6259
    6360/// This procedure is functionally equivalent to psLogMsg(), except that
    6461/// it takes a va_list as the message parameter, not a printf-style string.
    65 void psLogMsgV(const char *name, ///< name of the log source
    66                int myLevel,      ///< severity level of this log message
    67                const char *fmt,  ///< printf-style format command
    68                va_list ap        ///< varargs argument list
     62void 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
    6966              );
    7067
     
    7471    PS_LOG_ERROR,
    7572    PS_LOG_WARN,
    76     PS_LOG_INFO };
     73    PS_LOG_INFO
     74};
    7775
    7876///< Destinations for log messages
     
    8078    PS_LOG_NONE,
    8179    PS_LOG_TO_STDERR,
    82     PS_LOG_TO_STDOUT };
     80    PS_LOG_TO_STDOUT
     81};
    8382
    8483/// @}
  • trunk/psLib/src/sysUtils/psMemory.c

    r1406 r1407  
     1
    12/** @file  psMemory.c
    23*
     
    89*  @author Robert Lupton, Princeton University
    910*
    10 *  @version $Revision: 1.32 $ $Name: not supported by cvs2svn $
    11 *  @date $Date: 2004-08-06 22:34:05 $
     11*  @version $Revision: 1.33 $ $Name: not supported by cvs2svn $
     12*  @date $Date: 2004-08-07 00:06:06 $
    1213*
    1314*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1415*/
    1516
    16 #define PS_ALLOW_MALLOC                 // we're allowed to call malloc()
     17#define PS_ALLOW_MALLOC                    // we're allowed to call malloc()
    1718
    1819#include <stdlib.h>
     
    2627#include "psLogMsg.h"
    2728
    28 #define P_PS_MEMMAGIC (void *)0xdeadbeef // Magic number in psMemBlock header
    29 
    30 #define P_PS_LARGE_BLOCK_SIZE 65536    // size where under, we try to recycle
    31 
    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
     33static int checkMemBlock(const psMemBlock * m, const char *funcName);
    3334static psMemBlock *lastMemBlockAllocated = NULL;
    3435static pthread_mutex_t memBlockListMutex = PTHREAD_MUTEX_INITIALIZER;
     
    3839
    3940static 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_SIZE
    43     };
     41static int recycleBinSize[14] = {
     42                                    8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, P_PS_LARGE_BLOCK_SIZE
     43                                };
     44
    4445// 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     };
     46static psMemBlock *recycleMemBlockList[13] = {
     47            NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
     48        };
    4949
    5050#ifdef PS_MEM_DEBUG
    51 static psMemBlock* deadBlockList;    // a place to put dead memBlocks in debug mode.
     51static psMemBlock *deadBlockList;       // a place to put dead memBlocks in debug mode.
    5252#endif
     53
    5354/**
    5455 * Unique ID for allocated blocks
     
    5960 *  Default memExhausted callback.
    6061 */
    61 static void *memExhaustedCallbackDefault( size_t size )
    62 {
    63     void * ptr = NULL;
    64 
    65     pthread_mutex_lock( &recycleMemBlockListMutex );
     62static void *memExhaustedCallbackDefault(size_t size)
     63{
     64    void *ptr = NULL;
     65
     66    pthread_mutex_lock(&recycleMemBlockListMutex);
    6667    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);
    7376        }
    7477        level--;
    7578    }
    76     pthread_mutex_unlock( &recycleMemBlockListMutex );
     79    pthread_mutex_unlock(&recycleMemBlockListMutex);
    7780
    7881    return ptr;
     
    8184static psMemExhaustedCallback memExhaustedCallback = memExhaustedCallbackDefault;
    8285
    83 psMemExhaustedCallback psMemExhaustedCallbackSet( psMemExhaustedCallback func )
     86psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func)
    8487{
    8588    psMemExhaustedCallback old = memExhaustedCallback;
    8689
    87     if ( func != NULL ) {
     90    if (func != NULL) {
    8891        memExhaustedCallback = func;
    8992    } else {
     
    9497}
    9598
    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 );
     99static 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);
    107109    }
    108110}
    109111static psMemProblemCallback memProblemCallback = memProblemCallbackDefault;
    110112
    111 psMemProblemCallback psMemProblemCallbackSet( psMemProblemCallback func )
     113psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func)
    112114{
    113115    psMemProblemCallback old = memProblemCallback;
    114116
    115     if ( func != NULL ) {
     117    if (func != NULL) {
    116118        memProblemCallback = func;
    117119    } else {
     
    121123    return old;
    122124}
     125
    123126/*
    124127 * And now the I-want-to-be-informed callbacks
     
    126129 * Call the callbacks when these IDs are allocated/freed
    127130 */
    128 psMemoryId p_psMemAllocateID = 0;  // notify user this block is allocated
     131psMemoryId p_psMemAllocateID = 0;       // notify user this block is allocated
    129132psMemoryId p_psMemFreeID = 0;   // notify user this block is freed
    130133
    131 psMemoryId psMemAllocateCallbackSetID( psMemoryId id )
     134psMemoryId psMemAllocateCallbackSetID(psMemoryId id)
    132135{
    133136    psMemoryId old = p_psMemAllocateID;
     137
    134138    p_psMemAllocateID = id;
    135139
     
    137141}
    138142
    139 psMemoryId psMemFreeCallbackSetID( psMemoryId id )
     143psMemoryId psMemFreeCallbackSetID(psMemoryId id)
    140144{
    141145    psMemoryId old = p_psMemFreeID;
     146
    142147    p_psMemFreeID = id;
    143148
     
    151156 * isn't resignalled)
    152157 */
    153 static psMemoryId memAllocateCallbackDefault( const psMemBlock *ptr )
    154 {
    155     static psMemoryId incr = 0;  // "p_psMemAllocateID += incr"
     158static psMemoryId memAllocateCallbackDefault(const psMemBlock * ptr)
     159{
     160    static psMemoryId incr = 0; // "p_psMemAllocateID += incr"
    156161
    157162    return incr;
    158163}
    159164
    160 static psMemoryId memFreeCallbackDefault( const psMemBlock *ptr )
    161 {
    162     static psMemoryId incr = 0;  // "p_psMemFreeID += incr"
     165static psMemoryId memFreeCallbackDefault(const psMemBlock * ptr)
     166{
     167    static psMemoryId incr = 0; // "p_psMemFreeID += incr"
    163168
    164169    return incr;
     
    171176static psMemFreeCallback memFreeCallback = memFreeCallbackDefault;
    172177
    173 psMemAllocateCallback psMemAllocateCallbackSet( psMemAllocateCallback func )
     178psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func)
    174179{
    175180    psMemFreeCallback old = memAllocateCallback;
    176181
    177     if ( func != NULL ) {
     182    if (func != NULL) {
    178183        memAllocateCallback = func;
    179184    } else {
     
    184189}
    185190
    186 psMemFreeCallback psMemFreeCallbackSet( psMemFreeCallback func )
     191psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func)
    187192{
    188193    psMemFreeCallback old = memFreeCallback;
    189194
    190     if ( func != NULL ) {
     195    if (func != NULL) {
    191196        memFreeCallback = func;
    192197    } else {
     
    200205 * Return memory ID counter for next block to be allocated
    201206 */
    202 psMemoryId psMemGetId( void )
     207psMemoryId psMemGetId(void)
    203208{
    204209    psMemoryId id;
    205     pthread_mutex_lock( &memIdMutex );
     210
     211    pthread_mutex_lock(&memIdMutex);
    206212    id = memid + 1;
    207     pthread_mutex_unlock( &memIdMutex );
     213    pthread_mutex_unlock(&memIdMutex);
    208214
    209215    return id;
     
    216222 */
    217223
    218 static int checkMemBlock( const psMemBlock *m, const char* funcName )
     224static int checkMemBlock(const psMemBlock * m, const char *funcName)
    219225{
    220226    // n.b. since this is called by psMemCheckCorruption while the memblock list is mutex locked,
    221227    // we shouldn't call such things as p_psAlloc/p_psFree here.
    222228
    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.");
    225231        return 1;
    226232    }
    227233
    228     if ( m->refCounter == 0 ) {
     234    if (m->refCounter == 0) {
    229235        // 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);
    232237        return 1;
    233238    }
    234239
    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);
    238242        return 1;
    239243    }
    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);
    243246        return 1;
    244247    }
     
    247250}
    248251
    249 int psMemCheckCorruption( bool abort_on_error )
    250 {
    251     int nbad = 0;                       // number of bad blocks
     252int psMemCheckCorruption(bool abort_on_error)
     253{
     254    int nbad = 0;               // number of bad blocks
    252255
    253256    // 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__)) {
    258261            nbad++;
    259262
    260             memProblemCallback( iter, __func__, __LINE__ );
    261 
    262             if ( abort_on_error ) {
     263            memProblemCallback(iter, __func__, __LINE__);
     264
     265            if (abort_on_error) {
    263266                // 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");
    266269                return nbad;
    267270            }
     
    270273
    271274    // release the lock on the memblock list
    272     pthread_mutex_unlock( &memBlockListMutex );
     275    pthread_mutex_unlock(&memBlockListMutex);
    273276    return nbad;
    274277}
    275278
    276 void *p_psAlloc( size_t size, const char *file, int lineno )
    277 {
    278 
    279     psMemBlock * ptr = NULL;
     279void *p_psAlloc(size_t size, const char *file, int lineno)
     280{
     281
     282    psMemBlock *ptr = NULL;
    280283
    281284    // 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) {
    283286        // find the bin we need.
    284287        int level = 0;
    285         while ( size > recycleBinSize[ level ] ) {
     288
     289        while (size > recycleBinSize[level]) {
    286290            level++;
    287291        }
    288292        // 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;
    300304                }
    301305                size = ptr->userMemorySize;
    302306            }
    303307
    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);
    316319            }
    317320        }
     
    320323        ptr->endblock = P_PS_MEMMAGIC;
    321324        ptr->userMemorySize = size;
    322         pthread_mutex_init( &ptr->refCounterMutex, NULL );
    323     }
    324 
     325        pthread_mutex_init(&ptr->refCounterMutex, NULL);
     326    }
    325327    // 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);
    329331
    330332    ptr->file = file;
    331333    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;
    334336    ptr->previousBlock = NULL;
    335337
    336     ptr->refCounter = 1;                // one user so far
     338    ptr->refCounter = 1;                   // one user so far
    337339
    338340    // need exclusive access of the memory block list now...
    339     pthread_mutex_lock( &memBlockListMutex );
     341    pthread_mutex_lock(&memBlockListMutex);
    340342
    341343    // insert the new block to the front of the memBlock linked-list
    342344    ptr->nextBlock = lastMemBlockAllocated;
    343     if ( ptr->nextBlock != NULL ) {
     345    if (ptr->nextBlock != NULL) {
    344346        ptr->nextBlock->previousBlock = ptr;
    345347    }
    346348    lastMemBlockAllocated = ptr;
    347349
    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    }
    355356    // And return the user the memory that they allocated
    356     return ptr + 1;   // user memory
    357 }
    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
     360void *p_psRealloc(void *vptr, size_t size, const char *file, int lineno)
     361{
     362    if (vptr == NULL) {
     363        return p_psAlloc(size, file, lineno);
    363364    } else {
    364         psMemBlock *ptr = ( ( psMemBlock * ) vptr ) - 1;
     365        psMemBlock *ptr = ((psMemBlock *) vptr) - 1;
    365366        bool isBlockLast = false;
    366367
    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);
    382382        }
    383383
    384384        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) {
    388388            lastMemBlockAllocated = ptr;
    389389        }
    390 
    391390        // the block location may have changed, so fix the linked list addresses.
    392         if ( ptr->nextBlock != NULL ) {
     391        if (ptr->nextBlock != NULL) {
    393392            ptr->nextBlock->previousBlock = ptr;
    394393        }
    395         if ( ptr->previousBlock != NULL ) {
     394        if (ptr->previousBlock != NULL) {
    396395            ptr->previousBlock->nextBlock = ptr;
    397396        }
    398397
    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 memory
    407     }
    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
     409void p_psFree(void *vptr, const char *file, int lineno)
     410{
     411    (void)p_psMemDecrRefCounter(vptr, file, lineno);    // this handles the free, if required.
    413412}
    414413
     
    416415 * Check for memory leaks.
    417416 */
    418 int psMemCheckLeaks( psMemoryId id0, psMemBlock ***arr, FILE *fd )
     417int psMemCheckLeaks(psMemoryId id0, psMemBlock *** arr, FILE * fd)
    419418{
    420419    int nleak = 0;
    421420    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)) {
    428427            nleak++;
    429428
    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");
    433432                }
    434433
    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) {
    443442        return nleak;
    444443    }
    445444
    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 all
     445    *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
    453452                break;
    454453            }
     
    456455    }
    457456
    458     pthread_mutex_unlock( &memBlockListMutex );
     457    pthread_mutex_unlock(&memBlockListMutex);
    459458
    460459    return nleak;
     
    465464 */
    466465// return refCounter
    467 psReferenceCount psMemGetRefCounter( void *vptr )
    468 {
    469     psMemBlock * ptr;
     466psReferenceCount psMemGetRefCounter(void *vptr)
     467{
     468    psMemBlock *ptr;
    470469    unsigned int refCount;
    471470
    472     if ( vptr == NULL ) {
     471    if (vptr == NULL) {
    473472        return 0;
    474473    }
    475474
    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);
    483482    refCount = ptr->refCounter;
    484     pthread_mutex_unlock( &ptr->refCounterMutex );
     483    pthread_mutex_unlock(&ptr->refCounterMutex);
    485484
    486485    return refCount;
    487486}
     487
    488488// increment and return refCounter
    489 void* p_psMemIncrRefCounter( void *vptr, const char *file, int lineno )
    490 {
    491     psMemBlock * ptr;
    492 
    493     if ( vptr == NULL ) {
     489void *p_psMemIncrRefCounter(void *vptr, const char *file, int lineno)
     490{
     491    psMemBlock *ptr;
     492
     493    if (vptr == NULL) {
    494494        return vptr;
    495495    }
    496496
    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);
    504504    ptr->refCounter++;
    505     pthread_mutex_unlock( &ptr->refCounterMutex );
     505    pthread_mutex_unlock(&ptr->refCounterMutex);
    506506
    507507    return vptr;
     
    509509
    510510// decrement and return refCounter
    511 void* p_psMemDecrRefCounter( void *vptr, const char *file, int lineno )
    512 {
    513     if ( vptr == NULL ) {
     511void *p_psMemDecrRefCounter(void *vptr, const char *file, int lineno)
     512{
     513    if (vptr == NULL) {
    514514        return NULL;
    515515    }
    516516
    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);
    521521        return NULL;
    522522    }
    523523
    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);
    530530
    531531    } else {
    532         pthread_mutex_unlock( &ptr->refCounterMutex );
     532        pthread_mutex_unlock(&ptr->refCounterMutex);
    533533
    534534        // 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);
    544544
    545545        // cut the memBlock out of the memBlock list
    546         if ( ptr->nextBlock != NULL ) {
     546        if (ptr->nextBlock != NULL) {
    547547            ptr->nextBlock->previousBlock = ptr->previousBlock;
    548548        }
    549         if ( ptr->previousBlock != NULL ) {
     549        if (ptr->previousBlock != NULL) {
    550550            ptr->previousBlock->nextBlock = ptr->nextBlock;
    551551        }
    552         if ( lastMemBlockAllocated == ptr ) {
     552        if (lastMemBlockAllocated == ptr) {
    553553            lastMemBlockAllocated = ptr->nextBlock;
    554554        }
    555555
    556         pthread_mutex_unlock( &memBlockListMutex );
    557 
     556        pthread_mutex_unlock(&memBlockListMutex);
    558557
    559558        // do we need to recycle?
    560         if ( ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE ) {
     559        if (ptr->userMemorySize < P_PS_LARGE_BLOCK_SIZE) {
    561560
    562561            int level = 1;
    563             while ( ptr->userMemorySize >= recycleBinSize[ level ] ) {
     562
     563            while (ptr->userMemorySize >= recycleBinSize[level]) {
    564564                level++;
    565565            }
     
    569569            ptr->previousBlock = NULL;
    570570
    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);
    578578
    579579        } else {
    580580            // memory is larger than I want to recycle.
    581581            #ifdef PS_MEM_DEBUG
    582             ( void ) p_psRealloc( vptr, 0, file, lineno );
     582            (void)p_psRealloc(vptr, 0, file, lineno);
    583583            ptr->previousBlock = NULL;
    584584            ptr->nextBlock = deadBlockList;
    585             if ( deadBlockList != NULL ) {
     585            if (deadBlockList != NULL) {
    586586                deadBlockList->previous = ptr;
    587587            }
     
    589589            #else
    590590
    591             pthread_mutex_destroy( &ptr->refCounterMutex );
    592             free( ptr );
     591            pthread_mutex_destroy(&ptr->refCounterMutex);
     592            free(ptr);
    593593            #endif
    594594
    595595        }
    596596
    597         vptr = NULL;    // since we freed it, make sure we return NULL.
     597        vptr = NULL;                       // since we freed it, make sure we return NULL.
    598598    }
    599599
     
    601601}
    602602
    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__ );
     603void 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__);
    613613    }
    614614
     
    616616
    617617}
    618 psFreeFcn p_psMemGetDeallocator( void* vptr )
    619 {
    620     if ( vptr == NULL ) {
     618psFreeFcn p_psMemGetDeallocator(void *vptr)
     619{
     620    if (vptr == NULL) {
    621621        return NULL;
    622622    }
    623623
    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__);
    628628    }
    629629
  • trunk/psLib/src/sysUtils/psMemory.h

    r1406 r1407  
    11#if !defined(PS_MEMORY_H)
    2 #define PS_MEMORY_H
     2#    define PS_MEMORY_H
     3
    34/** @file  psMemory.h
    45 *
     
    1415 *  @ingroup MemoryManagement
    1516 *
    16  *  @version $Revision: 1.23 $ $Name: not supported by cvs2svn $
    17  *  @date $Date: 2004-08-06 22:34:05 $
     17 *  @version $Revision: 1.24 $ $Name: not supported by cvs2svn $
     18 *  @date $Date: 2004-08-07 00:06:06 $
    1819 *
    1920 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    2021 */
    2122
    22 #include <stdio.h>                      // needed for FILE
    23 #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.
    2526
    2627/** @addtogroup MemoryManagement
     
    5354
    5455/// typedef for deallocator.
    55 typedef void (*psFreeFcn)(void* ptr);
     56typedef void (*psFreeFcn) (void *ptr);
    5657
    5758/** Book-keeping data for storage allocator.
     
    6263typedef struct psMemBlock
    6364{
    64     const void* startblock;            ///< initialised to p_psMEMMAGIC
    65     struct psMemBlock* previousBlock;  ///< previous block in allocation list
    66     struct psMemBlock* nextBlock;      ///< next block allocation list
    67     psFreeFcn freeFcn;                 ///< deallocator.  If NULL, use generic deallocation.
    68     size_t  userMemorySize;            ///< the size of the user-portion of the memory block
    69     const psMemoryId id;               ///< a unique ID for this allocation
    70     const char* file;                  ///< set from __FILE__ in e.g. p_psAlloc
    71     const int lineno;                  ///< set from __LINE__ in e.g. p_psAlloc
    72     pthread_mutex_t   refCounterMutex; ///< mutex to ensure exclusive access to reference counter
    73     psReferenceCount refCounter;       ///< how many times pointer is referenced
    74     const void* endblock;              ///< initialised to p_psMEMMAGIC
     65    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
    7576}
    7677psMemBlock;
     
    8182 *  @ingroup memCallback
    8283 */
    83 typedef psMemoryId (*psMemAllocateCallback)(
    84     const psMemBlock *ptr           ///< the psMemBlock just allocated
    85 );
     84typedef psMemoryId(*psMemAllocateCallback) (const psMemBlock * ptr      // /< the psMemBlock just allocated
     85                                           );
    8686
    8787/** prototype of memory free callback used by memory functions
     
    9090 *  @ingroup memCallback
    9191 */
    92 typedef psMemoryId (*psMemFreeCallback)(
    93     const psMemBlock *ptr           ///< the psMemBlock being freed
    94 );
     92typedef psMemoryId(*psMemFreeCallback) (const psMemBlock * ptr  // /< the psMemBlock being freed
     93                                       );
    9594
    9695/** prototype of a callback used in error conditions
     
    101100 *  @ingroup memCallback
    102101 */
    103 typedef void (*psMemProblemCallback)(
    104     const psMemBlock *ptr,          ///< the pointer to the problematic memory block.
    105     const char *file,               ///< the file in which the problem originated
    106     int lineno                      ///< the line number in which the problem originated
    107 );
     102typedef 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                                     );
    108107
    109108/** prototype of a callback function used when memory runs out
     
    115114 *  @ingroup memCallback
    116115 */
    117 typedef void *(*psMemExhaustedCallback)(
    118     size_t size                     //< the size of buffer required
    119 );
     116typedef void *(*psMemExhaustedCallback) (size_t size    // < the size of buffer required
     117                                        );
    120118
    121119/** Memory allocation.  This operates much like malloc(), but is guaranteed to return a non-NULL value.
     
    124122 *  @see psFree
    125123 */
    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
     125void *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
     133void p_psMemSetDeallocator(void *ptr, psFreeFcn freeFcn);
     134psFreeFcn p_psMemGetDeallocator(void *ptr);
    139135
    140136/// 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
    144139
    145140/** Memory re-allocation.  This operates much like realloc(), but is guaranteed to return a non-NULL value.
     
    148143 *  @see psAlloc, psFree
    149144 */
    150 #ifdef DOXYGEN
    151 void* psRealloc(void *ptr               ///< Pointer to re-allocate
    152                 size_t size,            ///< Size required
     145#    ifdef DOXYGEN
     146void *psRealloc(void *ptr       // /< Pointer to re-allocate
     147                size_t size,    // /< Size required
    153148               );
    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
     166void 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
    159172                 );
    160173
    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 #endif
    165 
    166 
    167 /** Free memory.  This operates much like free().
    168  *
    169  *  @see psAlloc, psRealloc
    170  */
    171 #ifdef DOXYGEN
    172 void psFree(void *ptr,                  ///< Pointer to free, if NULL, function returns immediately.
    173            );
    174 #else
    175 void p_psFree(void *ptr,                ///< Pointer to free
    176               const char *file,         ///< File of call
    177               int lineno                ///< Line number of call
    178              );
    179 
    180174/// Free memory.  psFree sends file and line number to p_psFree.
    181 #define psFree(size) p_psFree(size, __FILE__, __LINE__)
    182 
    183 #endif
     175#        define psFree(size) p_psFree(size, __FILE__, __LINE__)
     176
     177#    endif
    184178
    185179/** Check for memory leaks.  This scans for allocated memory buffers not freed with an ID not less than id0.
     
    197191 *  @ingroup memTracing
    198192 */
    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 );
     193int 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                   );
    204197
    205198/** Check for memory corruption.  Scans all currently allocated memory buffers and checks for corruptions,
     
    208201 *  @ingroup memTracing
    209202 */
    210 int psMemCheckCorruption(
    211     bool abort_on_error              ///< Abort on detecting corruption?
    212 );
     203int psMemCheckCorruption(bool abort_on_error    // /< Abort on detecting corruption?
     204                        );
    213205
    214206/** Return reference counter
     
    216208 *  @ingroup memRefCount
    217209 */
    218 psReferenceCount psMemGetRefCounter(
    219     void *vptr                      ///< Pointer to get refCounter for
    220 );
     210psReferenceCount psMemGetRefCounter(void *vptr  // /< Pointer to get refCounter for
     211                                   );
    221212
    222213/** Increment reference counter and return the pointer
     
    224215 *  @ingroup memRefCount
    225216 */
    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
     218void *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
    238228
    239229/** Decrement reference counter and return the pointer
     
    241231 *  @ingroup memRefCount
    242232 */
    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
     234void *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
    255244
    256245/** Set callback for problems
    257246 *  @ingroup memCallback
    258247 */
    259 psMemProblemCallback psMemProblemCallbackSet(
    260     psMemProblemCallback func       ///< Function to run
    261 );
     248psMemProblemCallback psMemProblemCallbackSet(psMemProblemCallback func  // /< Function to run
     249                                            );
    262250
    263251/** Set callback for out-of-memory
     
    265253 *  @ingroup memCallback
    266254 */
    267 psMemExhaustedCallback psMemExhaustedCallbackSet(
    268     psMemExhaustedCallback func     ///< Function to run
    269 );
     255psMemExhaustedCallback psMemExhaustedCallbackSet(psMemExhaustedCallback func    // /< Function to run
     256                                                );
    270257
    271258/** Set call back for when a particular memory block is allocated
     
    273260 *  @ingroup memCallback
    274261 */
    275 psMemAllocateCallback psMemAllocateCallbackSet(
    276     psMemAllocateCallback func          ///< Function to run
    277 );
     262psMemAllocateCallback psMemAllocateCallbackSet(psMemAllocateCallback func       // /< Function to run
     263                                              );
    278264
    279265/** Set call back for when a particular memory block is freed
     
    281267 *  @ingroup memCallback
    282268 */
    283 psMemFreeCallback psMemFreeCallbackSet(
    284     psMemFreeCallback func              ///< Function to run
    285 );
     269psMemFreeCallback psMemFreeCallbackSet(psMemFreeCallback func   // /< Function to run
     270                                      );
    286271
    287272/** get next memory ID
     
    295280 *  @ingroup memCallback
    296281 */
    297 psMemoryId psMemAllocateCallbackSetID(
    298     psMemoryId id                       ///< ID to set
    299 );
     282psMemoryId psMemAllocateCallbackSetID(psMemoryId id     // /< ID to set
     283                                     );
    300284
    301285/** set p_psMemFreeID to id
     
    303287 *  @ingroup memCallback
    304288 */
    305 psMemoryId psMemFreeCallbackSetID(
    306     psMemoryId id                       ///< ID to set
    307 );
     289psMemoryId psMemFreeCallbackSetID(psMemoryId id // /< ID to set
     290                                 );
    308291
    309292//@} End of Memory Management Functions
    310293
    311 #ifndef DOXYGEN
     294#    ifndef DOXYGEN
    312295
    313296/*
    314297 * Ensure that any program using malloc/realloc/free will fail to compile
    315298 */
    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
    12/** @file  psString.c
    23 *
     
    89 *  @author Eric Van Alst, MHPCC
    910 *   
    10  *  @version $Revision: 1.7 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    1922#include <stdlib.h>
     
    2427
    2528/******************************************************************************/
     29
    2630/*  DEFINE STATEMENTS                                                         */
     31
    2732/******************************************************************************/
    2833
     
    3035
    3136/******************************************************************************/
     37
    3238/*  TYPE DEFINITIONS                                                          */
     39
    3340/******************************************************************************/
    3441
     
    3643
    3744/*****************************************************************************/
     45
    3846/*  GLOBAL VARIABLES                                                         */
     47
    3948/*****************************************************************************/
    4049
     
    4251
    4352/*****************************************************************************/
     53
    4454/*  FILE STATIC VARIABLES                                                    */
     55
    4556/*****************************************************************************/
    4657
     
    4859
    4960/*****************************************************************************/
     61
    5062/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
     63
    5164/*****************************************************************************/
    5265
     
    5467
    5568/*****************************************************************************/
     69
    5670/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     71
    5772/*****************************************************************************/
    5873
    59 char *psStringCopy(
    60     const char*  str
    61 )
     74char *psStringCopy(const char *str)
    6275{
    6376    // Allocate memory using psAlloc function
     
    6780}
    6881
    69 char *psStringNCopy(
    70     const char*  str,
    71     int          nChar
    72 )
     82char *psStringNCopy(const char *str, int nChar)
    7383{
    7484    char *returnValue = NULL;
    7585
    7686    // Check the number of characters to copy is non-negative
    77     if ( nChar < 0 ) {
     87    if (nChar < 0) {
    7888        // 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);
    8190        return NULL;
    8291    }
     
    8493    // Copy input string to memory allocated up to nChar characters
    8594    // 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);
    8796
    8897    // 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';
    91100    }
    92 
    93101    // Return the string pointer
    94102    return returnValue;
    95103}
    96 
    97 
  • trunk/psLib/src/sysUtils/psString.h

    r974 r1407  
     1
    12/** @file  psString.h
    23 *
     
    1011 *  @author Eric Van Alst, MHPCC
    1112 *
    12  *  @version $Revision: 1.5 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-06-10 01:58:06 $
     13 *  @version $Revision: 1.6 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_STRING_H
    19 #define PS_STRING_H
     20#    define PS_STRING_H
    2021
    2122/******************************************************************************/
     23
    2224/*  DEFINE STATEMENTS                                                         */
     25
    2326/******************************************************************************/
    2427
    2528/** This macro will convert the arguement to a quoted string */
    26 #define PS_STRING(S)  #S
     29#    define PS_STRING(S)  #S
    2730
    2831/******************************************************************************/
     32
    2933/*  TYPE DEFINITIONS                                                          */
     34
    3035/******************************************************************************/
    3136
     
    3338
    3439/*****************************************************************************/
     40
    3541/* FUNCTION PROTOTYPES                                                       */
     42
    3643/*****************************************************************************/
    3744
    3845// Doxygen group tags
     46
    3947/** @addtogroup SysUtils
    4048 *  @{
     
    4957 *
    5058 */
    51 char *psStringCopy(
    52     const char *str      /**< Input string of characters to copy */
    53 );
    5459
     60char *psStringCopy(const char *str
     61                   /**< Input string of characters to copy */
     62                  );
    5563
    5664/** Copies the input string up to the specified number of characters
     
    6775 *
    6876 */
     77
    6978/*@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 );
    7479
    75 /* @} */  // Doxygen - End of SystemGroup Functions
     80char *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
    7688
    7789#endif
    78 
  • trunk/psLib/src/sysUtils/psTrace.c

    r1406 r1407  
     1
    12/** @file psTrace.c
    23 *  \brief basic run-time trace facilities
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-06 22:34:05 $
     12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
     17
    1618/*****************************************************************************
    1719    NOTES:
     
    3436#ifndef PS_NO_TRACE
    3537
    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 component
    46 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
     47static p_psComponent *p_psCroot = NULL; // The root of the trace component
     48static FILE *p_psTraceFP = NULL;        // File destination for messages.
     49
     50static void componentFree(p_psComponent * comp);
     51static p_psComponent *componentAlloc(const char *name, int level);
    5052
    5153/*****************************************************************************
    5254componentAlloc(): allocate memory for a new node, and initialize members.
    5355 *****************************************************************************/
    54 static p_psComponent *componentAlloc(const char *name,
    55                                      int level)
     56static p_psComponent *componentAlloc(const char *name, int level)
    5657{
    5758    p_psComponent *comp = psAlloc(sizeof(p_psComponent));
    58     p_psMemSetDeallocator(comp,(psFreeFcn)componentFree);
     59
     60    p_psMemSetDeallocator(comp, (psFreeFcn) componentFree);
    5961    comp->name = psStringCopy(name);
    6062    comp->level = level;
     
    6466}
    6567
    66 
    6768/*****************************************************************************
    6869componentFree(): free the current node in the root tree, and all children
    6970nodes as well.
    7071 *****************************************************************************/
    71 static void componentFree(p_psComponent *comp)
     72static void componentFree(p_psComponent * comp)
    7273{
    7374    if (comp == NULL) {
     
    8586}
    8687
    87 
    8888/*****************************************************************************
    8989initTrace(): simply initialize the component root tree.
     
    9696}
    9797
    98 
    9998/*****************************************************************************
    10099Set all trace levels to zero.
    101100 *****************************************************************************/
    102 void p_psTraceReset(p_psComponent *currentNode)
     101void p_psTraceReset(p_psComponent * currentNode)
    103102{
    104103    int i = 0;
     
    109108
    110109    currentNode->level = 0;
    111     for (i=0;i<currentNode->n;i++) {
     110    for (i = 0; i < currentNode->n; i++) {
    112111        if (NULL == currentNode->subcomp[i]) {
    113112            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);
    116114        } else {
    117115            p_psTraceReset(currentNode->subcomp[i]);
     
    129127}
    130128
    131 
    132129/*****************************************************************************
    133130Free all nodes in the component tree.
     
    137134    psFree(p_psCroot);
    138135}
    139 
    140136
    141137/*****************************************************************************
     
    145141to ANSI-C.
    146142 *****************************************************************************/
    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
     143static 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
    154149    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.
    158153    if (strcmp(".", addNodeName) == 0) {
    159154        p_psCroot->level = level;
     
    162157
    163158    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);
    166160        exit(1);
    167161    }
     
    188182        if (nodeExists == 0) {
    189183            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}
    199191
    200192/*****************************************************************************
     
    210202*****************************************************************************/
    211203int psTraceSetLevel(const char *comp,   // component of interest
    212                     int level)          // desired trace level
     204                    int level)  // desired trace level
    213205{
    214206    // If the root component tree does not exist, then initialize it.
     
    216208        initTrace();
    217209    }
    218 
    219210    // Add the new component to the component tree.
    220211    componentAdd(comp, level);
     
    223214    return 0;
    224215}
    225 
    226216
    227217/*****************************************************************************
     
    241231static int doGetTraceLevel(const char *aname)
    242232{
    243     char       name[strlen(aname) + 1]; // need a writeable copy: for strsep()
    244     char      *pname=name;
    245     char      *firstComponent = NULL;   // first component of name
     233    char name[strlen(aname) + 1];      // need a writeable copy: for strsep()
     234    char *pname = name;
     235    char *firstComponent = NULL;        // first component of name
    246236    p_psComponent *currentNode = p_psCroot;
    247     int        i = 0;
     237    int i = 0;
    248238
    249239    if (NULL == currentNode) {
    250         return(PS_UNKNOWN_TRACE_LEVEL);
     240        return (PS_UNKNOWN_TRACE_LEVEL);
    251241    }
    252242
    253243    if (strcmp(".", aname) == 0) {
    254         return(p_psCroot->level);
     244        return (p_psCroot->level);
    255245    }
    256246
    257247    if (aname[0] != '.') {
    258         return(PS_UNKNOWN_TRACE_LEVEL);
     248        return (PS_UNKNOWN_TRACE_LEVEL);
    259249    }
    260250
     
    266256            if (NULL == currentNode->subcomp[i]) {
    267257                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);
    270259            }
    271260
     
    273262                currentNode = currentNode->subcomp[i];
    274263                if (pname == NULL) {
    275                     return(currentNode->level);
     264                    return (currentNode->level);
    276265                }
    277266            }
    278267        }
    279268    }
    280     return(PS_UNKNOWN_TRACE_LEVEL);
    281 }
    282 
     269    return (PS_UNKNOWN_TRACE_LEVEL);
     270}
    283271
    284272/*****************************************************************************
     
    297285{
    298286    if (p_psCroot == NULL) {
    299         return(PS_UNKNOWN_TRACE_LEVEL);
    300     }
    301 
     287        return (PS_UNKNOWN_TRACE_LEVEL);
     288    }
    302289    // Search the component root tree, determine the trace level.
    303     return(doGetTraceLevel(name));
    304 }
    305 
     290    return (doGetTraceLevel(name));
     291}
    306292
    307293/*****************************************************************************
     
    317303 null
    318304 *****************************************************************************/
    319 static void doPrintTraceLevels(const p_psComponent *comp,
    320                                int depth)
     305static void doPrintTraceLevels(const p_psComponent * comp, int depth)
    321306{
    322307    int i = 0;
     
    327312    } else {
    328313        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, ".");
    331315        } 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);
    334317        }
    335318    }
    336319
    337320    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}
    342324
    343325/*****************************************************************************
     
    359341    doPrintTraceLevels(p_psCroot, 0);
    360342}
    361 
    362343
    363344/*****************************************************************************
     
    376357 *****************************************************************************/
    377358void p_psTrace(const char *comp,        // component being traced
    378                int level,               // desired trace level
    379                ...)                     // arguments
     359               int level,       // desired trace level
     360               ...)             // arguments
    380361{
    381362    char *fmt = NULL;
     
    384365
    385366    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    }
    390369    // Only display this message if it's trace level is less than the level
    391370    // of it's associatedcomponent.
     
    413392        va_end(ap);
    414393    }
    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
     397void psTraceSetDestination(FILE * fp)
    420398{
    421399    p_psTraceFP = fp;
  • trunk/psLib/src/sysUtils/psTrace.h

    r1393 r1407  
     1
    12/** @file psTrace.h
    23 *  \brief basic run-time trace facilities
     
    910 *  @author George Gusciora, MHPCC
    1011 *
    11  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    12  *  @date $Date: 2004-08-05 19:38:52 $
     12 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1314 *
    1415 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1516 */
    1617#if !defined(PS_TRACE_H)
    17 #define PS_TRACE_H 1
     18#    define PS_TRACE_H 1
    1819
    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
    2222
    2323/** \addtogroup LogTrace
     
    2929//#define PS_NO_TRACE 1   ///< to turn off all tracing
    3030
    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
    4145
    42 /** Basic structure for the component tree.  A component is a string of the
    43     form aaa.bbb.ccc, and may itself contain further subcomponents.  The
    44     Component structure doesn't in fact contain it's full name, but only the
    45     last part. */
    46 typedef struct p_psComponent
    47 {
    48     const char *name;                     // last part of name of component
    49     int level;                            // trace level for this component
    50     int n;                                // number of subcomponents
    51     struct p_psComponent **subcomp;           // next level of subcomponents
    52 }
     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        }
    5357p_psComponent;
    5458
    55 #ifndef DOXYGEN
     59#        ifndef DOXYGEN
    5660/// Send a trace message
    57 void p_psTrace(const char *facil,  ///< facilty of interest
    58                int myLevel,  ///< desired trace level
    59                ...)   ///< trace message arguments
     61void p_psTrace(const char *facil,       // /< facilty of interest
     62               int myLevel,     // /< desired trace level
     63               ...)             // /< trace message arguments
    6064;
    61 #endif
     65#        endif
    6266
    6367/// Set trace level
    64 int psTraceSetLevel(const char *facil, ///< facilty of interest
    65                     int level)  ///< desired trace level
     68int psTraceSetLevel(const char *facil,     // /< facilty of interest
     69                    int level)     // /< desired trace level
    6670;
    6771
    6872/// Get the trace level
    69 int psTraceGetLevel(const char *facil) ///< facilty of interest
     73int psTraceGetLevel(const char *facil)     // /< facilty of interest
    7074;
    7175
    7276/// Set all trace levels to zero (do not free nodes in the component tree).
    73 void psTraceReset()
    74 ;
     77void psTraceReset();
    7578
    7679/// Free all nodes in the component tree.
    77 void psTraceFree()
    78 ;
     80void psTraceFree();
    7981
    8082/// print trace levels
    81 void psTracePrintLevels(void)
    82 ;
     83void psTracePrintLevels(void);
    8384
    8485/// Set the destination of future trace messages.
    85 void psTraceSetDestination(FILE *fp);
     86void psTraceSetDestination(FILE * fp);
    8687
     88/* \} */// End of SystemGroup Functions
    8789
    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
    9292
    9393#endif
    94 
  • trunk/psLib/src/sysUtils/psType.h

    r1385 r1407  
     1
    12/** @file  psType.h
    23*
     
    1011*  @author Ross Harman, MHPCC
    1112*
    12 *  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-04 23:37:39 $
     13*  @version $Revision: 1.17 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819#ifndef PS_TYPE_H
    19 #define PS_TYPE_H
     20#    define PS_TYPE_H
    2021
    21 #include <complex.h>
    22 #include <stdint.h>
    23 #include <float.h>
     22#    include <complex.h>
     23#    include <stdint.h>
     24#    include <float.h>
    2425
    2526/// @addtogroup DataContainer
     
    2728
    2829/******************************************************************************/
     30
    2931/*  TYPE DEFINITIONS                                                          */
     32
    3033/******************************************************************************/
    3134
     
    3740 */
    3841
    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 
     42typedef uint8_t psU8;           // /< 8-bit unsigned int
     43typedef uint16_t psU16;         // /< 16-bit unsigned int
     44typedef uint32_t psU32;         // /< 32-bit unsigned int
     45typedef uint64_t psU64;         // /< 64-bit unsigned int
     46typedef int8_t psS8;            // /< 8-bit signed int
     47typedef int16_t psS16;          // /< 16-bit signed int
     48typedef int32_t psS32;          // /< 32-bit signed int
     49typedef int64_t psS64;          // /< 64-bit signed int
     50typedef float psF32;            // /< 32-bit floating point
     51typedef double psF64;           // /< 64-bit floating point
     52typedef complex float psC32;    // /< complex with 32-bit floating point Real and Imagary numbers
     53typedef complex double psC64;   // /< complex with 64-bit floating point Real and Imagary numbers
     54typedef void *psPTR;            // /< void pointer
    5355
    5456typedef 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.
    6872} psElemType;
    6973
    70 #define PS_TYPE_MASK PS_TYPE_U8         ///< the psElemType to use for mask image
    71 #define PS_TYPE_MASK_DATA U8            ///< the data member to use for mask image
    72 #define PS_TYPE_MASK_NAME "psU8"
    73 typedef psU8 psMaskType;                ///< the C datatype for a mask image
     74#    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"
     77typedef psU8 psMaskType;        // /< the C datatype for a mask image
    7478
    75 #define PS_MIN_S8        INT8_MIN
    76 #define PS_MIN_S16       INT16_MIN
    77 #define PS_MIN_S32       INT32_MIN
    78 #define PS_MIN_S64       INT64_MIN
    79 #define PS_MIN_U8        0
    80 #define PS_MIN_U16       0
    81 #define PS_MIN_U32       0
    82 #define PS_MIN_U64       0
    83 #define PS_MIN_F32       -FLT_MAX
    84 #define PS_MIN_F64       -DBL_MAX
    85 #define PS_MIN_C32       -FLT_MAX
    86 #define PS_MIN_C64       -DBL_MAX
     79#    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
    8791
    88 #define PS_MAX_S8        INT8_MAX
    89 #define PS_MAX_S16       INT16_MAX
    90 #define PS_MAX_S32       INT32_MAX
    91 #define PS_MAX_S64       INT64_MAX
    92 #define PS_MAX_U8        UINT8_MAX
    93 #define PS_MAX_U16       UINT16_MAX
    94 #define PS_MAX_U32       UINT32_MAX
    95 #define PS_MAX_U64       UINT64_MAX
    96 #define PS_MAX_F32       FLT_MAX
    97 #define PS_MAX_F64       DBL_MAX
    98 #define PS_MAX_C32       FLT_MAX
    99 #define PS_MAX_C64       DBL_MAX
     92#    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
    100104
    101105/// Macro to get the bad pixel reason code (stored as part of mask value)
    102 #define PS_BADPIXEL_BITMASK 0x0f
    103 #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)
    104108
    105 #define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)
     109#    define PS_IS_BADPIXEL(maskValue) (PS_GET_BADPIXEL(maskValue) != 0)
    106110
    107111/// 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) \
    109113{ \
    110114    maskValue = (psMaskType)((reasonCode & PS_BADPIXEL_BITMASK) | (maskValue & ~PS_BADPIXEL_BITMASK)); \
     
    112116
    113117/// 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)
    115119/// 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)
    117121/// 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)
    119123/// 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)
    121125/// 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) )
    123127
    124128/** Dimensions of a data type.
     
    128132 */
    129133typedef 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.
    135139} psDimen;
    136140
     
    143147typedef struct
    144148{
    145     psElemType type;    ///< Primitive type.
    146     psDimen dimen;      ///< Dimensionality.
     149    psElemType type;            // /< Primitive type.
     150    psDimen dimen;              // /< Dimensionality.
    147151}
    148152psType;
  • trunk/psLib/src/types/psArray.c

    r1406 r1407  
     1
    12/** @file  psArray.c
    23 *
     
    89 *  @author Ross Harman, MHPCC
    910 *
    10  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    11  *  @date $Date: 2004-08-06 22:34:05 $
     11 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     12 *  @date $Date: 2004-08-07 00:06:06 $
    1213 *
    1314 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516
    1617/******************************************************************************/
     18
    1719/*  INCLUDE FILES                                                             */
     20
    1821/******************************************************************************/
    19 #include<stdlib.h>            // for qsort, etc.
     22#include<stdlib.h>                         // for qsort, etc.
    2023
    2124#include "psMemory.h"
     
    2427#include "psLogMsg.h"
    2528
     29/*****************************************************************************/
     30
     31/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    2632
    2733/*****************************************************************************/
    28 /*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    29 /*****************************************************************************/
    30 static void arrayFree(psArray *restrict psArr);
     34static void arrayFree(psArray * restrict psArr);
    3135
    3236/*****************************************************************************/
     37
    3338/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
     39
    3440/*****************************************************************************/
    35 psArray* psArrayAlloc(unsigned int nalloc)
     41psArray *psArrayAlloc(unsigned int nalloc)
    3642{
    3743    psArray *psArr = NULL;
    3844
    3945    // Invalid nalloc
    40     if(nalloc < 1) {
     46    if (nalloc < 1) {
    4147        psError(__func__, "Invalid value for nalloc. nalloc: %d\n", nalloc);
    4248        return NULL;
    4349    }
    44 
    4550    // 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);
    4853
    4954    psArr->nalloc = nalloc;
     
    5156
    5257    // Create vector data array
    53     psArr->data = psAlloc(nalloc*sizeof(psPTR));
     58    psArr->data = psAlloc(nalloc * sizeof(psPTR));
    5459
    5560    return psArr;
    5661}
    5762
    58 psArray *psArrayRealloc(unsigned int nalloc, psArray *restrict in)
     63psArray *psArrayRealloc(unsigned int nalloc, psArray * restrict in)
    5964{
    6065    // Invalid nalloc
    61     if(nalloc < 1) {
     66    if (nalloc < 1) {
    6267        psError(__func__, "Invalid value for realloc (%d)\n", nalloc);
    6368        return NULL;
    6469    }
    6570
    66     if(in == NULL) {
     71    if (in == NULL) {
    6772        psError(__func__, "Null input vector\n");
    6873        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]);
    7678            }
    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;
    8180        }
     81        // Realloc after decrementation to avoid accessing freed array elements
     82        in->data = psRealloc(in->data, nalloc * sizeof(psPTR));
     83        in->nalloc = nalloc;
     84    }
    8285
    8386    return in;
    8487}
    8588
    86 static void arrayFree(psArray *restrict psArr)
     89static void arrayFree(psArray * restrict psArr)
    8790{
    8891    if (psArr == NULL) {
     
    9598}
    9699
    97 void psArrayElementFree(psArray *restrict psArr)
     100void psArrayElementFree(psArray * restrict psArr)
    98101{
    99102
    100     if(psArr == NULL) {
     103    if (psArr == NULL) {
    101104        return;
    102105    }
    103106
    104     for(int i = 0; i < psArr->n; i++) {
     107    for (int i = 0; i < psArr->n; i++) {
    105108        psFree(psArr->data[i]);
    106109        psArr->data[i] = NULL;
     
    108111}
    109112
    110 psArray* psArraySort(psArray* in, psComparePtrFcn compare)
     113psArray *psArraySort(psArray * in, psComparePtrFcn compare)
    111114{
    112115    if (in == NULL) {
     
    114117    }
    115118
    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);
    119120
    120121    return in;
  • trunk/psLib/src/types/psArray.h

    r1228 r1407  
     1
    12/** @file  psArray.h
    23 *
     
    1112 *  @author Ross Harman, MHPCC
    1213 *
    13  *  @version $Revision: 1.11 $ $Name: not supported by cvs2svn $
    14  *  @date $Date: 2004-07-15 22:18:02 $
     14 *  @version $Revision: 1.12 $ $Name: not supported by cvs2svn $
     15 *  @date $Date: 2004-08-07 00:06:06 $
    1516 *
    1617 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920#ifndef PS_ARRAY_H
    20 #define PS_ARRAY_H
     21#    define PS_ARRAY_H
    2122
    22 #include "psType.h"
    23 #include "psCompare.h"
     23#    include "psType.h"
     24#    include "psCompare.h"
    2425
    2526/// @addtogroup Array
     
    3334typedef struct
    3435{
    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 elements
     36    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
    3839}
    3940psArray;
    4041
    4142/*****************************************************************************/
     43
    4244/* FUNCTION PROTOTYPES                                                       */
     45
    4346/*****************************************************************************/
    4447
     
    5154 *
    5255 */
    53 psArray *psArrayAlloc(
    54     unsigned int nalloc                 ///< Total number of elements to make available.
    55 );
     56psArray *psArrayAlloc(unsigned int nalloc       // /< Total number of elements to make available.
     57                     );
    5658
    5759/** Reallocate an array.
     
    6365 *
    6466 */
    65 psArray *psArrayRealloc(
    66     unsigned int nalloc,                ///< Total number of elements to make available.
    67     psArray *restrict psArr            ///< array to reallocate.
    68 );
     67psArray *psArrayRealloc(unsigned int nalloc,    // /< Total number of elements to make available.
     68                        psArray * restrict psArr        // /< array to reallocate.
     69                       );
    6970
    7071/** Deallocate/Dereference elements of an array.
     
    7576 *
    7677 */
    77 void psArrayElementFree(
    78     psArray *restrict psArr    ///< Void pointer array to destroy.
    79 );
     78void psArrayElementFree(psArray * restrict psArr        // /< Void pointer array to destroy.
     79                       );
    8080
    8181/** Sort the array according to an external compare function.
     
    8686 *  @return psArray*       The sorted array.
    8787 */
    88 psArray* psArraySort(psArray* in, psComparePtrFcn compare);
     88psArray *psArraySort(psArray * in, psComparePtrFcn compare);
    8989
    9090/// @}
  • trunk/psLib/src/types/psBitSet.c

    r1406 r1407  
     1
    12/** @file  psBitSet.c
    23 *
     
    1011 *  @author Ross Harman, MHPCC
    1112 *
    12  *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-08-06 22:34:05 $
     13 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     14 *  @date $Date: 2004-08-07 00:06:06 $
    1415 *
    1516 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1718
    1819/******************************************************************************/
     20
    1921/*  INCLUDE FILES                                                             */
     22
    2023/******************************************************************************/
    2124#include <string.h>
     
    3134
    3235/******************************************************************************/
     36
    3337/*  DEFINE STATEMENTS                                                         */
    34 /******************************************************************************/
    35 
    36 // None
    37 
    38 /******************************************************************************/
     38
     39/******************************************************************************/
     40
     41// None
     42
     43/******************************************************************************/
     44
    3945/*  TYPE DEFINITIONS                                                          */
    40 /******************************************************************************/
    41 
    42 // None
    43 
    44 /*****************************************************************************/
     46
     47/******************************************************************************/
     48
     49// None
     50
     51/*****************************************************************************/
     52
    4553/*  GLOBAL VARIABLES                                                         */
    46 /*****************************************************************************/
    47 
    48 // None
    49 
    50 /*****************************************************************************/
     54
     55/*****************************************************************************/
     56
     57// None
     58
     59/*****************************************************************************/
     60
    5161/*  FILE STATIC VARIABLES                                                    */
    52 /*****************************************************************************/
    53 
    54 // None
    55 
    56 /*****************************************************************************/
     62
     63/*****************************************************************************/
     64
     65// None
     66
     67/*****************************************************************************/
     68
    5769/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    58 /*****************************************************************************/
    59 static void psBitSetFree(psBitSet *restrict inBitSet);
    60 
     70
     71/*****************************************************************************/
     72static void psBitSetFree(psBitSet * restrict inBitSet);
    6173
    6274/** Private function to create a mask.
     
    7082{
    7183    char mask = (char)0x01;
     84
    7285    // Ignore splint warning about negative bit shifts
    73     /*@i@*/
    74     mask = mask << (bit%8);
     86    /* @i@ */
     87    mask = mask << (bit % 8);
    7588
    7689    return mask;
     
    7891
    7992/*****************************************************************************/
     93
    8094/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    81 /*****************************************************************************/
    82 psBitSet* psBitSetAlloc(int n)
     95
     96/*****************************************************************************/
     97psBitSet *psBitSetAlloc(int n)
    8398{
    8499    int numBytes = 0;
    85100    psBitSet *newObj = NULL;
    86101
    87     if(n <= 0) {
     102    if (n <= 0) {
    88103        psError(__func__, " : Line %d - Allocation size must be > 0: size = %d", __LINE__, n);
    89104        return 0;
    90105    }
    91106
    92     numBytes = ceil(n/8.0);
     107    numBytes = ceil(n / 8.0);
    93108    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);
    98113    newObj->n = numBytes;
    99114
    100115    // 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__);
    105120    }
    106121
     
    110125}
    111126
    112 static void psBitSetFree(psBitSet *restrict inBitSet)
    113 {
    114     if(inBitSet == NULL) {
     127static void psBitSetFree(psBitSet * restrict inBitSet)
     128{
     129    if (inBitSet == NULL) {
    115130        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    116131        return;
     
    119134}
    120135
    121 psBitSet* psBitSetSet(psBitSet *inBitSet, int bit)
    122 {
    123     char* byte = NULL;
    124 
    125     if(inBitSet == NULL) {
     136psBitSet *psBitSetSet(psBitSet * inBitSet, int bit)
     137{
     138    char *byte = NULL;
     139
     140    if (inBitSet == NULL) {
    126141        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    127142        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    }
    138150    // 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;
    140152    *byte |= mask(bit);
    141153
     
    143155}
    144156
    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 
     157bool 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    }
    162171    // 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) {
    165174        return 0;
    166175    }
     
    169178}
    170179
    171 psBitSet* psBitSetOp(psBitSet *outBitSet, const psBitSet *restrict inBitSet1, char *operator,
    172                      const psBitSet *restrict inBitSet2)
     180psBitSet *psBitSetOp(psBitSet * outBitSet, const psBitSet * restrict inBitSet1, char *operator,
     181                     const psBitSet * restrict inBitSet2)
    173182{
    174183    int i = 0;
     
    179188    char *inBits2 = NULL;
    180189
    181     if(inBitSet1 == NULL) {
     190    if (inBitSet1 == NULL) {
    182191        psError(__func__, " : Line %d - Null psBitSet for inBitSet1 argument", __LINE__);
    183192        return outBitSet;
    184193    }
    185194
    186     if(operator == NULL) {
     195    if (operator == NULL) {
    187196        psError(__func__, " : Line %d - Null input operator\n", __LINE__);
    188197        return outBitSet;
    189198    }
    190199
    191     if(inBitSet2 == NULL) {
     200    if (inBitSet2 == NULL) {
    192201        psError(__func__, " : Line %d - Null psBitSet for inBitSet2 argument", __LINE__);
    193202        return outBitSet;
    194203    }
    195204
    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) {
    201210        psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__);
    202211        return outBitSet;
     
    209218
    210219    tempChar = toupper(operator[0]);
    211     switch(tempChar) {
     220    switch (tempChar) {
    212221    case 'A':
    213         for(i=0; i<n; i++) {
     222        for (i = 0; i < n; i++) {
    214223            outBits[i] = inBits1[i] & inBits2[i];
    215224        }
    216225        break;
    217226    case 'O':
    218         for(i=0; i<n; i++) {
     227        for (i = 0; i < n; i++) {
    219228            outBits[i] = inBits1[i] | inBits2[i];
    220229        }
    221230        break;
    222231    case 'X':
    223         for(i=0; i<n; i++) {
     232        for (i = 0; i < n; i++) {
    224233            outBits[i] = inBits1[i] ^ inBits2[i];
    225234        }
     
    232241}
    233242
    234 psBitSet* psBitSetNot(psBitSet *outBitSet, const psBitSet *restrict inBitSet)
     243psBitSet *psBitSetNot(psBitSet * outBitSet, const psBitSet * restrict inBitSet)
    235244{
    236245    int i = 0;
     
    239248    char *inBits = NULL;
    240249
    241     if(inBitSet == NULL) {
     250    if (inBitSet == NULL) {
    242251        psError(__func__, " : Line %d - Null psBitSet for inBitSet argument", __LINE__);
    243252        return outBitSet;
     
    245254
    246255    n = inBitSet->n;
    247     if(n == 0) {
     256    if (n == 0) {
    248257        psError(__func__, " : Line %d - No elements in inBitSet", __LINE__);
    249258        return outBitSet;
    250259    }
    251260
    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) {
    257266        psError(__func__, " : Line %d - psBitSet sizes not the same", __LINE__);
    258267        return outBitSet;
     
    262271    inBits = inBitSet->bits;
    263272
    264     for(i=0; i<n; i++) {
     273    for (i = 0; i < n; i++) {
    265274        outBits[i] = ~inBits[i];
    266275    }
     
    269278}
    270279
    271 char *psBitSetToString(const psBitSet *restrict inBitSet)
     280char *psBitSetToString(const psBitSet * restrict inBitSet)
    272281{
    273282    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';
    282292    }
    283293
  • trunk/psLib/src/types/psBitSet.h

    r1172 r1407  
     1
    12/** @file  psBitSet.h
    23 *
     
    1213 *  @author Ross Harman, MHPCC
    1314 *
    14  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    15  *  @date $Date: 2004-07-01 21:48:11 $
     15 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     16 *  @date $Date: 2004-08-07 00:06:06 $
    1617 *
    1718 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1920
    2021#ifndef PSBITSET_H
    21 #define PSBITSET_H
     22#    define PSBITSET_H
    2223
    2324/// @addtogroup BitSet
     
    2526
    2627/******************************************************************************/
     28
    2729/*  TYPE DEFINITIONS                                                          */
     30
    2831/******************************************************************************/
    2932
     
    3538typedef struct
    3639{
     40
    3741    int n;      /**< Number of bytes in the array */
     42
    3843    char *bits; /**< Aray of bytes holding bits */
    3944}
     
    4146
    4247/*****************************************************************************/
     48
    4349/* FUNCTION PROTOTYPES                                                       */
     50
    4451/*****************************************************************************/
    4552
     
    5158 *  @return  psBitSet*: Pointer to struct containing array of bits and size of array.
    5259 */
     60
    5361/*@null@*/
    54 psBitSet* psBitSetAlloc(
    55     int n   /**< Number of bits in psBitSet array */
    56 );
     62
     63psBitSet *psBitSetAlloc(int n
     64                        /**< Number of bits in psBitSet array */
     65                       );
    5766
    5867/** Set a bit.
     
    6473 *  @return  psBitSet*: Pointer to struct containing psBitSet.
    6574 */
    66 psBitSet* psBitSetSet(
    67     /*@returned@*/psBitSet *restrict inMask,  /**< Pointer to psBitSet to be set. */
    68     int bit                     /**< Bit to be set. */
     75psBitSet *psBitSetSet(
     76
     77    /* @returned@ */ psBitSet * restrict inMask,
     78    /**< Pointer to psBitSet to be set. */
     79
     80    int bit/**< Bit to be set. */
    6981);
    7082
     
    7890 *  @return  int: Value of bit, either one or zero.
    7991 */
    80 bool psBitSetTest(
    81     const psBitSet *restrict inMask,    /**< Pointer psBitSet to be tested. */
    82     int bit                             /**< Bit to be tested. */
    83 );
     92
     93bool psBitSetTest(const psBitSet * restrict inMask,
     94                  /**< Pointer psBitSet to be tested. */
     95
     96                  int bit               /**< Bit to be tested. */
     97                 );
    8498
    8599/** Perform a binary operation on two psBitSets
     
    90104 *  @return  psBitSet*: Pointer to struct containing result of binary operation.
    91105 */
    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 */
     106psBitSet *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 */
    97118);
    98119
     
    103124 *  @return  psBitSet*: Pointer to struct containing result of operation.
    104125 */
    105 psBitSet* psBitSetNot(
    106     psBitSet *outBitSet,                /**< Resulting psBitSet from operation */
    107     const psBitSet *restrict inBitSet   /**< Input psBitSet */
    108 );
     126
     127psBitSet *psBitSetNot(psBitSet * outBitSet,
     128                      /**< Resulting psBitSet from operation */
     129
     130                      const psBitSet * restrict inBitSet
     131                      /**< Input psBitSet */
     132                     );
    109133
    110134/** Convert the psBitSet to a string of ones and zeros.
     
    115139 *  @return  char*: Pointer to character array containing string data.
    116140 */
    117 char *psBitSetToString(
    118     const psBitSet *restrict inMask /**< psBitSet to convert */
    119 );
     141
     142char *psBitSetToString(const psBitSet * restrict inMask
     143                       /**< psBitSet to convert */
     144                      );
    120145
    121146/// @}
  • trunk/psLib/src/types/psList.c

    r1406 r1407  
     1
    12/** @file psList.c
    23 *  @brief Support for doubly linked lists
     
    67 *  @author Robert Daniel DeSonia, MHPCC
    78 *
    8  *  @version $Revision: 1.13 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2004-08-06 22:34:05 $
     9 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
     10 *  @date $Date: 2004-08-07 00:06:06 $
    1011 *
    1112 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1516#include <stdbool.h>
    1617#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.
    1819
    1920#include "psError.h"
     
    2425#include "psLogMsg.h"
    2526
    26 #define ITER_INIT_HEAD ((void *)1) // next iteration should return head
    27 #define ITER_INIT_TAIL ((void *)2) // next iteration should return tail
     27#define ITER_INIT_HEAD ((void *)1)         // next iteration should return head
     28#define ITER_INIT_TAIL ((void *)2)         // next iteration should return tail
    2829
    2930// 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 
     31static psListElem *listGetIterator(psList * list);
     32static int listGetIteratorIndex(psList * list);
     33static void listSetIterator(psList * list, int where, bool lockList);
     34static void listFree(psList * list);
    3535
    3636psList *psListAlloc(void *data)
    3737{
    3838    psList *list = psAlloc(sizeof(psList));
    39     p_psMemSetDeallocator(list,(psFreeFcn)listFree);
     39
     40    p_psMemSetDeallocator(list, (psFreeFcn) listFree);
    4041
    4142    list->size = 0;
     
    4445    list->iterIndex = PS_LIST_HEAD;
    4546
    46     pthread_mutex_init(&(list->lock),NULL)
     47    pthread_mutex_init(&(list->lock), NULL)
    4748    ;
    4849
     
    5455}
    5556
    56 static void listFree(psList *list)
     57static void listFree(psList * list)
    5758{
    5859    if (list == NULL) {
     
    6364    ;
    6465
    65     for(psListElem *ptr = list->head; ptr != NULL; ) {
     66    for (psListElem * ptr = list->head; ptr != NULL;) {
    6667        psListElem *next = ptr->next;
    6768
     
    8081}
    8182
    82 bool psListAdd(psList *list, void *data, int where)
    83 {
    84     psListElem* position;
    85     psListElem* elem;
     83bool psListAdd(psList * list, void *data, int where)
     84{
     85    psListElem *position;
     86    psListElem *elem;
    8687    int cursorIndex = 0;
    8788
     
    9596
    9697    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);
    101100        return false;
    102101    }
     
    108107
    109108    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);
    113111        where = PS_LIST_TAIL;
    114112    }
     
    138136
    139137        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        }
    144141        // insert our new element in front of the given position
    145142        elem->prev = position->prev;
     
    147144        position->prev = elem;
    148145
    149         if (elem->prev == NULL) { // must be front of list
     146        if (elem->prev == NULL) {          // must be front of list
    150147            list->head = elem;
    151148        } else {
     
    167164
    168165/*****************************************************************************/
     166
    169167/*
    170168 * Remove an element from a list
    171169 */
    172 bool psListRemove(psList *list, void *data, int which)
    173 {
    174     psListElem *elem = NULL;  // element to remove
     170bool psListRemove(psList * list, void *data, int which)
     171{
     172    psListElem *elem = NULL;    // element to remove
    175173    int cursorIndex = 0;
    176174
    177175    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__);
    179177        return false;
    180178    }
    181 
    182179    // get exclusive access to list so that other threads will not get in the way.
    183180    pthread_mutex_lock(&list->lock)
     
    187184        // search list for the data item.
    188185
    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) {
    191189            if (ptr->data == data) {
    192190                which = i;
     
    201199        }
    202200    }
    203 
    204201    // position the list's cursor to the desired location
    205     listSetIterator(list,which,false);
     202    listSetIterator(list, which, false);
    206203    elem = listGetIterator(list);
    207204    cursorIndex = listGetIteratorIndex(list);
    208205
    209206    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);
    211208        return false;
    212209    }
     
    214211    list->size--;
    215212
    216     if (elem->prev == NULL) { // head of list?
     213    if (elem->prev == NULL) {              // head of list?
    217214        list->head = elem->next;
    218215    } else {
     
    220217    }
    221218
    222     if (elem->next == NULL) { // tail of list?
     219    if (elem->next == NULL) {              // tail of list?
    223220        list->tail = elem->prev;
    224221
     
    246243}
    247244
    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;
     245void psListSetIterator(psList * list, int where)
     246{
     247    listSetIterator(list, where, true);
     248}
     249
     250void listSetIterator(psList * list, int where, bool lockList)
     251{
     252    psListElem *cursor;
    256253    int position;
    257254
    258255    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__);
    260257        return;
    261258    }
     
    291288        if (cursor != NULL) {
    292289            list->iter = cursor->prev;
    293             list->iterIndex = position-1;
     290            list->iterIndex = position - 1;
    294291        }
    295292        break;
     
    301298        if (cursor != NULL) {
    302299            list->iter = cursor->next;
    303             list->iterIndex = position+1;
     300            list->iterIndex = position + 1;
    304301        }
    305302        break;
     
    309306
    310307    default:
    311         if (where <= PS_LIST_HEAD) { // bascially same as PS_LIST_UNKNOWN above
    312             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.");
    313310        } else {
    314311            cursor = listGetIterator(list);
    315             if (cursor == NULL) { // reset the iterator if it is invalid
     312            if (cursor == NULL) {      // reset the iterator if it is invalid
    316313                list->iter = ITER_INIT_HEAD;
    317314                list->iterIndex = 0;
     
    321318
    322319            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);
    326324                }
    327325            } 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);
    331330                }
    332331            }
     
    341340}
    342341
    343 psListElem* listGetIterator(psList* list)
     342psListElem *listGetIterator(psList * list)
    344343{
    345344    if (list == NULL) {
     
    349348    if (list->iter == ITER_INIT_HEAD) {
    350349        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
     357int listGetIteratorIndex(psList * list)
    360358{
    361359    if (list->iter == ITER_INIT_HEAD) {
    362360        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
     368void *psListGet(psList * list, int which)
     369{
     370    psListElem *element;
     371
     372    psListSetIterator(list, which);
    376373    element = listGetIterator(list);
    377374
     
    382379    }
    383380}
     381
    384382/*
    385383 * and now return the previous/next element of the list
    386384 */
    387 void *psListGetNext(psList *list)
     385void *psListGetNext(psList * list)
    388386{
    389387    return psListGet(list, PS_LIST_NEXT);
    390388}
    391389
    392 void *psListGetPrevious(psList *list)
     390void *psListGetPrevious(psList * list)
    393391{
    394392    return psListGet(list, PS_LIST_PREVIOUS);
    395393}
    396394
    397 void *psListGetCurrent(psList *list)
     395void *psListGetCurrent(psList * list)
    398396{
    399397    return psListGet(list, PS_LIST_CURRENT);
     
    403401 * Convert a psList to/from a psVoidPtrArray
    404402 */
    405 psArray* psListToArray(psList* restrict list)
    406 {
    407     psListElem* ptr;
     403psArray *psListToArray(psList * restrict list)
     404{
     405    psListElem *ptr;
    408406    unsigned int n;
    409     psArray* restrict arr;
     407    psArray *restrict arr;
    410408
    411409    if (list == NULL) {
     
    431429}
    432430
    433 psList* psArrayToList(psArray* arr)
     431psList *psArrayToList(psArray * arr)
    434432{
    435433    unsigned int n;
    436     psList* list; // list of elements
     434    psList *list;              // list of elements
    437435
    438436    if (arr == NULL) {
     
    443441    n = arr->n;
    444442    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);
    446444    }
    447445
     
    449447}
    450448
    451 
    452 psList* psListSort(psList* list, psComparePtrFcn compare)
    453 {
    454     psArray* arr;
     449psList *psListSort(psList * list, psComparePtrFcn compare)
     450{
     451    psArray *arr;
     452
    455453    if (list == NULL) {
    456454        return NULL;
    457455    }
    458 
    459456    // convert to indexable vector for use by qsort.
    460457    arr = psListToArray(list);
    461458    psFree(list);
    462459
    463     arr = psArraySort(arr,compare);
     460    arr = psArraySort(arr, compare);
    464461
    465462    // convert back to linked list
  • trunk/psLib/src/types/psList.h

    r1228 r1407  
    11#if !defined(PS_LIST_H)
    2 #define PS_LIST_H
     2#    define PS_LIST_H
    33
    44/** @file psList.h
     
    1010 *  @ingroup LinkedList
    1111 *
    12  *  @version $Revision: 1.9 $ $Name: not supported by cvs2svn $
    13  *  @date $Date: 2004-07-15 22:18:02 $
     12 *  @version $Revision: 1.10 $ $Name: not supported by cvs2svn $
     13 *  @date $Date: 2004-08-07 00:06:06 $
    1414 *
    1515 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1616 */
    1717
    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.
    2020
    21 #include "psCompare.h"
    22 #include "psArray.h"
     21#    include "psCompare.h"
     22#    include "psArray.h"
    2323
    2424/** @addtogroup LinkedList
     
    3333 */
    3434enum {
    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)
     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)
    4141};
    4242
     
    4444typedef struct psListElem
    4545{
    46     struct psListElem *prev;            ///< previous link in list
    47     struct psListElem *next;            ///< next link in list
    48     void *data;                         ///< real data item
     46    struct psListElem *prev;    // /< previous link in list
     47    struct psListElem *next;    // /< next link in list
     48    void *data;                 // /< real data item
    4949}
    5050psListElem;
     
    5757typedef struct
    5858{
    59     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
     59    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
    6565}
    6666psList;
     
    7070 *  @return psList*     A new psList object.
    7171 */
    72 psList* psListAlloc(
    73     void *data
    74     ///< initial data item; may be NULL if no an empty psList is desired
    75 )
     72psList *psListAlloc(void *data
     73                    // /< initial data item; may be NULL if no an empty psList is desired
     74                   )
    7675;
    7776
     
    8180 *                      NULL, the return value will also be NULL.
    8281 */
    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 );
     82bool 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              );
    8886
    8987/** Remove an item from a list.  If which parameter is PS_LIST_UNKNOWN,
     
    9189 *  @return bool        TRUE if element is successfully removed, otherwise FALSE.
    9290 */
    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 );
     91bool 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                 );
    10198
    10299/** Retrieve an item from a list.
     
    107104 *                      NULL is returned.
    108105 */
    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 );
     106void *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               );
    113109
    114110/** Set the iterator of the list to a given position.  If where is invalid the
     
    116112 *
    117113 */
    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 );
     114void psListSetIterator(psList * restrict list,  // /< list to retrieve element from
     115                       int where        // /< index number, PS_LIST_HEAD, or PS_LIST_TAIL
     116                      );
    122117
    123118/** Get next element relative to the iterator.  This also moves the iterator to
     
    128123 *                      parameter was NULL.
    129124 */
    130 void* psListGetNext(
    131     psList* restrict list              ///< list to retrieve element from
    132 );
     125void *psListGetNext(psList * restrict list      // /< list to retrieve element from
     126                   );
    133127
    134128/** Get current element according to the psList's iterator cursor.  This does
     
    139133 *                      iterator is not valid or list parameter was NULL.
    140134 */
    141 void* psListGetCurrent(
    142     psList* restrict list              ///< list to retrieve element from
    143 );
     135void *psListGetCurrent(psList * restrict list   // /< list to retrieve element from
     136                      );
    144137
    145138/** Get previous element relative to list's iterator. This also moves the
     
    150143 *                      parameter was NULL.
    151144 */
    152 void* psListGetPrevious(
    153     psList* restrict list              ///< list to retrieve element from
    154 );
     145void *psListGetPrevious(psList * restrict list  // /< list to retrieve element from
     146                       );
    155147
    156148/** Convert a linked list to an array
     
    159151 *                      or NULL if the given dlist parameter is NULL.
    160152 */
    161 psArray* psListToArray(
    162     psList *dlist                      ///< List to convert
    163 );
     153psArray *psListToArray(psList * dlist   // /< List to convert
     154                      );
    164155
    165156/** Convert array to a doubly-linked list
     
    168159 *                      or NULL is the given arr parameter is NULL.
    169160 */
    170 psList* psArrayToList(
    171     psArray* arr                      ///< vector to convert
    172 );
     161psList *psArrayToList(psArray * arr     // /< vector to convert
     162                     );
    173163
    174 psList* psListSort(psList* list, psComparePtrFcn compare);
     164psList *psListSort(psList * list, psComparePtrFcn compare);
    175165
    176166/// @} End of DataGroup Functions
    177167
    178168#endif
    179 
  • trunk/psLib/src/types/psMetadata.c

    r1406 r1407  
     1
    12/** @file  psMetadata.c
    23*
     
    1112*  @author Ross Harman, MHPCC
    1213*
    13 *  @version $Revision: 1.14 $ $Name: not supported by cvs2svn $
    14 *  @date $Date: 2004-08-06 22:34:05 $
     14*  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
     15*  @date $Date: 2004-08-07 00:06:06 $
    1516*
    1617*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
     
    1819
    1920/******************************************************************************/
     21
    2022/*  INCLUDE FILES                                                             */
     23
    2124/******************************************************************************/
    2225#include<stdio.h>
     
    3437#include "psString.h"
    3538
    36 
    3739/******************************************************************************/
     40
    3841/*  DEFINE STATEMENTS                                                         */
     42
    3943/******************************************************************************/
    4044
     
    5660
    5761/******************************************************************************/
     62
    5863/*  TYPE DEFINITIONS                                                          */
     64
    5965/******************************************************************************/
    6066
     
    6268
    6369/*****************************************************************************/
     70
    6471/*  GLOBAL VARIABLES                                                         */
     72
    6573/*****************************************************************************/
    6674
     
    6876
    6977/*****************************************************************************/
     78
    7079/*  FILE STATIC VARIABLES                                                    */
     80
    7181/*****************************************************************************/
    7282
     
    7484
    7585/*****************************************************************************/
     86
    7687/*  FUNCTION IMPLEMENTATION - LOCAL                                          */
    77 /*****************************************************************************/
    78 static void metadataItemFree( psMetadataItem *metadataItem )
     88
     89/*****************************************************************************/
     90static void metadataItemFree(psMetadataItem * metadataItem)
    7991{
    8092    psMetadataType type;
     
    8294    type = metadataItem->type;
    8395
    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 ||
    93105            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
     111static void metadataFree(psMetadata * metadata)
     112{
     113    if (metadata == NULL) {
     114        return;
     115    }
     116    psFree(metadata->list);
     117    psFree(metadata->table);
     118}
     119
     120/*****************************************************************************/
     121
    112122/* FUNCTION IMPLEMENTATION - PUBLIC                                          */
    113 /*****************************************************************************/
    114 
    115 psMetadataItem *psMetadataItemAlloc( const char *name, psMetadataType type, const char *comment, ... )
     123
     124/*****************************************************************************/
     125
     126psMetadataItem *psMetadataItemAlloc(const char *name, psMetadataType type, const char *comment, ...)
    116127{
    117128    va_list argPtr;
     
    119130
    120131    // Get the variable list parameters to pass to allocation function
    121     va_start( argPtr, comment );
     132    va_start(argPtr, comment);
    122133
    123134    // Call metadata item allocation
    124     metadataItem = psMetadataItemAllocV( name, type, comment, argPtr );
     135    metadataItem = psMetadataItemAllocV(name, type, comment, argPtr);
    125136
    126137    // Clean up stack after variable arguement has been used
    127     va_end( argPtr );
     138    va_end(argPtr);
    128139
    129140    return metadataItem;
    130141}
    131142
    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 
     143psMetadataItem *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    }
    141152    // 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    }
    147157    // Set deallocator
    148     p_psMemSetDeallocator( metadataItem, ( psFreeFcn ) metadataItemFree );
     158    p_psMemSetDeallocator(metadataItem, (psFreeFcn) metadataItemFree);
    149159
    150160    // 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) {
    153163        // Per SDRS, null isn't allowed, must use "" instead
    154         strncpy( metadataItem->comment, "", MAX_STRING_LENGTH );
     164        strncpy(metadataItem->comment, "", MAX_STRING_LENGTH);
    155165    } else {
    156         strncpy( metadataItem->comment, comment, MAX_STRING_LENGTH );
     166        strncpy(metadataItem->comment, comment, MAX_STRING_LENGTH);
    157167    }
    158168
    159169    // Set metadata item unique id
    160     *( int* ) ( &metadataItem->id ) = ++metadataId;
     170    *(int *)(&metadataItem->id) = ++metadataId;
    161171
    162172    // Set metadata item type
     
    164174
    165175    // Set metadata item value
    166     switch(type) {
     176    switch (type) {
    167177    case PS_META_BOOL:
    168         metadataItem->data.B = ( bool ) va_arg( argPtr, int );
     178        metadataItem->data.B = (bool) va_arg(argPtr, int);
     179
    169180        break;
    170181    case PS_META_S32:
    171         metadataItem->data.S32 = va_arg( argPtr, psS32 );
     182        metadataItem->data.S32 = va_arg(argPtr, psS32);
    172183        break;
    173184    case PS_META_F32:
    174         metadataItem->data.F32 = ( psF32 ) va_arg( argPtr, psF64 );
     185        metadataItem->data.F32 = (psF32) va_arg(argPtr, psF64);
    175186        break;
    176187    case PS_META_F64:
    177         metadataItem->data.F64 = va_arg( argPtr, psF64 );
     188        metadataItem->data.F64 = va_arg(argPtr, psF64);
    178189        break;
    179190    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
    181193        break;
    182194    case PS_META_IMG:
     
    186198    case PS_META_UNKNOWN:
    187199    default:
    188         psError( __func__, "Invalid psMetadataType: %d", type );
     200        psError(__func__, "Invalid psMetadataType: %d", type);
    189201    }
    190202
    191203    // 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);
    194206
    195207    // Allocate metadata items with same name.
    196     metadataItem->items = psListAlloc( NULL );
     208    metadataItem->items = psListAlloc(NULL);
    197209
    198210    return metadataItem;
    199211}
    200212
    201 psMetadata *psMetadataAlloc( void )
    202 {
    203     psList * list = NULL;
     213psMetadata *psMetadataAlloc(void)
     214{
     215    psList *list = NULL;
    204216    psHash *table = NULL;
    205217    psMetadata *metadata = NULL;
    206218
    207219    // 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    }
    213224    // Set deallocator
    214     p_psMemSetDeallocator( metadata, ( psFreeFcn ) metadataFree );
     225    p_psMemSetDeallocator(metadata, (psFreeFcn) metadataFree);
    215226
    216227    // 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");
    225236    }
    226237
     
    231242}
    232243
    233 bool psMetadataAddItem( psMetadata *restrict md, int where, psMetadataItem *restrict metadataItem )
    234 {
    235     char * key = NULL;
     244bool psMetadataAddItem(psMetadata * restrict md, int where, psMetadataItem * restrict metadataItem)
     245{
     246    char *key = NULL;
    236247    psHash *mdTable = NULL;
    237248    psList *mdList = NULL;
     
    239250    psMetadataType type = PS_META_ITEM_SET;
    240251
    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");
    248259        return false;
    249260    }
     
    252263
    253264    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");
    262273        return false;
    263274    }
    264275
    265276    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    }
    271281    // 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) {
    274284
    275285        // The key was found and the new metadata item is a leaf node (its type isn't PS_META_ITEM_SET), so
    276286        // 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);
    280289            return false;
    281290        }
    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);
    289304            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    }
    299307
    300308    // 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);
    304312        return false;
    305313    }
     
    308316}
    309317
    310 bool psMetadataAdd( psMetadata *restrict md, int where, const char *name, psMetadataType type,
    311                     const char *comment, ... )
     318bool psMetadataAdd(psMetadata * restrict md, int where, const char *name, psMetadataType type,
     319                   const char *comment, ...)
    312320{
    313321    va_list argPtr;
    314322    psMetadataItem *metadataItem = NULL;
    315323
    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 needed here
    328     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);
    329337
    330338    return true;
    331339}
    332340
    333 bool psMetadataRemove( psMetadata *restrict md, int where, const char *restrict key )
     341bool psMetadataRemove(psMetadata * restrict md, int where, const char *restrict key)
    334342{
    335343    int numChildren = 0;
     
    340348
    341349    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");
    344352        return false;
    345353    }
    346354
    347355    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    }
    353360    // Select removal by key or index
    354     if(key != NULL) {
     361    if (key != NULL) {
    355362
    356363        // 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);
    360367            return false;
    361368        }
    362369
    363370        numChildren = entry->items->size;
    364         if(entry->type == PS_META_ITEM_SET && numChildren > 0) {
     371        if (entry->type == PS_META_ITEM_SET && numChildren > 0) {
    365372
    366373            // 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);
    372379                    return false;
    373380                }
    374                 entryChild = psListGetNext( entry->items );
     381                entryChild = psListGetNext(entry->items);
    375382            }
    376383        }
    377 
    378384        // 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);
    381387            return false;
    382388        }
    383 
    384389        // 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);
    387392            return false;
    388393        }
     
    390395
    391396        // 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);
    395400            return false;
    396401        }
    397402
    398403        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);
    401406            return false;
    402407        }
    403 
    404408        // Use recursive remove, now that key is known
    405         psMetadataRemove( md, PS_LIST_UNKNOWN, key );
     409        psMetadataRemove(md, PS_LIST_UNKNOWN, key);
    406410    }
    407411
     
    409413}
    410414
    411 psMetadataItem *psMetadataLookup( psMetadata *restrict md, const char *restrict key )
    412 {
    413     psHash * mdTable = NULL;
     415psMetadataItem *psMetadataLookup(psMetadata * restrict md, const char *restrict key)
     416{
     417    psHash *mdTable = NULL;
    414418    psMetadataItem *entry = NULL;
    415419
    416420    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);
    430434        return NULL;
    431435    }
     
    434438}
    435439
    436 psMetadataItem *psMetadataGet( psMetadata *restrict md, int where )
    437 {
    438     psList * mdList = NULL;
     440psMetadataItem *psMetadataGet(psMetadata * restrict md, int where)
     441{
     442    psList *mdList = NULL;
    439443    psMetadataItem *entry = NULL;
    440444
    441445    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);
    450454        return NULL;
    451455    }
     
    454458}
    455459
    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 );
     460bool 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);
    467471
    468472    return true;
    469473}
    470474
    471 psMetadataItem *psMetadataGetNext( psMetadata *restrict md, const char *restrict match, int which )
    472 {
    473     psList * mdList = NULL;
     475psMetadataItem *psMetadataGetNext(psMetadata * restrict md, const char *restrict match, int which)
     476{
     477    psList *mdList = NULL;
    474478    psMetadataItem *entry = NULL;
    475479
    476480    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))) {
    492496
    493497            // Match found
    494498            return entry;
    495499        }
    496         entry = psListGetNext( mdList );
     500        entry = psListGetNext(mdList);
    497501    }
    498502
    499503    // 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);
    502506    }
    503507
     
    505509}
    506510
    507 psMetadataItem *psMetadataGetPrevious( psMetadata *restrict md, const char *restrict match, int which )
    508 {
    509     psList * mdList = NULL;
     511psMetadataItem *psMetadataGetPrevious(psMetadata * restrict md, const char *restrict match, int which)
     512{
     513    psList *mdList = NULL;
    510514    psMetadataItem *entry = NULL;
    511515
    512516    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))) {
    528532
    529533            // Match found
    530534            return entry;
    531535        }
    532         entry = psListGetPrevious( mdList );
     536        entry = psListGetPrevious(mdList);
    533537    }
    534538
    535539    // 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);
    538542    }
    539543
     
    541545}
    542546
    543 void psMetadataItemPrint( FILE *fd, const char *format, const psMetadataItem *restrict metadataItem )
     547void psMetadataItemPrint(FILE * fd, const char *format, const psMetadataItem * restrict metadataItem)
    544548{
    545549    psMetadataType type;
    546550
    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;
    560564    }
    561565
    562566    type = metadataItem->type;
    563567
    564     switch(type) {
     568    switch (type) {
    565569    case PS_META_BOOL:
    566         fprintf( fd, format, metadataItem->data.B );
     570        fprintf(fd, format, metadataItem->data.B);
    567571        break;
    568572    case PS_META_S32:
    569         fprintf( fd, format, metadataItem->data.S32 );
     573        fprintf(fd, format, metadataItem->data.S32);
    570574        break;
    571575    case PS_META_F32:
    572         fprintf( fd, format, metadataItem->data.F32 );
     576        fprintf(fd, format, metadataItem->data.F32);
    573577        break;
    574578    case PS_META_F64:
    575         fprintf( fd, format, metadataItem->data.F64 );
     579        fprintf(fd, format, metadataItem->data.F64);
    576580        break;
    577581    case PS_META_STR:
    578         fprintf( fd, format, metadataItem->data.V );
     582        fprintf(fd, format, metadataItem->data.V);
    579583        break;
    580584    case PS_META_ITEM_SET:
     
    585589    case PS_META_UNKNOWN:
    586590    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
     595psMetadata *psMetadataFReadHeader(psMetadata * output, char *extName, int extNum, fitsfile * fd)
    592596{
    593597    bool tempBool;
    594598    bool success;
    595599    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];
    600604    int i;
    601605    int hduType = 0;
     
    605609    psMetadataType metadataItemType;
    606610
    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    }
    621623    // Allocate metadata if user didn't
    622     if(output == NULL) {
     624    if (output == NULL) {
    623625        output = psMetadataAlloc();
    624626    }
    625 
    626627    // 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) {
    629630            FITS_ERROR("FITS error while locating header %s: %s", extName);
    630631        }
    631632    } else {
    632         if(fits_movabs_hdu( fd, extNum, &hduType, &status ) != 0) {
     633        if (fits_movabs_hdu(fd, extNum, &hduType, &status) != 0) {
    633634            FITS_ERROR("FITS error while locating header %d: %s", extNum);
    634635        }
     
    636637
    637638    // 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) {
    639640        FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    640641    }
    641 
    642642    // 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) {
    645645            FITS_ERROR("FITS error while reading key %d: %s", keyNum);
    646646        }
    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) {
    650650                FITS_ERROR("FITS error while determining key %d type: %s", keyNum);
    651651            } 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
    653654                keyType = 'C';
    654655                status = 0;
     
    656657        }
    657658
    658         switch(keyType) {
     659        switch (keyType) {
    659660        case 'I':
    660661            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));
    662665            break;
    663666        case 'F':
    664667            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));
    666671            break;
    667672        case 'C':
    668673            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);
    670676            break;
    671677        case 'L':
    672678            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);
    675682            break;
    676683        case 'U':
    677684        case 'X':
    678685        default:
    679             psError( __func__, "Invalid psMetadataType: %c", keyType );
     686            psError(__func__, "Invalid psMetadataType: %c", keyType);
    680687            return output;
    681688        }
    682689
    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);
    685692            return output;
    686693        }
  • trunk/psLib/src/types/psMetadata.h

    r1394 r1407  
     1
    12/** @file  psMetadata.h
    23*
     
    1011*  @author Ross Harman, MHPCC
    1112*
    12 *  @version $Revision: 1.15 $ $Name: not supported by cvs2svn $
    13 *  @date $Date: 2004-08-05 20:55:22 $
     13*  @version $Revision: 1.16 $ $Name: not supported by cvs2svn $
     14*  @date $Date: 2004-08-07 00:06:06 $
    1415*
    1516*  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
    1617*/
    1718#ifndef PS_METADATA_H
    18 #define PS_METADATA_H
    19 
    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"
    2627
    2728/// @addtogroup Metadata
     
    3334 */
    3435typedef enum {
    35     PS_META_ITEM_SET = 0,                   ///< Null. Metadata is in psMetadataItem.items
    36     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.
    4748} psMetadataType;
    4849
     
    5455typedef struct psMetadataItem
    5556{
    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 {
    6161        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.
    6969}
    7070psMetadataItem;
     
    7878typedef struct psMetadata
    7979{
    80     psList* restrict list;
    81     psHash* restrict table;
     80    psList *restrict list;
     81    psHash *restrict table;
    8282}
    8383psMetadata;
    8484
    85 
    8685/*****************************************************************************/
     86
    8787/* FUNCTION PROTOTYPES                                                       */
     88
    8889/*****************************************************************************/
    8990
     
    101102 * @return psMetadataItem*: Pointer metadata item.
    102103 */
    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 );
     104psMetadataItem *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                                   );
    109109
    110110/** Create a metadata item with va_list.
     
    121121 * @return psMetadataItem*: Pointer metadata item.
    122122 */
    123 psMetadataItem *psMetadataItemAllocV(
    124     const char *name,                       ///< Name of metadata item.
    125     psMetadataType type,                    ///< Type of metadata item.
    126     const char *comment,                    ///< Comment for metadata item.
    127     va_list list                        ///< Arguments for name formatting and metadata item data.
    128 );
     123psMetadataItem *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                                    );
    129129
    130130/** Create a metadata collection.
     
    134134 * @return psMetadata*: Pointer metadata.
    135135 */
    136 psMetadata *psMetadataAlloc(
    137     void                                ///< Void.
    138 );
     136psMetadata *psMetadataAlloc(void        // /< Void.
     137                           );
    139138
    140139/** Add existing metadata item to metadata collection.
     
    144143 * @return bool: True for success, false for failure.
    145144 */
    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 );
     145bool 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                      );
    151149
    152150/** Create and add a metadata item to metadata collection.
     
    156154 * @return bool: True for success, false for failure.
    157155 */
    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 );
     156bool 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                  );
    166163
    167164/** Remove an item from metadata collection.
     
    174171 * @return bool: True for success, false for failure.
    175172 */
    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 );
     173bool 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                     );
    181177
    182178/** Find an item in the metadata collection based on key name.
     
    187183 * @return psMetadataItem*: Pointer metadata item.
    188184 */
    189 psMetadataItem *psMetadataLookup(
    190     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    191     const char *restrict key            ///< Name of metadata key.
    192 );
     185psMetadataItem *psMetadataLookup(psMetadata * restrict md,      // /< Metadata collection to insert metadat
     186                                 // item.
     187                                 const char *restrict key       // /< Name of metadata key.
     188                                );
    193189
    194190/** Find an item in the metadata collection based on list index.
     
    198194 * @return psMetadataItem*: Pointer metadata item.
    199195 */
    200 psMetadataItem *psMetadataGet(
    201     psMetadata *restrict md,                ///< Metadata collection to insert metadat item.
    202     int where                           ///< Location to be retrieved.
    203 );
     196psMetadataItem *psMetadataGet(psMetadata * restrict md, // /< Metadata collection to insert metadat item.
     197                              int where // /< Location to be retrieved.
     198                             );
    204199
    205200/** Set or reset metadata iterator.
     
    209204 * @return void: void.
    210205 */
    211 bool psMetadataSetIterator(
    212     psMetadata *restrict md,                ///< Metadata collection to iterate.
    213     int where                           ///< Location of iterator.
    214 );
     206bool psMetadataSetIterator(psMetadata * restrict md,    // /< Metadata collection to iterate.
     207                           int where    // /< Location of iterator.
     208                          );
    215209
    216210/** Get next metadata item.
     
    220214 * @return psMetadataItem*: Pointer metadata item.
    221215 */
    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 );
     216psMetadataItem *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                                 );
    227220
    228221/** Get previous metadata item.
     
    232225 * @return psMetadataItem*: Pointer metadata item.
    233226 */
    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 );
     227psMetadataItem *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                                     );
    239231
    240232/** Print metadata item to file.
     
    248240 * @return psMetadataItem*: Pointer metadata item.
    249241 */
    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 );
     242void 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                        );
    255246
    256247/** Read metadata header.
     
    261252 * @return psMetadata*: Pointer metadata.
    262253 */
    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 );
     254psMetadata *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                                );
    269259
    270260/** Read metadata header.
     
    274264 * @return psMetadata*: Pointer metadata.
    275265 */
    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 );
     266psMetadata *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
    282272/// @}
    283273
Note: See TracChangeset for help on using the changeset viewer.