Utilities in libcfshr

The utility functions listed here are in defined various separate files. They are declared in cfsemshare.h, which includes mrcslice.h and is included by b3dutil.h.

Functions for Tapering and Padding Images


void sliceTaperOutPad(void *array, int type, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny, int ifmean, float dmeanin)
void taperoutpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *ifmean, float *dmeanin)
void sliceTaperInPad(void *array, int type, int nxdimin, int ix0, int ix1, int iy0, int iy1, float *brray, int nxdim, int nx, int ny, int nxtap, int nytap)
void taperinpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *nxtap, int *nytap)
void sliceSmoothOutPad(void *array, int type, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny)
void smoothoutpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny)
double sliceEdgeMean(float *array, int nxdim, int ixlo, int ixhi, int iylo, int iyhi)
double sliceedgemean(float *array, int *nxdim, int *ixlo, int *ixhi, int *iylo, int *iyhi)
void sliceSplitFill(float *array, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny, int iffill, float fillin)
void splitfill(float *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *iffill, float *fillin)

Functions for Tapering an Image at Fill Areas


int sliceTaperAtFill(Islice *sl, int ntaper, int inside)
int taperatfill(float *array, int *nx, int *ny, int *ntaper, int *inside)

Functions for Fourier Correlation and Filtering


void XCorrSetCTF(float sigma1, float sigma2, float radius1, float radius2, float *ctf, int nx, int ny, float *delta)
void setctfwsr(float *sigma1, float *sigma2, float *radius1, float *radius2, float *ctf, int *nx, int *ny, float *delta)
void XCorrSetCTFnoScl(float sigma1, float sigma2, float radius1, float radius2, float *ctf, int nx,int ny, float *delta, int *nsizeOut)
void setctfnoscl(float *sigma1, float *sigma2, float *radius1, float *radius2, float *ctf, int *nx, int *ny, float *delta, int *nsize)
void XCorrFilterPart(float *fft, float *array, int nx, int ny, float *ctf, float delta)
void filterpart(float *fft, float *array, int *nx, int *ny, float *ctf, float *delta)
void XCorrMeanZero(float *array, int nxdim, int nx, int ny)
void meanzero(float *array, int *nxdim, int *nx, int *ny)
void XCorrPeakFind(float *array, int nxdim, int ny, float *xpeak, float *ypeak, float *peak, int maxpeaks)
void xcorrpeakfind(float *array, int *nxdim, int *ny, float *xpeak, float *ypeak, float *peak, int *maxpeaks)
double parabolicFitPosition(float y1, float y2, float y3)
double parabolicfitposition(float *y1, float *y2, float *y3)
void conjugateProduct(float *array, float *brray, int nx, int ny)
void conjugateproduct(float *array, float *brray, int *nx, int *ny)
double XCorrCCCoefficient(float *array, float *brray, int nxdim, int nx, int ny, float xpeak, float ypeak, int nxpad, int nypad, int *nsum)
double cccoefficient(float *array, float *brray, int *nxdim, int *nx, int *ny, float *xpeak, float *ypeak, int *nxpad, int *nypad, int *nsum)

Sobel Filter Function


int scaledSobel(float *inImage, int nxin, int nyin, float scaleFac, float minInterp, int linear, float center, float *outImage, int *nxout, int *nyout, float *xOffset, float *yOffset)

Function for Image Transformation by Interpolation


void cubinterp(float *array, float *bray, int nxa, int nya, int nxb, int nyb, float amat[2][2], float xc, float yc, float xt, float yt, float scale, float dmean, int linear)

Functions for Image Reduction with Filtering


int selectZoomFilter(int type, double zoom, int *outWidth)
int selectzoomfilter(int *type, float *zoom, int *outWidth)
int zoomWithFilter(unsigned char **slines, int aXsize, int aYsize, float aXoff, float aYoff, int bXsize, int bYsize, int bXdim, int bXoff, int dtype, void *outData, b3dUInt32 *cindex, unsigned char *bindex)
int zoomwithfilter(float *array, int *aXsize, int *aYsize, float *aXoff, float *aYoff, int *bXsize, int *bYsize, int *bXdim, int *bXoff, float *outData)
int zoomFiltInterp(float *array, float *bray, int nxa, int nya, int nxb, int nyb, float xc, float yc, float xt, float yt, float dmean)
int zoomfiltinterp(float *array, float *bray, int *nxa, int *nya, int *nxb, int *nyb, float *xc, float *yc, float *xt, float *yt, float *dmean)

Binning Function


int reduceByBinning(void *array, int type, int nxin, int nyin, int nbin, void *brray, int keepByte, int *nxr, int *nyr)
void reduce_by_binning(float *array, int *nx, int *ny, int *nbin, float *brray, int *nxr, int *nyr)

Functions for Working with Linear Transformations


void xfUnit(float *f, float val, int rows)
void xfCopy(float *f1, int rows1, float *f2, int rows2)
void xfMult(float *f1, float *f2, float *prod, int rows)
void xfInvert(float *f, float *finv, int rows)
void xfApply(float *f, float xcen, float ycen, float x, float y, float *xp, float *yp, int rows)

Functions for Converting Linear Transformation


void amatToRotmagstr(float a11, float a12, float a21, float a22, float *theta, float *smag, float *str, float *phi)
void amat_to_rotmagstr(float *amat, float *theta, float *smag, float *str, float *phi)
void rotmagstrToAmat(float theta, float smag, float str, float phi, float *a11, float *a12, float *a21, float *a22)
void rotmagstr_to_amat(float *theta, float *smag, float *str, float *phi, float *amat)

Functions for Fitting Circles and Spheres


int circleThrough3Pts(float x1, float y1, float x2, float y2, float x3, float y3, float *rad, float *xc, float *yc)
int fitSphere(float *xpt, float *ypt, float *zpt, int numPts, float *rad, float *xcen, float *ycen, float *zcen, float *rmsErr)
int fitSphereWgt(float *xpt, float *ypt, float *zpt, float *weights, int numPts, float *rad, float *xcen, float *ycen, float *zcen, float *rmsErr)

Function to Test for Point Inside Boundary


int InsideContour(float *ptX, float *ptY, int np, float x, float y)
int insidecontour(float *ptX, float *ptY, int *np, float *x, float *y)

Function for Finding Convex Boundary


void convexBound(float *sx, float *syin, int npnts, float fracomit, float pad, float *bx, float *by, int *nvert, float *xcen, float *ycen, int maxverts)
void convexbound(float *sx, float *syin, int *npnts, float *fracomit, float *pad, float *bx, float *by, int *nvert, float *xcen, float *ycen, int *maxverts)

Function for Sorting Points onto Two Surfaces


int setSurfSortParam(int index, float value)
int setsurfsortparam(int *index, float *value)
int surfaceSort(float *xyz, int numPts, int *group)
int surfacesort(float *xyz, int *numPts, int *group)
Parameters for surfaceSort

Function for Parsing Lists


int *parselist(const char *line, int *nlist)

Simplex Search Functions


void amoeba(float *p, float *y, int mp, int ndim, float ftol, void (*funk)(float *, float *), int *iterP, float *ptol, int *iloP)
void amoebaInit(float *p, float *y, int mp, int ndim, float delfac, float ptolFac, float *a, float *da, void (*funk)(float *, float *), float *ptol)

Histogram Functions


void kernelHistogram(float *values, int numVals, float *bins, int numBins, float firstVal, float lastVal, float h, int verbose)
void kernelhistogram(float *values, int *numVals, float *bins, int *numBins, float *firstVal, float *lastVal, float *h, int *verbose)
int scanHistogram(float *bins, int numBins, float firstVal, float lastVal, float scanBot, float scanTop, int findPeaks, float *dip, float *peakBelow, float *peakAbove)
int scanhistogram(float *bins, int *numBins, float *firstVal, float *lastVal, float *scanBot, float *scanTop, int *findPeaks, float *dip, float *peakBelow, float *peakAbove)
int findHistogramDip(float *values, int numVals, int minGuess, float *bins, int numBins, float firstVal, float lastVal, float *histDip, float *peakBelow, float *peakAbove, int verbose)
int findhistogramdip(float *values, int *numVals, int *minGuess, float *bins, int *numBins, float *firstVal, float *lastVal, float *histDip, float *peakBelow, float *peakAbove, int *verbose)

Functions for Analyzing Gold Beads


void makeModelBead(int boxSize, float beadSize, float *array)
double beadIntegral(float *array, int nxdim, int nx, int ny, float rCenter, float rInner, float rOuter, float xcen, float ycen, float *cenmean, float *annmean, float *temp, float annPct, float *median)

Functions for Simple Statistics


void avgSD(float *x, int n, float *avg, float *sd, float *sem)
void avgsd(float *x, int *n, float *avg, float *sd, float *sem)
void sumsToAvgSD(float sx, float sxsq, int n, float *avg, float *sd)
void sums_to_avgsd(float *sx, float *sxsq, int *n, float *avg, float *sd)
void sumsToAvgSDdbl(double sx8, double sxsq8, int n1, int n2, float *avg, float *sd)
void sums_to_avgsd8(double *sx8, double *sxsq8, int *n1, int *n2, float *avg, float *sd)
void lsFit(float *x, float *y, int num, float *slope, float *intcp, float *ro)
void lsfit(float *x, float *y, int *num, float *slope, float *intcp, float *ro)
void lsFitPred(float *x, float *y, int n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se, float xpred, float *ypred, float *prederr)
void lsfitpred(float *x, float *y, int *n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se, float *xpred, float *ypred, float *prederr)
void lsfits(float *x, float *y, int *n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se)
void lsFit2(float *x1, float *x2, float *y, int n, float *a, float *b, float *c)
void lsfit2(float *x1, float *x2, float *y, int *n, float *a, float *b, float *c)
void lsfit2noc(float *x1, float *x2, float *y, int *n, float *a, float *b)
void lsFit2Pred(float *x1, float *x2, float *y, int n, float *a, float *b, float *c, float x1pred, float x2pred, float *ypred, float *prederr)
void lsfit2pred(float *x1, float *x2, float *y, int *n, float *a, float *b, float *c, float *x1pred, float *x2pred, float *ypred, float *prederr)
void lsFit3(float *x1, float *x2, float *x3, float *y, int n, float *a1, float *a2, float *a3, float *c)
void lsfit3(float *x1, float *x2, float *x3, float *y, int *n, float *a1, float *a2, float *a3, float *c)

Functions for Sorting and Robust Statistics


void rsSortFloats(float *x, int n)
void rssortfloats(float *x, int *n)
void rsSortIndexedFloats(float *x, int *index, int n)
void rssortindexedfloats(float *x, int *index, int *n)
void rsMedianOfSorted(float *x, int n, float *median)
void rsmedianofsorted(float *x, int *n, float *median)
void rsMedian(float *x, int n, float *xsort, float *median)
void rsmedian(float *x, int *n, float *xsort, float *median)
void rsMADN(float *x, int n, float median, float *tmp, float *MADN)
void rsmadn(float *x, int *n, float *median, float *tmp, float *MADN)
void rsMadMedianOutliers(float *x, int n, float kcrit, float *out)
void rsmadmedianoutliers(float *x, int *n, float *kcrit, float *out)
void rsTrimmedMeanOfSorted(float *x, int n, float gamma, float *trmean)
void rstrimmedmeanofsorted(float *x, int *n, float *gamma, float *median)
void rsTrimmedMean(float *x, int n, float gamma, float *xsort, float *trmean)
void rstrimmedmean(float *x, int *n, float *gamma, float *xsort, float *median)

Functions for Finding a Percentile


float percentileFloat(int s, float *r, int num)
int percentileInt(int s, int *r, int num)

Functions for Statistics by Sampling


int sampleMeanSD(unsigned char **image, int type, int nx, int ny, float sample, int ixStart, int iyStart, int nxUse, int nyUse, float *mean, float *sd)
int samplemeansd(float *image, int *nx, int *ny, float *sample, int *ixStart, int *iyStart, int *nxUse, int *nyUse, float *mean, float *sd)
int percentileStretch(unsigned char **image, int type, int nx, int ny, float sample, int ixStart, int iyStart, int nxUse, int nyUse, float pctLo, float pctHi, float *scaleLo, float *scaleHi)

Statistical Functions


double tValue(double signif, int ndf)
double dtvalue(double *signif, int *ndf)
double fValue(double signif, int ndf1, int ndf2)
double dfvalue(double *signif, int *ndf1, int *ndf2)
double errFunc(double x)
double errfunc(double *x)
double incompBeta(double a, double b, double x)
double incompbeta(double *a, double *b, double *x)
double betaFunc(double p, double q)
double lnGamma(double x)

Gauss-Jordan Function for Solving Linear Equations


int gaussj(float *a, int n, int np, float *b, int m, int mp)

Sparse Matrix Functions to Use with Lsqr


void sparseProd(int mode, int m, int n, double x[], double y[], void *UsrWrk)
void addValueToRow(float val, int icol, float *valRow, int *icolRow, int *numInRow)
void addvaluetorow(float *val, int *icol, float *valRow, int *icolRow, int *numInRow)
int addRowToMatrix(float *valRow, int *icolRow, int numInRow, float *rwrk, int *ia, int *ja, int *numRows, int maxRows, int maxVals)
int addrowtomatrix(float *valRow, int *icolRow, int *numInRow, float *rwrk, int *ia, int *ja, int *numRows, int *maxRows, int *maxVals)
void normalizeColumns(float *rwrk, int *ia, int *ja, int numVars, int numRows, float *sumEntries)
void normalizecolumns(float *rwrk, int *ia, int *ja, int *numVars, int *numRows, float *sumEntries)

Functions for Working with Montage Piece Lists


int checkPieceList(int *pclist, int stride, int npclist, int redfac, int nframe, int *minpiece, int *npieces, int *noverlap)
void checklist(int *pclist, int *npclist, int *redfac, int *nframe, int *minpiece, int *npieces, int *noverlap)
void adjustPieceOverlap(int *pclist, int stride, int npclist, int nframe, int minpiece, int noverlap, int newOverlap)
void adjustpieceoverlap(int *pclist, int *npclist, int *nframe, int *minpiece, int *noverlap, int *newOverlap)

Function for Finding Best Shift of Montage Pieces


int findPieceShiftsint findPieceShifts (int *ivarpc, int nvar, int *indvar, int *ixpclist, int *iypclist, float *dxedge, float *dyedge, int idir, int *pieceLower, int *pieceUpper, int *ifskipEdge, int edgeStep, float *dxyvar, int varStep, int *edgeLower, int *edgeUpper, int pcStep, int *work, int fort, int leaveInd, int skipCrit, float robustCrit, float critMaxMove, float critMoveDiff, int maxIter, int numAvgForTest, int intervalForTest, int *numIter, float *wErrMean, float *wErrMax)

C Functions for Safe Parallel Writing to File


int parWrtInitialize(char *filename, int nxin, int nyin)
int parwrtinitializefw(char *filename, int *nxin, int *nyin, int strlen)
int parWrtProperties(int *allSec, int *linesBound, int *nfiles)
int parwrtproperties(int *allSec, int *linesBound, int *nfiles)
int parWrtSetCurrent(int index)
int parwrtsetcurrentfw(int *index)
int parWrtFindRegion(int secNum, int lineNum, int nlWrite, char **filename, int *sections, int *startLines)
int parwrtfindregion(int *secNum, int *lineNum, int *nlWrite, char *filename, int *sections, int *startLines, int strlen)
int parwrtgetregion(int *regionNum, char *filename, int *sections, int *startLines, int strlen)

Color Map Functions


int *cmapStandardRamp()
int *cmapInvertedRamp()
int cmapConvertRamp(int *rampData, unsigned char table[3][256])
int cmapReadConvert(char *filename, unsigned char table[3][256])
Standard color ramps

Functions for Tapering and Padding Images

void sliceTaperOutPad(void *array, int type, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny, int ifmean, float dmeanin)

Pads an image in array with dimensions nxbox by nybox into the center of a larger array, brray, which can be the same as array.  The SLICE_MODE is specified by type, which must be byte, float or short integer. The size of the padded image is specified by nx and ny while nxdim specifies the X dimension of the output array.  The values of the image in the padding area will be tapered from the value of a pixel at the edge of the input image edge down to a common value.  That value is either the mean at the edge of the input image, if ifmean is zero, or the value supplied in dmeanin, if ifmean is nonzero.

void taperoutpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *ifmean, float *dmeanin)

Fortran wrapper to call sliceTaperOutPad with a floating point array.

void sliceTaperInPad(void *array, int type, int nxdimin, int ix0, int ix1, int iy0, int iy1, float *brray, int nxdim, int nx, int ny, int nxtap, int nytap)

Extracts a subarea of an image, places it into the center of a potentially larger array with padding, and tapers the image down to the mean value at its edge, tapering pixels inside the extracted image area.  The image data are in array, their X dimension is nxdimin, and their SLICE_MODE is given in type.  The mode can be byte, signed or unsigned short, float, or RGB.  The starting and ending coordinates to extract in X and Y are ix0 to ix1 and iy0 to iy1.  The output image array is brray and its X dimension is specified by nxdim.  The padded image size is specified by nx and ny, and nxtap and nytap indicate the number of pixels over which to taper in X and Y.  The output array can be the same as the input array if the input image fills the entire array.

void taperinpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *nxtap, int *nytap)

Fortran wrapper to sliceTaperInPad for padding a whole float image array of size nxbox by nybox.  The output array can be the same as the input array.

void sliceSmoothOutPad(void *array, int type, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny)

Pads an image in array with dimensions nxbox by nybox into the center of a larger array, brray, which can be the same as array.  The SLICE_MODE is specified by type, which must be byte, float or short integer. The size of the padded image is specified by nx and ny while nxdim specifies the X dimension of the output array.  The padding is done by replicating pixels and smoothing lines progressively more for farther out from the pixels in the box.  This is done in a series of progressively larger rectangles; the each pixel in first rectangle contains the average of the three nearest pixels on the outer edge of the actual data; each pixel in the second rectangle is the average of the 5 nearest pixels in the first rectangle, etc.

void smoothoutpad(void *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny)

Fortran wrapper to call sliceSmoothOutPad with a floating point array.

double sliceEdgeMean(float *array, int nxdim, int ixlo, int ixhi, int iylo, int iyhi)

Computes the mean along the edge for the portion of the image in array bounded by X indices ixlo and ixhi and Y indices iylo and iyhi, inclusive.  nxdim is the X dimension of the array.  The mean is based solely on the single columns at ixlo and ixhi and the single rows at iylo and iyhi.

double sliceedgemean(float *array, int *nxdim, int *ixlo, int *ixhi, int *iylo, int *iyhi)

Fortran wrapper to sliceEdgeMean .  The indexes are numbered from 1.

void sliceSplitFill(float *array, int nxbox, int nybox, float *brray, int nxdim, int nx, int ny, int iffill, float fillin)

Splits a small image in array with dimensions nxbox by nybox into the 4 corners of a potentially larger array.  The padded image is placed in brray with a size of nx by ny, where nxdim is the X dimension of brray.  The image will be padded with the mean at the edge of the image, or with the value in fillin if iffill is non-zero.  In either case the values will be shifted so that the mean of the whole array is zero.

void splitfill(float *array, int *nxbox, int *nybox, float *brray, int *nxdim, int *nx, int *ny, int *iffill, float *fillin)

Fortran wrapper to splitFill .

Functions for Tapering an Image at Fill Areas

int sliceTaperAtFill(Islice *sl, int ntaper, int inside)

Analyzes for fill areas at the edge of the slice sl, finds the borders between actual image and fill areas, and tapers the image intensities down to the fill value over ntaper pixels.  If inside is 0 the image intensities at the edge are extended into the fill area, while if inside is 1 then pixels inside the image are attenuated.  Returns -1 for memory allocation errors.

int taperatfill(float *array, int *nx, int *ny, int *ntaper, int *inside)

Fortran wrapper to sliceTaperAtFill for tapering a real*4 image in array of size nx by ny.  Returns -1 for memory error.

Functions for Fourier Correlation and Filtering

void XCorrSetCTF(float sigma1, float sigma2, float radius1, float radius2, float *ctf, int nx, int ny, float *delta)

Takes the filter parameters sigma1, sigma2, radius1, and radius2 and sets up a contrast transfer (filter) function in the array ctf, which should be dimensioned to at least 8193.  The dimensions of the real space image being filtered are specified in nx and ny, and the step size between the values in ctf is returned in delta.  If no filtering is selected (sigma1 and sigma2 both 0) then 0 is returned in delta. The values in ctf are scaled so that mean of all but the zero element is 1.

void setctfwsr(float *sigma1, float *sigma2, float *radius1, float *radius2, float *ctf, int *nx, int *ny, float *delta)

Fortran wrapper for XCorrSetCTF.

void XCorrSetCTFnoScl(float sigma1, float sigma2, float radius1, float radius2, float *ctf, int nx,int ny, float *delta, int *nsizeOut)

Sets up a filter function in ctf as described for XCorrSetCTF, but with no scaling, such that the filter value will be 1 for all unattenuated frequencies.  The number of elements computed in ctf is returned in nizeOut.

void setctfnoscl(float *sigma1, float *sigma2, float *radius1, float *radius2, float *ctf, int *nx, int *ny, float *delta, int *nsize)

Fortran wrapper for XCorrSetCTFnoScl.

void XCorrFilterPart(float *fft, float *array, int nx, int ny, float *ctf, float delta)

Applies the filter in ctf to the 2D Fourier transform in fft, and puts result into array, which can be the same as ctf.  The dimensions of the real space image are given by nx and ny, and the dimension of the real image array are assumed to be nx + 2 by ny.  delta is the interval in reciprocal space (1/pixel) for the function in ctf.

void filterpart(float *fft, float *array, int *nx, int *ny, float *ctf, float *delta)

Fortran wrapper to XCorrFilterPart

void XCorrMeanZero(float *array, int nxdim, int nx, int ny)

Shifts the contents of array to have a zero mean.  nxdim specifies the X dimension of array, and nx and ny are the size of the data in array.

void meanzero(float *array, int *nxdim, int *nx, int *ny)

Fortran wrapper to XCorrMeanZero

void XCorrPeakFind(float *array, int nxdim, int ny, float *xpeak, float *ypeak, float *peak, int maxpeaks)

Finds the coordinates of the maxpeaks highest peaks in array, which is dimensioned to nxdim by ny, and returns the positions in xpeak, ypeak and the peak values in peak.  The X size of the image is assumed to be nxdim - 2.  The sub-pixel position is determined by fitting a parabola separately in X and Y to the peak and 2 adjacent points.  Positions are numbered from zero and coordinates bigger than half the image size are shifted to be negative.  The positions are thus the amount to shift a second image in a correlation to align it to the first.  If fewer than maxpeaks peaks are found, then the remaining values in peaks will be -1.e30.

void xcorrpeakfind(float *array, int *nxdim, int *ny, float *xpeak, float *ypeak, float *peak, int *maxpeaks)

Fortran wrapper to XCorrPeakFind.  If maxpeaks is 1, then xpeak, ypeak, and peak can be single variables instead of arrays.

double parabolicFitPosition(float y1, float y2, float y3)

Given values at three successive positions, y1, y2, and y3, where y2 is the peak value, this fits a parabola to the values and returns the offset of the peak from the center position, a number between -0.5 and 0.5.

double parabolicfitposition(float *y1, float *y2, float *y3)

Fortran wrapper to parabolicFitPosition

void conjugateProduct(float *array, float *brray, int nx, int ny)

Forms the product of complex numbers in array and the complex conjugate of numbers in brray and puts the result back in array, where the arrays are Fourier transforms of images with dimensions nx by ny.

void conjugateproduct(float *array, float *brray, int *nx, int *ny)

Fortran wrapper to conjugateProduct

double XCorrCCCoefficient(float *array, float *brray, int nxdim, int nx, int ny, float xpeak, float ypeak, int nxpad, int nypad, int *nsum)

Returns the cross-correlation coefficient between the images in array and brray at a shift between the images given by xpeak, ypeak.  The images have sizes nx by ny and the arrays have X dimension nxdim.  Areas on each size of nxpad in X and nypad in Y are excluded from the correlation.  Otherwise, the correlation will include all the pixels in the overlap between the images at the given shift.  The number of pixels will be returned in nsum.

double cccoefficient(float *array, float *brray, int *nxdim, int *nx, int *ny, float *xpeak, float *ypeak, int *nxpad, int *nypad, int *nsum)

Fortran wrapper to XCorrCCCoefficient.

Sobel Filter Function

int scaledSobel(float *inImage, int nxin, int nyin, float scaleFac, float minInterp, int linear, float center, float *outImage, int *nxout, int *nyout, float *xOffset, float *yOffset)

Applies a Sobel-type gradient filter to an image after scaling it by a specified amount.  When an image is being scaled down, some of the scaling can be done with binning and the remainder is done with interpolation.
  inImage - input image
  nxin, nyin - size of image, which is assumed to be contiguous in the image array (X dimension equals nxin.)
  scaleFac - overall amount by which image is being scaled down (a value < 1 will scale an image up).
  minInterp - minimum amount of this scaling to be done by interpolation.
  linear - set nonzero to use linear rather than cubic interpolation
  center - weighting of center pixel, 2 for Sobel or 1 for Prewitt filter
  outImage - output image
  nxout, nyout - returned with size of output image
  xOffset, yOffset - coordinate offset in output image:
     input_coord = output_coord * scalingFactor + xOffset
The return value is 1 for a failure to allocate a temporary array.  
If inImage is NULL or center < 0, the function will compute the output sizes and offsets and return.  
If center is 0, the scaled image is computed and returned without Sobel filtering.
The call from Fortran is the same as that from C.

Function for Image Transformation by Interpolation

void cubinterp(float *array, float *bray, int nxa, int nya, int nxb, int nyb, float amat[2][2], float xc, float yc, float xt, float yt, float scale, float dmean, int linear)

Applies a linear transformation to an image using cubic or linear interpolation.  It eliminates all range tests from the inner loop, but falls back from cubic to quadratic interpolation (which range tests) around the edges of the input image area.  
array - The input image array  
bray - The output image array  
nxa,nya - The dimensions of array  
nxb,nyb - The dimensions of bray  
amat - A 2x2 matrix to specify rotation, scaling, and skewing  
xc,yc - The coordinates of the center of array  
xt,yt - The translation to add to the final image. The center of the output array is taken as nxb / 2., nyb / 2.  
scale - A multiplicative scale factor for the intensities  
dmean - Mean intensity of image or other value with which to fill empty image area  
linear - Set non-zero to do linear interpolation  
The coordinate transformation from (Xi, Yi) in the input image to the (Xo, Yo) in the output image is given by:  
Xo = a11(Xi - Xc) + a12(Yi - Yc) + nxb/2. + xt  
Yo = a21(Xi - Xc) + a22(Yi - Yc) + nyb/2. + yt  
where Xi is a coordinate running from 0 at the left edge of the first pixel to nxa at the right edge of the last pixel in X, and similarly for Y.  
When calling from C, indices in amat are transposed: a11 = amat[0][0], a12 = amat[1][0], a21 = amat[0][1], a22 = amat[1][1]  
To call from Fortran, use arguments of the same type and in the same order. Indices in amat are in logical order: a11 = amat(1,1), a12 = amat(1,2), etc.  
This routine is now parallelized with OpenMP.  The allowed threads is proportional to the square root of output image area, falling to 1 at about 32x32.

Functions for Image Reduction with Filtering

int selectZoomFilter(int type, double zoom, int *outWidth)

Selects which filter to use in image reduction with type and sets the scaling factor with zoom, a value less that must be less than 1.  The type can be 0 for a box (equivalent to binning), 1 for a Blackman window, 2 for a triangle filter, 3 for a Mitchell filter, or 4 or 5 for Lanczos 2 or Lanczos 3.  The total width of the filter in the source image is returned in outWidth.  Returns 1 for a filter type out of range or 2 for a zoom out of range.

int selectzoomfilter(int *type, float *zoom, int *outWidth)

Fortran wrapper for selectZoomFilter

int zoomWithFilter(unsigned char **slines, int aXsize, int aYsize, float aXoff, float aYoff, int bXsize, int bYsize, int bXdim, int bXoff, int dtype, void *outData, b3dUInt32 *cindex, unsigned char *bindex)

Reduces an image using the interpolation filter and zoom specified in selectZoomFilter.
slines - array of line pointers for the input image
aXsize, aYsize - size of input image
aXoff, aYoff - coordinate in the input image at which the lower left pixel of the output starts
bXsize, bYsize - size output image to be created, potentially from a subset of the input in X or Y and into a subset of the output array
bXdim - X dimension of the full output image array
bXoff - Index of first pixel in X to fill in output array
dtype - Type of data, a SLICE_MODE_... value.  BYTE, FLOAT, RGB, and USHORT are allowed
outData - Output array, or address of first line to fill in a larger output array. The array is the same data type as the input unless mapping is being done, in which case it must be unsigned integers.
cindex - Unsigned integer RGBA values to map byte or short data into, or NULL for no mapping
bindex - Byte values to map RGB data into, or NULL for no mapping.  Each channel is mapped the same and a fourth channel is added with zero.
Returns 1 if no filter has been selected, 2 for an unsupported data type, 3 for an attempt to map float data, 4 if needed input coordinates to compose the output image go out of range, or 5 for a memory allocation error.
This function is parallelized with OpenMP and uses the same formula as cubinterp for reducing the number of threads for small images.

int zoomwithfilter(float *array, int *aXsize, int *aYsize, float *aXoff, float *aYoff, int *bXsize, int *bYsize, int *bXdim, int *bXoff, float *outData)

Fortran wrapper for zoomWithFilter

int zoomFiltInterp(float *array, float *bray, int nxa, int nya, int nxb, int nyb, float xc, float yc, float xt, float yt, float dmean)

Performs image reduction using zoomWithFilter and can be used the same way as cubinterp could be for scaling an image down and shifting it.  The zoom and filter must already be specified with selectZoomFilter .  
array - The input image array  
bray - The output image array  
nxa,nya - The dimensions of array  
nxb,nyb - The dimensions of bray  
xc,yc - The coordinates of the center of array  
xt,yt - The translation to add to the final image. The center of the output array is taken as nxb / 2., nyb / 2.  
dmean - Mean intensity of image or other value with which to fill empty image area  
Returns the same error values as zoomWithFilter

int zoomfiltinterp(float *array, float *bray, int *nxa, int *nya, int *nxb, int *nyb, float *xc, float *yc, float *xt, float *yt, float *dmean)

Fortran wrapper for zoomFiltInterp

Functions for Working with Linear Transformations

void xfUnit(float *f, float val, int rows)

Initializes transform f with a11 and a22 set equal to val; use 1.0 for a unit transform.

void xfCopy(float *f1, int rows1, float *f2, int rows2)

Copies transform f1 to f2, which have rows1 and rows2 rows, respectively.

void xfMult(float *f1, float *f2, float *prod, int rows)

Multiples transform f1 (the one applied first) by f2 (the one applied second) and places the result in prod, which can be the same as f1 or f2.

void xfInvert(float *f, float *finv, int rows)

Takes the inverse of transform f and returns the result in finv, which can be the same as f.

void xfApply(float *f, float xcen, float ycen, float x, float y, float *xp, float *yp, int rows)

Applies transform f to the point x, y, with the center of transformation at xcen, ycen, and returns the result in xp, yp, which can be the same as x, y.

Functions for Converting Linear Transformation

void amatToRotmagstr(float a11, float a12, float a21, float a22, float *theta, float *smag, float *str, float *phi)

Converts a 2 by 2 transformation matrix into four "natural" parameters of image transformation.  The transformation is specified by a11, a12, a21, and a22, where
   x' = a11 * x + a12 * y
   y' = a21 * x + a22 * y   
In the converted transformation, theta is overall rotation, smag is overall magnification, str is a unidirectional stretch, and phi is the angle of the stretch axis.  Two equivalent solutions are possible, with the stretch axis in the first or fourth quadrant.  The function returns the solution that makes the magnification smag nearer to 1.0.

void amat_to_rotmagstr(float *amat, float *theta, float *smag, float *str, float *phi)

Fortran wrapper to amatToRotmagstr, where amat is dimensioned (2,*) or otherwise has elements in the order a11, a21, a12, a22.

void rotmagstrToAmat(float theta, float smag, float str, float phi, float *a11, float *a12, float *a21, float *a22)

Obtains a 2 by 2 transformation from four parameters of image transformation: theta is overall rotation, smag is overall magnification, str is a unidirectional stretch, and phi is the angle of the stretch axis, where angles are in degrees.  The transformation is returned in a11, a12, a21, and a22.

void rotmagstr_to_amat(float *theta, float *smag, float *str, float *phi, float *amat)

Fortran wrapper to rotmagstrToAmat, where amat is dimensioned (2,*) or otherwise has elements in the order a11, a21, a12, a22.

Binning Function

int reduceByBinning(void *array, int type, int nxin, int nyin, int nbin, void *brray, int keepByte, int *nxr, int *nyr)

Reduces an array in size by summing pixels (binning) by the factor nbin. array has the input, with dimensions nxin by nyin, and slice mode in type.  The slice mode can be byte, short, unsigned short, float, or RGB. brray receives the output, with dimensions returned in nxr and nyr. The output will have the same mode as the input and will be the average of binned values, except in two cases.  If the input is bytes or RGB and keepByte is 0, then the output will be signed short integers and will be the sum, not the average, of the binned values, and for RGB data the output will be an equal sum of red, green, and blue values.  brray can be the same as array, and nxr, nyr can be the same variables as nxin, nyin.  The output size is obtained by integer division of the input size by the binning.  If the remainder of this division is nonzero, the data are centered in the output array as nearly as possible.  Specifically, the coordinates of the lower left corner of the output array are offset by
  ((nx % nbin) / 2, (ny % nbin) / 2)
relative to the input array.  Returns 1 for an unsupported data type.

void reduce_by_binning(float *array, int *nx, int *ny, int *nbin, float *brray, int *nxr, int *nyr)

Fortran wrapper for reduceByBinning, called as reduce_by_binning. Again, the output variables can safely be the same as the input variables.

Functions for Fitting Circles and Spheres

int circleThrough3Pts(float x1, float y1, float x2, float y2, float x3, float y3, float *rad, float *xc, float *yc)

Computes the radius rad and center (xc, yc) for a circle through the 3 given points (x1, y1), (x2, y2), and (x3, y3).  Returns 1 for error (square root of negative number).

int fitSphere(float *xpt, float *ypt, float *zpt, int numPts, float *rad, float *xcen, float *ycen, float *zcen, float *rmsErr)

Fit a circle or sphere to a set of points using a simplex search with the amoeba routine.
Inputs: X and Y coordinates in arrays xpt, ypt; zpt is NULL for a circle fit or has the array of Z coordinate; number of points in numPts.
Outputs: radius in rad, center coordinate in xcen, ycen, and zcen for a sphere fit, and RMS error in rmsErr.  Returns 0.

int fitSphereWgt(float *xpt, float *ypt, float *zpt, float *weights, int numPts, float *rad, float *xcen, float *ycen, float *zcen, float *rmsErr)

Fit a circle or sphere to a set of points with weighting of errors using a simplex search with the amoeba routine.
Inputs: X and Y coordinates in arrays xpt, ypt; zpt is NULL for a circle fit or has the array of Z coordinate; weights has an array of weights or is NULL for no weighting; the number of points is in numPts.
Outputs: radius in rad, center coordinate in xcen, ycen, and zcen for a sphere fit, and RMS error in rmsErr.  Returns 0.

Function to Test for Point Inside Boundary

int InsideContour(float *ptX, float *ptY, int np, float x, float y)

Returns 1 if the point x, y is inside or on the polygon (contour) whose vertices are in ptX, ptY, where np is the number of points, otherwise returns 0.

int insidecontour(float *ptX, float *ptY, int *np, float *x, float *y)

Fortran wrapper to InsideContour .  But it is more convenient to call
   logical function inside(ptX, ptY, np, x, y)

Function for Finding Convex Boundary

void convexBound(float *sx, float *syin, int npnts, float fracomit, float pad, float *bx, float *by, int *nvert, float *xcen, float *ycen, int maxverts)

Finds the smallest convex boundary around an arbitrary set of points in sx, sy.  npnts is the total number of points. If fracomit is nonzero, it omits that fraction of points from consideration completely, choosing the points that are farthest from the centroid of all the points.  (If fracomit is negative, the Y coordinates of the points will be temporarily scaled to have the same standard deviation as the X range in order to determine the farthest points; it then eliminates -fracomit points.) It returns the centroid of the points under consideration in xcen, ycen.  It returns the set of boundary points in bx, by and the number of points in nvert.  The size of bx and by is specified by maxverts.  If pad is nonzero, it makes the boundary points be that distance away from the outermost sx, sy points. It uses Graham's scan algorithm.  nvert is returned with -1 for an error allocating temporary arrays, or -2 for the boundary arrays not large enough.

void convexbound(float *sx, float *syin, int *npnts, float *fracomit, float *pad, float *bx, float *by, int *nvert, float *xcen, float *ycen, int *maxverts)

Fortran wrapper for convexBound

Function for Sorting Points onto Two Surfaces

int setSurfSortParam(int index, float value)

Sets one parameter for surfaceSort .

int setsurfsortparam(int *index, float *value)

Fortran wrapper for setSurfSortParam

int surfaceSort(float *xyz, int numPts, int *group)

Sorts a set of points in 3D onto two surfaces.  The X, Y, and Z coordinates of the numPts points are packed sequentially into the array xyz.  The surfaces number, 1 for the bottom one and 2 for the top one, are returned in group.  The return value is 1 for a memory allocation error.

int surfacesort(float *xyz, int *numPts, int *group)

Fortran wrapper for surfaceSort, where xyz is dimensioned to (3,*)

Parameters for surfaceSort

The numbers in the comments are index values for setSurfSortParam

/* Spacing of squares for sorting points and accessing rings of points */
static float gridSpacing = 50.; /* 0 */
/* Maximum neighbors to evalue for finding neighbor with steepest angle */
static int maxAngleNeigh = 50;  /* 1 */
/* Use pairs with angle more than this fraction of very steepest angle */
static float steepestRatio = 0.5f; /* 2 */
/* If there are fewer than this number of pairs, take pairs down to angleMax */
static int numMinForAmax = 10;  /* 3 */
/* Angle to go down to if steepestRatio doesn't give enough pairs */
static float angleMax = 20.;    /* 4 */
/* If fewer than this number of pairs, take pairs down to angelRelax */
static int numMinForArelax = 3; /* 5 */
/* Angle to go down to if angleMax doesn't give enough pairs */
static float angleRelax = 5.;   /* 6 */
/* Criterion for MAD-Median outlier elimination based on delta Z of a pair */
static float outlierCrit = 3.;  /* 7 */
/* Maximum distance to search for neighboring points in plane fits */
static float maxFitDist = 2048.; /* 8 */
/* Maximum number of points in plane fits */
static int maxNumFit = 15;      /* 9 */
/* Minimum # of points for fitting parallel planes */
static int biplaneMinFit = 5;   /* 10 */
/* Minimum # of points for fitting one plane */
static int planeMinFit = 4;     /* 11 */
/* Maximum % distance of Z value between nearest and other plane for deferring to 2nd round: values > 50 disable deferring points */
static float maxRound1Dist = 100.; /* 12 */
/* 1 for minimal output, 2 for exhaustive output */
static int debugLevel = 0;      /* 13 */

Function for Parsing Lists

int *parselist (const char *line, int *nlist)

Converts a list entry in the string line into a set of integers, returns a pointer to the list of numbers, and returns the number of values in nlist.  An example of a list is 1-5,7,9,11,15-20. Numbers separated by dashes are replaced by all of the numbers in the range.  Numbers need not be in any order, and backward ranges (10-5) are handled.  Any characters besides digits are valid separators.  A / at the beginning of the string will return an error.  Negative numbers can be entered provided that the minus sign immediately precedes the number.  E.g.: -3 - -1 or -3--1 will give -3,-2,-1; -3, -1,1 or -3,-1,1 will give -3,-1,1.

Simplex Search Functions

void amoeba(float *p, float *y, int mp, int ndim, float ftol, void (*funk)(float *, float *), int *iterP, float *ptol, int *iloP)

Performs a multidimensional search to minimize a function of ndim variables using the Nelder-Mead algorithm as elaborated by Lagarius et al. The function value is computed by funk, a void function of two variables: a float array containing the values of the ndim variables, and a pointer to a float for the function value. p is a 2-dimensional array dimensioned to at least one more than the number of variables in each dimension, and mp specifies its fastest dimension (second in C, first in fortran).  y is a one-dimensional array also dimensioned to at least one more than the number of variables. Both of these should be preloaded by calling amoebaInit. Termination is controlled by ftol, which is a limit for the fractional difference in function value between the lowest and highest point in the simplex, and the array ptol, which has limits for the difference of each variable; each component of each point must be within the respective limit of the value for the lowest point.  iterP is returned with the number of iterations; iloP is returned with the index of the minimum vector in p (p[i][iloP] in C, p(iloP, i) in fortran).
From fortran the subroutine is called as:
call amoeba(p, y, mp, ndim, ftol, funk, iter, ptol, ilo)
where funk is:
subroutine funk(a, value)

void amoebaInit(float *p, float *y, int mp, int ndim, float delfac, float ptolFac, float *a, float *da, void (*funk)(float *, float *), float *ptol)

Initializes the arrays p, y, and ptol before calling amoeba. a is an array with the initial values of the variable. da is an array with factors proportional to the magnitude of the components of a. The initial step size for each variable is set to delfac times da, while the termination tolerance for each variable is set to ptolFac times da.  Other variables are as just described.  From fortran it is called as:
call amoebaInit(p, y, mp, ndim, delfac, ptolFac, a, da, func, ptol)

Histogram Functions

void kernelHistogram(float *values, int numVals, float *bins, int numBins, float firstVal, float lastVal, float h, int verbose)

Computes a standard or kernel histogram from the numVals values in the array values.  The histogram is placed in the array bins, and occupies numBins between firstVal and lastVal. The kernel width is set by h, use 0 for a standard binned histogram. Set verbose to 1 for a list of values, or 2 for a list of bin values.

void kernelhistogram(float *values, int *numVals, float *bins, int *numBins, float *firstVal, float *lastVal, float *h, int *verbose)

Fortran wrapper for kernelHistogram

int scanHistogram(float *bins, int numBins, float firstVal, float lastVal, float scanBot, float scanTop, int findPeaks, float *dip, float *peakBelow, float *peakAbove)

Scans a histogram for peaks and a dip.  The histogram is in numBins elements of bins, extending from firstVal to lastVal.  It will be scanned between values scanBot and scanTop.  If findPeaks is nonzero, it will find the two highest peaks and return their values in peakBelow and peakAbove, then find the dip between them and returns its value in dip; otherwise it just scans the range for the lowest point and returns the value in dip.  The return value is 1 if it fails to find two peaks.

int scanhistogram(float *bins, int *numBins, float *firstVal, float *lastVal, float *scanBot, float *scanTop, int *findPeaks, float *dip, float *peakBelow, float *peakAbove)

Fortran wrapper for scanHistogram

int findHistogramDip(float *values, int numVals, int minGuess, float *bins, int numBins, float firstVal, float lastVal, float *histDip, float *peakBelow, float *peakAbove, int verbose)

Finds a histogram dip by starting with a high smoothing and dropping to a lower one.  
values - Array of values to form histogram from
numVals - Number of values in the array
bins - Array to build histogram in
numBins - Number of bins to divide histogram into
firstVal, lastVal - Starting and ending value for histogram range
minGuess - If non-zero, it specifies an estimate of the minimum number of items above the dip
verbose - Verbose output flag, passed to kernelHistogram histDip - Returned with the location of the dip
peakBelow, peakAbove - Returned with the peak values below and above the dip
The return value is 1 if a dip cannot be found after 4 trial H values.

int findhistogramdip(float *values, int *numVals, int *minGuess, float *bins, int *numBins, float *firstVal, float *lastVal, float *histDip, float *peakBelow, float *peakAbove, int *verbose)

Fortran wrapper for findHistogramDip

Functions for Analyzing Gold Beads

void makeModelBead(int boxSize, float beadSize, float *array)

Makes a model bead of radius beadSize in array with dimensions boxSize by boxSize.

double beadIntegral(float *array, int nxdim, int nx, int ny, float rCenter, float rInner, float rOuter, float xcen, float ycen, float *cenmean, float *annmean, float *temp, float annPct, float *median)

Finds integral above background of a bead located at xcen, ycen in array, an image nx by ny with X dimension nxdim.  rCenter, rInner, and rOuter are radii of the center and the inner and outer radii of the background annulus.  Returns the center and annular means in cenmean and annmean, and if annPct is supplied with a fractional percentile, returns the percentile value in median, using temp as a temporary array.  temp is not used if annPct is 0.  The return value is center minus annular mean.

Functions for Simple Statistics

void avgSD(float *x, int n, float *avg, float *sd, float *sem)

Calculates the mean avg, standard deviation sd, and standard error of mean sem, from the n values in array x.  Callable from Fortran by the same name.

void avgsd(float *x, int *n, float *avg, float *sd, float *sem)

Fortran wrapper for avgSD

void sumsToAvgSD(float sx, float sxsq, int n, float *avg, float *sd)

Computes a mean avg and standard deviation sd from the sum of values sx, sum of squares sxsq, and number of values n. It will not generate any division by 0 errors.  Callable from Fortran by the same name.

void sums_to_avgsd(float *sx, float *sxsq, int *n, float *avg, float *sd)

Fortran wrapper for sumsToAvgSD

void sumsToAvgSDdbl(double sx8, double sxsq8, int n1, int n2, float *avg, float *sd)

Computes a mean avg and standard deviation sd from the sum of values sx8, sum of squares sxsq8, and number of values n1 * n2, where the number of values can be greater than 2**31. It will not generate any division by 0 errors.

void sums_to_avgsd8(double *sx8, double *sxsq8, int *n1, int *n2, float *avg, float *sd)

Fortran wrapper for sumsToAvgSDdbl; use real*8 for sx8, sxsq8.

void lsFit(float *x, float *y, int num, float *slope, float *intcp, float *ro)

Fits a straight line to the n points in arrays x and y by the method of least squares, returning slope, intercept bint, correlation coeficient ro.

void lsfit(float *x, float *y, int *num, float *slope, float *intcp, float *ro)

Fortran wrapper for lsFit

void lsFitPred(float *x, float *y, int n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se, float xpred, float *ypred, float *prederr)

Fits a straight line to the n points in arrays x and y by the method of least squares, returning slope, intercept bint, correlation coeficient ro, standard errors of the estimate se, the slope sb, and the intercept sa, and for one X value xpred, it returns the predicted value ypred and the standard error of the prediction prederr.

void lsfitpred(float *x, float *y, int *n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se, float *xpred, float *ypred, float *prederr)

Fortran wrapper for lsFitPred

void lsfits(float *x, float *y, int *n, float *slope, float *bint, float *ro, float *sa, float *sb, float *se)

Fortran wrapper for lsFitPred that returns the standard errors and omits the prediction

void lsFit2(float *x1, float *x2, float *y, int n, float *a, float *b, float *c)

Does a linear regression fit of the n values in the array y to the values in the arrays x1 and x2, namely to the equation
   y = a * x1 + b * x2 + c   
It returns the coefficients a and c, and the intercept c. If c is NULL it fits instead to
   y = a * x1 + b * x2

void lsfit2(float *x1, float *x2, float *y, int *n, float *a, float *b, float *c)

Fortran wrapper for lsFit2

void lsfit2noc(float *x1, float *x2, float *y, int *n, float *a, float *b)

Fortran wrapper for calling lsFit2 with c NULL.

void lsFit2Pred(float *x1, float *x2, float *y, int n, float *a, float *b, float *c, float x1pred, float x2pred, float *ypred, float *prederr)

Does a linear regression fit of the n values in the array y to the values in the arrays x1 and x2, namely to the equation
   y = a * x1 + b * x2 + c   
It returns the coefficients a and b, and the intercept c, but if c is NULL it fits instead to
   y = a * x1 + b * x2   
For one value of x1 and x2 given by x1pred and x2pred, it returns the value predicted by the equation in ypred and the standard error of the prediction in prederr.

void lsfit2pred(float *x1, float *x2, float *y, int *n, float *a, float *b, float *c, float *x1pred, float *x2pred, float *ypred, float *prederr)

Fortran wrapper for lsFit2Pred

void lsFit3(float *x1, float *x2, float *x3, float *y, int n, float *a1, float *a2, float *a3, float *c)

Does a linear regression fit of the n values in the array y to the values in the arrays x1, x2, and x3, namely, to the equation
   y = a1 * x1 + a2 * x2 + a3 * x3 + c   
It returns the coefficients a1, a2, a3 and the intercept c.

void lsfit3(float *x1, float *x2, float *x3, float *y, int *n, float *a1, float *a2, float *a3, float *c)

Fortran wrapper for lsFit3

Functions for Sorting and Robust Statistics

void rsSortFloats(float *x, int n)

Uses qsort to sort the n floats in the array x.

void rssortfloats(float *x, int *n)

Fortran wrapper for rsSortFloats

void rsSortIndexedFloats(float *x, int *index, int n)

Uses qsort to sort indexes in index to the n floats in the array x.

void rssortindexedfloats(float *x, int *index, int *n)

Fortran wrapper for rsSortIndexedFloats

void rsMedianOfSorted(float *x, int n, float *median)

Computes the median of the n values in the array x, which has already been sorted, and returns the value in median.

void rsmedianofsorted(float *x, int *n, float *median)

Fortran wrapper for rsMedianOfSorted

void rsMedian(float *x, int n, float *xsort, float *median)

Computes the median of the n values in x.  The value is returned in median and xsort is used for sorting the array and returned with the sorted values.

void rsmedian(float *x, int *n, float *xsort, float *median)

Fortran wrapper for rsMedian

void rsMADN(float *x, int n, float median, float *tmp, float *MADN)

Computes the normalized median absolute deviation from the median for the n values in x, using the value already computed for the median in median.  The result is returned in MADN, and tmp is returned with sorted values of the absolute deviations.

void rsmadn(float *x, int *n, float *median, float *tmp, float *MADN)

Fortran wrapper for rsMADN

void rsMadMedianOutliers(float *x, int n, float kcrit, float *out)

Selects outliers among the n values in the array x by testing whether the absolute deviation from the median is greater than normalized median absolute deviation by the criterion kcrit.  out is used for temporary storage and is returned with -1 or 1 for outliers in the negative or positive direction from the median, 0 otherwise.

void rsmadmedianoutliers(float *x, int *n, float *kcrit, float *out)

Fortran wrapper for rsMadMedianOutliers

void rsTrimmedMeanOfSorted(float *x, int n, float gamma, float *trmean)

Computes a trimmed mean of the n already sorted values in x, trimming off the fraction gamma on each end of the distribution.  The value is returned in trmean.

void rstrimmedmeanofsorted(float *x, int *n, float *gamma, float *median)

Fortran wrapper for rsTrimmedMeanOfSorted

void rsTrimmedMean(float *x, int n, float gamma, float *xsort, float *trmean)

Computes a trimmed mean of the n values in x, trimming off the fraction gamma on each end of the distribution.  The value is returned in trmean and xsort is used for sorting the array and returned with the sorted values.

void rstrimmedmean(float *x, int *n, float *gamma, float *xsort, float *median)

Fortran wrapper for rsTrimmedMean

Functions for Finding a Percentile

float percentileFloat(int s, float *r, int num)

Selects item number s (numbered from 1) out of num items in the array r, where items are considered in order from low to high.  r is partially rearranged while finding the item.

int percentileInt(int s, int *r, int num)

Same as percentileFloat but with an integer array r

Functions for Statistics by Sampling

int sampleMeanSD(unsigned char **image, int type, int nx, int ny, float sample, int ixStart, int iyStart, int nxUse, int nyUse, float *mean, float *sd)

Estimates mean and SD of a sample of an image.  Returns nonzero for errors.
image = array of pointers to each line of data
type = data type, 0 for bytes, 2 for unsigned shorts, 3 for signed shorts, 6 for floats, 7 for 4-byte integers, 8 for RGB triples of bytes or 9 for RGBA bytes; RGB values are weighted with NTSC weighting
nx, ny = X and Y dimensions of image
sample = fraction of pixels to sample
ixStart, iyStart = starting X and Y index to include
nxUse, nyUse = number of pixels in X and Y to include
mean, sd = returned values of mean and sd

int samplemeansd(float *image, int *nx, int *ny, float *sample, int *ixStart, int *iyStart, int *nxUse, int *nyUse, float *mean, float *sd)

Fortran wrapper for sampleMeanSD with a floating point array in image

int percentileStretch(unsigned char **image, int type, int nx, int ny, float sample, int ixStart, int iyStart, int nxUse, int nyUse, float pctLo, float pctHi, float *scaleLo, float *scaleHi)

Estimates percentile limits for contrast strecthing an image by building a histogram of a sample.
image = line pointers to image
mode = data type, a SLICE_MODE_ value; BYTE, USHORT, SHORT, or FLOAT are allowed
nx, ny = X and Y dimensions of image
sample = fraction of pixels to sample
ixStart, iyStart = starting X and Y coordinates to sample
nxUse, nyUse = extent of image to sample in X and Y
pctLo, pctHi = Percentile levels to find on the low and high end of range (1.0 is 1%)
scaleLo, scaleHi = returned values of those percentile levels
Returns 1 for inadequate number of pixels, 2 for invalid mode, or 3 for memory error.

Statistical Functions

double tValue(double signif, int ndf)

Returns the t-value that gives the significance level signif with the number of degrees of freedom ndf, where signif should be between 0.5 and 1.0.

double dtvalue(double *signif, int *ndf)

Fortran wrapper for tValue

double fValue(double signif, int ndf1, int ndf2)

Returns the F-value that gives the cumulative probability value signif with the number of degrees of freedom ndf1 and ndf2.

double dfvalue(double *signif, int *ndf1, int *ndf2)

Fortran wrapper for fValue

double errFunc(double x)

Returns the value of the error function erf() at x.

double errfunc(double *x)

Fortran wrapper for errFunc

double incompBeta(double a, double b, double x)

Computes and returns the incomplete beta function of x for parameters a and b, for 0 <= x <= 1, and a > 0 and b > 0.

double incompbeta(double *a, double *b, double *x)

Fortran wrapper for incompBeta

double betaFunc(double p, double q)

Computes and returns the beta function of p and q, which must be > 0.

double lnGamma(double x)

Computes and returns the natural log of the gamma function of x, which should not equal 0, -1, -2, etc.

Gauss-Jordan Function for Solving Linear Equations

int gaussj(float *a, int n, int np, float *b, int m, int mp)

Solves the linear matrix equation A X = B by Gauss-Jordan elimination. A is a square matrix of size n by n in array a, dimensioned to np columns.  B is a matrix with one row per row of A and m columns in array b, dimensioned to mp columns.  The columns of b are replaced by the m solution vectors while a is reduced to a unit matrix.  It is called the same from C and Fortran, but the matrices must be in row-major order in both cases.  Specifically, in C, the matrices are indexed as Arowcolumn and in Fortran they are indexed as A(column,row).
The maximum value of n is 2000 but better and faster approaches should be used long before reaching that point.  The routine returns -1 if n exceeds this value and 1 if the A matrix is singular.

Sparse Matrix Functions to Use with Lsqr

void sparseProd(int mode, int m, int n, double x[], double y[], void *UsrWrk)

Compute products in a sparse matrix for lsqr.  The matrix has m data rows times n columns, one for each variable  
If mode = 1, compute  y = y + A*x.  
If mode = 2, compute  x = x + A(transpose)*y.  
UsrWrk is loaded as follows:  
Offset to JA values, the column number of each data value (from 1)
Offset to RW values, the data values themselves  
IA values: the starting index of each row.  Numbered from 1  

void addValueToRow(float val, int icol, float *valRow, int *icolRow, int *numInRow)

Adds one value val and its data column icol to arrays valRow and icolRow for the current row, and maintains the number of values in numInRow.

void addvaluetorow(float *val, int *icol, float *valRow, int *icolRow, int *numInRow)

Fortran wrapper for addValueToRow

int addRowToMatrix(float *valRow, int *icolRow, int numInRow, float *rwrk, int *ia, int *ja, int *numRows, int maxRows, int maxVals)

Adds one data row to a sparse matrix.  Values are in valRow, column numbers (numbered from 1) in icolRow, number of values in numInRow. rwrk is the sparse matrix array of data values, ja is the corresponding array of column numbers, ia is an array of starting indexes into those arrays for each row (indexes numbered from 1).  The number of rows is maintained in numRows, and maxRows and maxVals are the maximum number of rows and values allowed.

int addrowtomatrix(float *valRow, int *icolRow, int *numInRow, float *rwrk, int *ia, int *ja, int *numRows, int *maxRows, int *maxVals)

Fortran wrapper for addRowToMatrix

void normalizeColumns(float *rwrk, int *ia, int *ja, int numVars, int numRows, float *sumEntries)

Normalizes each column of data in the sparse matrix by dividing it by the square root of the sum of squares of values in that column, as recommended for running lsqr.  rwrk, ja, and ia are as described for addRowToMatrix; numVars is the number of variables (columns) and numRows is the number of rows.  The normalizing factor for each column is returned in sumEntries.  The solution vector obtained from normalized data needs to be divided by sumEntries.

void normalizecolumns(float *rwrk, int *ia, int *ja, int *numVars, int *numRows, float *sumEntries)

Fortran wrapper for normalizeColumns

Functions for Working with Montage Piece Lists

int checkPieceList(int *pclist, int stride, int npclist, int redfac, int nframe, int *minpiece, int *npieces, int *noverlap)

Examines a list of npclist piece coordinates in pclist for one dimension (x or y) at a spacing of stride between successive values, applies a reduction factor redfac, and given the frame size nframe, it finds the minimum coordinate minpiece, the # of pieces npieces, and the overlap noverlap. It also checks that ALL coordinates on the list are multiples of frame size minus overlap.  Upon failure, it returns the line number at which that  check fails, and also return -1 in npieces.

void checklist(int *pclist, int *npclist, int *redfac, int *nframe, int *minpiece, int *npieces, int *noverlap)

Fortran wrapper for checkPieceList which assumes the stride is 1.  Upon error, it prints a message, and still returns -1 in npieces.

void adjustPieceOverlap(int *pclist, int stride, int npclist, int nframe, int minpiece, int noverlap, int newOverlap)

Adjusts a list of npclist piece coordinates in pclist for one dimension (x or y), at a spacing of stride between successive values, changing the overlap from noverlap to newOverlap, given the frame size nframe and the minimum coordinate minpiece (which is retained).

void adjustpieceoverlap(int *pclist, int *npclist, int *nframe, int *minpiece, int *noverlap, int *newOverlap)

Fortran wrapper for adjustPieceOverlap that assumes a stride of 1.

Function for Finding Best Shift of Montage Pieces

int findPieceShifts (int *ivarpc, int nvar, int *indvar, int *ixpclist, int *iypclist, float *dxedge, float *dyedge, int idir, int *pieceLower, int *pieceUpper, int *ifskipEdge, int edgeStep, float *dxyvar, int varStep, int *edgeLower, int *edgeUpper, int pcStep, int *work, int fort, int leaveInd, int skipCrit, float robustCrit, float critMaxMove, float critMoveDiff, int maxIter, int numAvgForTest, int intervalForTest, int *numIter, float *wErrMean, float *wErrMax)

Solves for positions of overlapping pieces by adjusting them iteratively to minimize the difference between measured displacement between pairs of pieces and the difference in their positions.
ivarpc: index from included variables (pieces) to overall piece number
nvar: Number of variables
indvar: index from piece number to variable number; must be set to less than the minimum variable number (0 for C, 1 for Fortran) for all pieces potentially connected to the ones included as variables.
ixpclist, iypclist: X and Y piece coordinates.
dxedge, dyedge: the measured difference from the nominal displacement between pieces at an edge
idir: 1 if those values are the amount that the upper piece is displaced from being in register with the lower; -1 if they are the amount that the upper piece needs to be shifted to be in register.
pieceLower, pieceUpper: index of pieces below and above an edge
ifskipEdge: A number indicating whether the edge should be skipped
edgeStep: Stride between X and Y edges at the same edge index in the edge arrays dxedge, dyedge, pieceLower, pieceUpper, ifskipEdge.  If the arrays are accessed in Fortran as array(edge,ixy), then this value is the first dimension of the array.  If they are accessed in C as arrayedgeixy or array2*edge+ixy then the value is 1.
dxyvar: array into which the piece shifts in X and Y are returned for each piece in the variable list
varStep: Stride between X and Y shifts for a given piece in dxyvar; as for edgeStep, this is either 1 or the long dimension of the array.
edgeLower, edgeUpper: edge index of edge below or edge above a given piece in X or Y.
pcStep: Stride between X and Y edges at the same piece in those arrays; again, this is either 1 or the long dimension of the array
work: Array for temporary storage, must be at least 20.25 times the number of variables plus 1.
fort: A nonzero value indicates that the indexes in ivarpc, indvar, pieceLower, pieceUpper, edgeLower, edgeUpper are numbered from 1 instead 0.
leaveInd: Absolute edge index in edge arrays of edge to leave out
skipCrit: An edge is skipped if ifskipEdge is >= this value
critMaxMove: Terminate if the maximum move of any piece in X or Y is less than this criterion.
robustCrit: Use robust fitting to eliminate or down-weight outlying edge displacements; multiply outlier criterion by given factor.
critMoveDiff: Terminate if the average move changes by less than this amount between samples
maxIter: Maximum number of iterations
numAvgForTest: Number of iterations over which to average the average  
moves in X and Y for the test based on critMoveDiff  
intervalForTest: Number of iterations between such tests  
numIter is returned with the number of iteratation.
wErrMean and wErrMax are returned with the mean and maximum of weighted errors.
Returns 1 if the strides are not all 1 or all different from 1.
Called from Fortran with identical arguments and name.

C Functions for Safe Parallel Writing to File

int parWrtInitialize(char *filename, int nxin, int nyin)

Initialize parallel writing to an image file by reading in the boundary info file whose name is filename, and storing various values in static variables. filename can be NULL or an empty string, in which case the count of parallel writing files is incremented and this info file index is marked as having no info file.  nxin and nyin * specify the dimensions of the images.  The format of the info file is to start with a line with these entries:
Version  type  nx  numLines  numFiles  
version = 1 for now  
type = 0 for chunks in Z, 1 for chunks in Y that require boundaries on each section  
nx = X dimension of image file  
numLines = number of lines written at each boundary  
numFiles = number of boundary files  
For each boundary file, there are then two lines:  
Name of boundary file  
Boundary 1 section and starting line, boundary 2 section and starting line
Sections and lines are numbered from 0.  For chunks in Z, the section number should be -1 for no boundary (i.e., for boundary 1 of first chunk and boundary 2 of last chunk).  A line number of -1 indicates that the boundary extends to the end of the section (thus, a setup script does not need to know the size of the images in Y).  This routine will convert a line number of -1 to the appropriate starting line.  
For chunks in Y, the section number is ignored (and should be -1) and the line number should be -1 for no boundary. Returns 1 for failure to open file, 2 for error reading file, 3 for inappropriate values in header line of file, 4 for memory allocation errors, or 5 for trying to open too many boundary info files for the array.

int parwrtinitializefw(char *filename, int *nxin, int *nyin, int strlen)

Simple Fortran wrapper for parWrtInitialize, called by the Fortran parWrtInitialize funtion.

int parWrtProperties(int *allSec, int *linesBound, int *nfiles)

Returns properties read from the current boundary info file: allSec 1 if chunks are in Y, linesBound with the number of lines in each boundary, nfiles with the number of boundary files. These values are all zero if there was no boundary info file at the current index.  Returns 1 for parallel writing not initialized.

int parwrtproperties(int *allSec, int *linesBound, int *nfiles)

Fortran wrapper for parWrtProperties.

int parWrtSetCurrent(int index)

Sets the index of the current boundary info file to index, numbered from 0.  Returns 1 for index out of range.

int parwrtsetcurrentfw(int *index)

Fortran wrapper for parWrtSetCurrent, with index numbered from 1.

int parWrtFindRegion(int secNum, int lineNum, int nlWrite, char **filename, int *sections, int *startLines)

Finds the parallel writing region that contains nlWrite lines starting with line lineNum on section secNum and returns the boundary file in filename, and the section and starting line of the first and second boundaries in arrays sections and startLines.  Returns 1 if parallel writing not initialized, or 2 if the region is not found.

int parwrtfindregion(int *secNum, int *lineNum, int *nlWrite, char *filename, int *sections, int *startLines, int strlen)

Fortran wrapper for parWrtFindRegion

int parwrtgetregion(int *regionNum, char *filename, int *sections, int *startLines, int strlen)

Fortran-callable function to get the parameters of parallel writing region number regionNum (numbered from 1) and return the boundary file in filename and the sections and starting lines in arrays sections and startLines.  Returns 2 if writing not initialized, or 1 if the region number is out of bounds.

Color Map Functions

int *cmapStandardRamp()

Returns a pointer to the color ramp specification for the standard false color table used in 3dmod.

int *cmapInvertedRamp()

Returns a pointer to a color ramp specification for an false color table inverted from the one used in 3dmod.

int cmapConvertRamp(int *rampData, unsigned char table[3][256])

Converts a color ramp specification in rampData to a full 256-color table in table.  The first value in the rampData array is the number of color specifications; each set of 4 numbers after that is a red, green, and blue value (range 0-255) and a relative position along the color table.

int cmapReadConvert(char *filename, unsigned char table[3][256])

Reads a color map specification from the file specified by filename and converts it to a complete color table in table.  The file starts with the number of lines of color data.  If there are 256 lines they must be red, green, blue triplets (range 0-255); otherwise each line has a red, green, and blue followed by a relative position in the color table. Returns 1 for error opening a file, 2 for errors reading the file, 3 for an invalid number of lines, or 4 for a memory allocation error.

Standard color ramps

The standard color ramp specification used in 3dmod
static int standardRampData[] =
  { 
    15,
    255,    0,  255,  -616,
    179,    0,  255,  -569,
    120,   40,  255,  -528,
    60,   96,  255,  -469,
    0,  175,  177,  -400,
    0,  191,  143,  -383,
    0,  207,   78,  -361,
    90,  255,   60,  -305,
    191,  255,    0,  -259,
    239,  255,    0,  -240,
    255,  255,    0,  -229,
    255,  175,    0,  -162,
    255,  105,    0,   -83,
    255,   45,   55,   -20,
    255,    0,   90,    0,
  };

/* An inverted color ramp specification, used in model view for mesh normals */
static int invertedRampData[] =
  { 
    15,
    255,    0,   90,    0,
    255,   45,   55,   20,
    255,  105,    0,   83,
    255,  175,    0,  162,
    255,  255,    0,  229,
    239,  255,    0,  240,
    191,  255,    0,  259,
    90,  255,   60,  305,
    0,  207,   78,  361,
    0,  191,  143,  383,
    0,  175,  177,  400,
    60,   96,  255,  469,
    120,   40,  255,  528,
    179,    0,  255,  569,
    255,    0,  255,  616,
  };