Search is not available for this dataset
text
string
meta
dict
/* gcPresAbs.c - Calculate probability of expression in an mrna sample given a cel file of results. Use empiracal rank within a gc population to estimate probability and fisher's method of combining probabilities to calculate probe set probability. */ #include "common.h" #include "hash.h" #include "linefile.h" #include "obscure.h" #include "options.h" #include "dystring.h" #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> struct row1lq /* A single row from a affymetrix 1lq file. Also used for storing values and probability of expression. */ { struct row1lq *next; /* Next in list. */ char *psName; /* Name of probe set.*/ char *seq; /* Sequence of probe, in weird affy format. */ int x; /* X coordinate from affy cel file. */ int y; /* Y coordinate from affy cel file. */ int gcCount; /* Number of g's and c's in sequence. */ int repCount; /* Number of experiments we're looking at. */ double *intensity; /* Intensities for each experiment. */ double *pVal; /* Pvals for each experiment. */ }; struct psProb /* Probability that a probe set is expressed. */ { struct psProb *next; /* Next in list. */ char psName[128]; /* Name of probe set. */ double pVal; /* P-Value of expression. */ }; struct replicateMap /* Map the replicates to eachother. */ { struct replicateMap *next; /* Next in list. */ char *rootName; /* Root name of replicates. */ int repCount; /* Number of replicates. */ int *repIndexes; /* Indexes into matrix columns. */ }; struct row1lq **gcBins = NULL; /* Bins of lists of row1lqs for different amounts of GCs. */ struct row1lq *badBin = NULL; struct hash *probeSetHash = NULL; /* Hash of slRefs for each probe set where slRef->val is a row1lq. */ struct hash *killHash = NULL; /* Hash of probes to be ignored. */ struct hash *outputValsHash= NULL; /* Hash of probe sets to output values for. */ FILE *outputPsSetSeqs = NULL; /* Output probe sets and sequences used here. */ FILE *outputIntenVals = NULL; /* File to output intensity for individual values to. */ FILE *outputPvals = NULL; /* File to output pvals for individual to. */ int minGcBin = 0; /* Minimum GC bin. */ int maxGcBin = 0; /* Maximum GC bin. */ struct psProb *probePVals = NULL; /* List of psProbe structs with pVals filled in. */ int minProbeNum = 3; /* Ignore probe sets that have less than this many probes. */ char *placeHolder = "dummy"; /* Hold a place in a hash. */ boolean combineCols = FALSE; /* Combine columns that are the same samples? */ int repToSort = 0; /* What replicate to sort the gc bins by. */ int maxReplicates = 0; /* What are the maximum number of replicates. */ int sampleCount = 0; /* Number of samples. */ int numBadProbes = 0; /* Number of bad probes counted. */ FILE *gCountsFile = NULL; /* File to output 'G' counts per probe to. */ FILE *gcCountFile = NULL; /* File to output 'G' + 'C' counts per probe to. */ FILE *cCountsFile = NULL; /* File to output 'C' counts per probe. */ boolean doMedianComb = FALSE; /* Do a median rather than Fisher's combination. */ boolean doCombo = FALSE; /* Do a combination of median and fisher. */ static struct optionSpec optionSpecs[] = /* Our acceptable options to be called with. */ { {"help", OPTION_BOOLEAN}, {"1lqFile", OPTION_STRING}, {"outFile", OPTION_STRING}, {"badProbes", OPTION_STRING}, {"combineReplicates", OPTION_BOOLEAN}, {"outputDuplicates", OPTION_BOOLEAN}, {"testVals", OPTION_BOOLEAN}, {"countPrefix", OPTION_STRING}, {"doMedianComb", OPTION_BOOLEAN}, {"testMedian", OPTION_BOOLEAN}, {"doCombo", OPTION_BOOLEAN}, {"outputVals", OPTION_STRING}, {"outputValsList", OPTION_STRING}, {"outputPsSetSeqs", OPTION_STRING}, {NULL,0} }; static char *optionDescripts[] = /* Description of our options for usage summary. */ { "Display this message.", "1lq file from affymetrix specifying probe layout on chip", "File to output matrix of probabilities to.", "File with sequence of probes that are known to be bad and should be ignored.", "Combine experiments with same name prefix.", "When used with combineReplicates, outputs a column for each tissue that has same prefix.", "Skip everything else and just run inverse chisq on each value degreeFreedom pair on command line.", "Output G/C probe countent counts to prefixCounts.tab", "Use median rather than Fisher's combination", "Test the median code.", "Do a combination of medians and fischer's combination.", "Output the intensity and probability to file with this prefix.", "Only output probe sets in this list.", "Output probe sets and sequences in 5'->3' orientation" }; void usage() /** Print usage and quit. */ { int i=0; warn("gcPresAbs - Calculate probability of expression in an mrna\n" "sample given a cel file of results. Use empiracal rank within\n" "a gc population to estimate probability and fisher's method\n" "of combining probabilities to calculate probe set probability."); for(i=0; i<ArraySize(optionSpecs) -1; i++) fprintf(stderr, " -%s -- %s\n", optionSpecs[i].name, optionDescripts[i]); errAbort("\nusage:\n " "gcPresAbs -1lqFile=chipmousea.1lq -outFile=probeSet.matrix.probs file1.cel file2.cel ... fileN.cel"); } int psCmp(const void *va, const void *vb) /* Compare based on probeSet name. */ { const struct psProb *a = *((struct psProb **)va); const struct psProb *b = *((struct psProb **)vb); return strcmp(a->psName, b->psName); } int row1lqCmp(const void *va, const void *vb) /* Compare to sort based on intensity for the given repliate. */ { const struct row1lq *a = *((struct row1lq **)va); const struct row1lq *b = *((struct row1lq **)vb); double bI = b->intensity[repToSort]; double aI = a->intensity[repToSort]; if(aI < bI) return 1; if(aI > bI) return -1; return 0; } int countGc(char *sequence) /* Count the numbers of G's+C's in the sequence. */ { int gCount = 0, cCount =0; tolowers(sequence); gCount = countChars(sequence, 'g'); if(gCountsFile) fprintf(gCountsFile, "%d\n", gCount); cCount = countChars(sequence, 'c'); if(cCountsFile) fprintf(cCountsFile, "%d\n", cCount); if(gcCountFile) fprintf(gcCountFile, "%d\n", cCount + gCount); return cCount + gCount; } void initGcBins(int minGc, int maxGc) /* Intialize the gcBins structure for maxGc-minGc bins. */ { int numBins = maxGc - minGc + 1; minGcBin = minGc; maxGcBin = maxGc; AllocArray(gcBins, numBins); } int binForGc(int gcCount) /* Return the correct bin for this gc count. */ { int count = 0; if(gcCount < minGcBin) gcCount = minGcBin; if(gcCount > maxGcBin) gcCount = maxGcBin; return gcCount - minGcBin; } void readBadProbes(char *fileName) /* Read in a list that contains bad probes sequence should be in first row. */ { struct lineFile *lf = NULL; char *line = NULL; killHash = newHash(15); lf = lineFileOpen(fileName, TRUE); while(lineFileNextReal(lf, &line)) { tolowers(line); hashAdd(killHash, line, placeHolder); } lineFileClose(&lf); } void read1lqFile(char *name, struct row1lq ***pRowArray, int *pRowCount) /* Read in the 1lq popluating the gcBins and hasing by probe set name. Need to index rows by a few different ways: 1) Index in file, for filling in intensity vals from cel files. 2) Gc Bin for calculating the rank within a set of probes that have same gc content. 3) Probe set for calculating the probability that the probe set as a whole is expressed. */ { struct lineFile *lf = lineFileOpen(name, TRUE); struct row1lq **array1lq = NULL; struct row1lq *rowList = NULL, *row=NULL, *rowNext = NULL; int i; char *words[50]; char *line = NULL; int count =0; boolean found = FALSE; struct slRef *refList = NULL, *ref = NULL; while(lineFileNextReal(lf, &line)) { if(stringIn("X\tY\t", line)) { found = TRUE; break; } } if(!found) errAbort("Couldn't find \"X\tY\t\" in 1lq file: %s", name); while(lineFileChopNextTab(lf, words, sizeof(words))) { AllocVar(row); row->psName = cloneString(words[5]); row->seq = cloneString(words[2]); row->x = atoi(words[0]); row->y = atoi(words[1]); slAddHead(&rowList, row); (*pRowCount)++; } slReverse(&rowList); AllocArray(array1lq, (*pRowCount)); probeSetHash = newHash(15); for(row = rowList; row != NULL; row = rowNext) { int bin = -1; struct slRef *ref = NULL, *reflist = NULL; rowNext = row->next; /* Keep track of the row by its index in the file. */ array1lq[count++] = row; /* Skip things that are on the kill list. */ tolowers(row->seq); if(sameString(row->seq, "!") || (killHash != NULL && hashFindVal(killHash, row->seq) != NULL)) { slAddHead(&badBin, row); numBadProbes++; continue; } /* Add it to the correct gc bin. */ row->gcCount = countGc(row->seq); bin = binForGc(row->gcCount); slAddHead(&gcBins[bin], row); /* Create a list of references indexed by the probe sets. */ AllocVar(ref); ref->val = row; refList = hashFindVal(probeSetHash, row->psName); if(refList == NULL) hashAddUnique(probeSetHash, row->psName, ref); else slAddTail(&refList, ref); } for(i = minGcBin; i < maxGcBin; i++) slReverse(&gcBins[i-minGcBin]); //lineFileClose(&lf); *pRowArray = array1lq; } void fillInMatrix(double **matrix, int celIx, int rowCount, char *celFile) /* Read in the values of the cel file into matrix column celIx. */ { struct lineFile *lf = lineFileOpen(celFile, TRUE); char *words[50]; char *line = NULL; boolean found = FALSE; int count =0; /* Read out the header. */ while(lineFileNextReal(lf, &line)) { if(stringIn("[INTENSITY]", line)) { found = TRUE; break; } } if(!found) errAbort("Couldn't find \"[INTENSITY]\" in cel file: %s", celFile); count =0; lineFileNextReal(lf, &line); /* NumberCells... */ lineFileNextReal(lf, &line); /* CellHeader...*/ /* Read in the data. */ while(lineFileChopNext(lf, words, sizeof(words))) { if(*(words[0]) == '[') break; assert(count+1 <= rowCount); matrix[count][celIx] = atof(words[2]); count++; if(lf->bytesInBuf == 0) warn("Something weird is happening..."); } //warn("Closing line file."); lineFileClose(&lf); } int xy2i(int x, int y) /* Take in the x,y coordinates on the array and return the index into the array. */ { return (712 * y) + x; } int doubleComp(const void *a, const void *b) /* Return difference to sort on doubles. */ { double x = (*(double *)a); double y = (*(double *)b); if(x > y) return 1; else if(y > x) return -1; else return 0; } /* double quantileArray(double *array, int count, double quantile) */ /* /\* give the quantile at a given position of the array. *\/ */ /* { */ /* double *results = NULL; */ /* boolean isEven = FALSE; */ /* int i = 0; */ /* double quant = 0; */ /* assert(count); */ /* assert(quantile >=0 && quantile <=1); */ /* AllocArray(results, count); */ /* if(floor(count * quantile) == ceil(count *quantile)) */ /* isEven = TRUE; */ /* if(isEven && (count % 2 != 0)) */ /* errAbort("Wrong even for quantile %.2f with count %d", quantile, count); */ /* if(!isEven && (count % 2 == 0)) */ /* errAbort("Wrong odd for quantile %.2f with count %d", quantile, count); */ /* for(i = 0; i < count; i++) */ /* results[i] = array[i]; */ /* qsort(results, count, sizeof(results[0]), doubleComp); */ /* if(isEven) */ /* quant = (results[(int)floor(count * quantile)-1] + results[(int)floor(count*quantile)])/2; */ /* else */ /* quant = results[(int)floor(count * quantile)]; */ /* freez(&results); */ /* return quant; */ /* } */ /* double medianArray(double *array, int count) */ /* /\* Give the median, or a quantile of an array. *\/ */ /* { */ /* return quantileArray(array, count, quantile); */ /* } */ double medianArray(double *array, int count) /* give the median of the array. */ { double *results = NULL; boolean isEven = FALSE; int i = 0; double median = 0; assert(count); AllocArray(results, count); if(count % 2 == 0) isEven = TRUE; for(i = 0; i < count; i++) results[i] = array[i]; qsort(results, count, sizeof(results[0]), doubleComp); if(isEven) median = (results[count/2-1] + results[count/2])/2; else median = results[count/2]; freez(&results); return median; } void printDoubleArray(double *array, int count) /* Print the elements of a double array. */ { int i = 0; for(i = 0; i<count; i++) printf("%.3f, ", array[i]); printf("\n"); } double medianRefList(struct slRef *refList) /** Return the median value of the row list. */ { struct slRef *ref = NULL; struct row1lq *row = NULL; int count = 0, currentIx = 0; boolean isEven = FALSE; double median = 0; double *results = NULL; int repIx = 0; /* How much memory do we need? */ for(ref = refList; ref != NULL; ref = ref->next) { row = ref->val; count += row->repCount; } assert(count > 0); AllocArray(results, count); /* Fill in the values. */ for(ref = refList; ref != NULL; ref = ref->next) { row = ref->val; for(repIx = 0; repIx < row->repCount; repIx++) { results[currentIx++] = row->pVal[repIx]; } } /* Get the median. */ median = medianArray(results, count); freez(&results); return 1 - median; } void probeSetCalcPval(void *val) /* Loop through the slRef list calculating pVal based on row1lq->pval using fishers method for combining probabilities. Create a psProbe val and add it to the probePVals list. */ { struct slRef *ref = NULL, *refList = NULL; struct psProb *ps = NULL; struct row1lq *row = NULL; boolean debug = FALSE; double probProduct = 0; int probeCount = 0; int probRepCount = 0; int i = 0, j = 0; refList = val; probeCount = slCount(refList); if(outputPsSetSeqs != NULL) { assert(refList); row = refList->val; fprintf(outputPsSetSeqs, "%s\t", row->psName); for(ref = refList; ref != NULL; ref = ref->next) { row = ref->val; reverseBytes(row->seq, strlen(row->seq)); if(ref->next != NULL) fprintf(outputPsSetSeqs, "%s,", row->seq); else fprintf(outputPsSetSeqs, "%s", row->seq); reverseBytes(row->seq, strlen(row->seq)); } fprintf(outputPsSetSeqs, "\n"); } /* Allocate some memory. */ AllocVar(ps); row = refList->val; ps->pVal = 0; safef(ps->psName, sizeof(ps->psName), "%s", row->psName); if(probeCount < minProbeNum) { ps->pVal=0; } else if(doMedianComb) { ps->pVal = medianRefList(refList); } else { for(ref = refList; ref != NULL; ref = ref->next) { row = ref->val; if(doCombo) { double med = medianArray(row->pVal, row->repCount); if(med == 0) med = .00000000001; probRepCount++; probProduct += log(med); } else { for(i = 0; i < row->repCount; i++) { probRepCount++; if(row->pVal[i] != 0) probProduct = probProduct + log(row->pVal[i]); else probProduct = probProduct + log(.000000001); } } } /* Fisher's method for combining probabilities. */ ps->pVal = gsl_cdf_chisq_P(-2*probProduct,2*probRepCount); } if(ps->pVal > 1 || ps->pVal < 0) warn("%s pVal is %.10f, wrong!"); slAddHead(&probePVals, ps); } doInvChiSq(int argc, char *argv[]) /* Test routine to make sure that gsl_cdf_chisq_P() is working correctly. */ { int i = 0; double result = 0; for(i = 1; i < argc; i+=2) { result = gsl_cdf_chisq_P(atof(argv[i]), atoi(argv[i+1])); printf("%s\t%s\t%.2f\n", argv[i], argv[i+1], result); } } void printIntensities(struct row1lq *rowList, int limit) /* Loop through and print out the row intensity for a list. */ { struct row1lq *row = NULL; int count = 0; if(limit == -1) limit = slCount(rowList); for(row = rowList; count < limit && row != NULL; row = row->next) { fprintf(stdout, "%.1f\n", row->intensity[repToSort]); count++; } } void fillInProbeSetPvals(double **matrix, int rowCount, int colCount, int repCount, int *repIndexes, int sampleIx, struct row1lq **row1lqArray, double ***probeSetPValsP, char ***probeSetNamesP, int *psCountP, double **probMatrix) /* Calculate and fill in the probe set probabilities of expression given the data in the matrix. */ { int i = 0, j = 0; int rank = 0; int binCount = 0; struct psProb *probe = NULL; struct row1lq *row = NULL; int psCount = 0; /* Fill in the values for the rows. */ for(i = 0; i < rowCount; i++) { row1lqArray[i]->repCount = repCount; for(j = 0; j < repCount; j++) { row1lqArray[i]->intensity[j] = matrix[i][repIndexes[j]]; } } /* Sort the gc bins by their rank and fill in the pVals as an empiracal rank. */ for(i = minGcBin; i <= maxGcBin; i++) { /* Sort for each replicate. */ for(j = 0; j < repCount; j++) { rank = 1; repToSort = j; slSort(&gcBins[i-minGcBin], row1lqCmp); binCount = slCount(gcBins[i-minGcBin]); for(row = gcBins[i-minGcBin]; row != NULL; row = row->next) { row->pVal[j] = ((double)rank)/binCount; probMatrix[xy2i(row->x, row->y)][repIndexes[j]] = row->pVal[j]; rank++; } } } /* Do the bad bin. */ for(row = badBin; row != NULL; row = row->next) { for(j = 0; j < repCount; j++) { row->pVal[j] = 0; } } hashTraverseVals(probeSetHash, probeSetCalcPval); if(outputPsSetSeqs == NULL) carefulClose(&outputPsSetSeqs); slSort(&probePVals, psCmp); psCount = slCount(probePVals); /* If this is the first time through Allocate some memory. */ if(*probeSetPValsP == NULL) { (*psCountP) = psCount; AllocArray((*probeSetNamesP), psCount); AllocArray((*probeSetPValsP), psCount); for(i = 0; i < psCount; i++) { AllocArray((*probeSetPValsP)[i], sampleCount); } i = 0; for(probe = probePVals; probe != NULL; probe = probe->next) { (*probeSetNamesP)[i++] = cloneString(probe->psName); } } i = 0; for(probe = probePVals; probe != NULL; probe = probe->next) { (*probeSetPValsP)[i++][sampleIx] = probe->pVal; } slFreeList(&probePVals); } struct replicateMap *createReplicateMap(char **expNames, int expCount) /* Group replicates together if required or just make a replicate for each one if no replicates are required. */ { struct replicateMap *rMapList = NULL, *rMap = NULL; int i = 0, j = 0; boolean combineReplicates = optionExists("combineReplicates"); boolean *used = NULL; char expBuff[256], nameBuff[256]; char *mark = NULL; /* If we're combining results look for expNames that have the same root (string before first ".") */ if(combineReplicates) { AllocArray(used, expCount); for(i = 0; i < expCount; i++) { /* If we haven't seen this experiment before start a new replicateMap. */ if(!used[i]) { safef(nameBuff, sizeof(nameBuff), "%s", expNames[i]); mark = strchr(nameBuff, '.'); if(mark != NULL) *mark = '\0'; AllocVar(rMap); used[i] = TRUE; rMap->rootName = cloneString(nameBuff); rMap->repCount = 1; AllocArray(rMap->repIndexes, expCount); rMap->repIndexes[0] = i; /* Loop through the experiments finding the ones that are replicates. */ for(j = i+1; j < expCount; j++) { safef(nameBuff, sizeof(nameBuff), "%s", expNames[j]); mark = strchr(nameBuff, '.'); if(mark != NULL) *mark = '\0'; if(sameString(nameBuff, rMap->rootName)) { used[j] = TRUE; rMap->repIndexes[rMap->repCount++] = j; } } maxReplicates = max(maxReplicates, rMap->repCount); slAddHead(&rMapList, rMap); } } } else /* Make each expName a new replicate. */ { for(i = 0; i < expCount; i++) { AllocVar(rMap); rMap->rootName = cloneString(expNames[i]); rMap->repCount = 1; AllocArray(rMap->repIndexes, rMap->repCount); rMap->repIndexes[0] = i; maxReplicates = max(maxReplicates, rMap->repCount); slAddHead(&rMapList, rMap); } } slReverse(&rMapList); /* Do a summmary of the replicates... */ /* for(rMap = rMapList; rMap != NULL; rMap = rMap->next) */ /* { */ /* printf("%s\t", rMap->rootName); */ /* for(i = 0; i < rMap->repCount; i++) */ /* { */ /* printf("%s,", expNames[rMap->repIndexes[i]]); */ /* } */ /* printf("\n"); */ /* } */ return rMapList; } boolean reportThisPSet(char *name) /* Return TRUE if thes pset should be outputed for intensity and pvals. */ { if(outputValsHash == NULL) return TRUE; return hashLookup(outputValsHash, name) != NULL; } void outputPvalValues(struct row1lq **row1lqArray, double **probMatrix, char **expNames, int rowCount, int colCount) /* Write out the pvals of the probe sets over all the tissues. */ { int rowIx = 0, colIx = 0; struct row1lq *row = NULL; assert(outputPvals); /* Print column headers. */ fprintf(outputPvals, "%s\t", "probeSetName"); for(colIx = 0; colIx < colCount-1; colIx++) fprintf(outputPvals, "%s\t", expNames[colIx]); fprintf(outputPvals , "%s\n", expNames[colIx]); /* Print all the data. */ for(rowIx = 0; rowIx < rowCount; rowIx++) { row = row1lqArray[rowIx]; if(reportThisPSet(row->psName)) { fprintf(outputPvals,"%d\t%s",rowIx, row->psName); for(colIx = 0; colIx < colCount; colIx++) { fprintf(outputPvals, "\t%.5f", probMatrix[rowIx][colIx]); } fputc('\n', outputPvals); } } } void outputValues(double **matrix, struct row1lq **row1lqArray, char **expNames, int rowCount, int colCount) /* Write out the intensity values for each probe. */ { int rowIx = 0, colIx = 0; struct row1lq *row = NULL; assert(outputIntenVals); fprintf(outputIntenVals, "%s\t", "probeSetName"); for(colIx = 0; colIx < colCount-1; colIx++) fprintf(outputIntenVals, "%s\t", expNames[colIx]); fprintf(outputIntenVals, "%s\n", expNames[colIx]); for(rowIx = 0; rowIx < rowCount; rowIx++) { row = row1lqArray[rowIx]; if(reportThisPSet(row->psName)) { assert(rowIx == xy2i(row->x, row->y)); fprintf(outputIntenVals, "%d\t%s", rowIx, row->psName); /* fprintf(outputIntenVals, "%s\t%s\t%d\t%d\t%d\t%d", row->psName, row->seq, row->x, row->y, rowIx, xy2i(row->x, row->y)); */ for(colIx = 0; colIx < colCount; colIx++) fprintf(outputIntenVals, "\t%.1f", matrix[rowIx][colIx]); fputc('\n', outputIntenVals); } } } void gcPresAbs(char *outFile, char *file1lq, int celCount, char *celFiles[]) /* Output all of the probe sets and their pvals for expression as calculated from the intensities in the cel files. */ { struct row1lq **rowArray = NULL, *row=NULL; char **expNames = NULL, **expOutNames = NULL; double **matrix = NULL, **probMatrix = NULL; double **probeSetPVals = NULL; /* Matrix of pVals of expression with probe sets ordered altphabetically. */ char **probeSetNames = NULL; /* List of probe set names indexing the probeSetPVals matrix. */ char *badProbeName = NULL; /* Name of file with bad probes. */ int psCount = 0; int i=0, j=0, k=0; int rowCount=0; FILE *out = NULL; struct replicateMap *rMapList = NULL, *rMap = NULL; boolean outputDuplicates = optionExists("outputDuplicates"); dotForUserInit(1); initGcBins(8,17); /* Determined by where most of the data lives... On the altmousea chip the data drops of significantly before 8 (15,732 3% <= 8) and after 18 (9636 2% >=18) */ /* See if we have a kill list. */ badProbeName = optionVal("badProbes", NULL); if(badProbeName != NULL) { warn("Reading the kill list"); readBadProbes(badProbeName); } /* Read in a 1lq file and put it in an array, lists and hash all at the same time. */ warn("Reading 1lq file: %s", file1lq); read1lqFile(file1lq, &rowArray, &rowCount); /* Lets initialize some memory. */ AllocArray(expNames, celCount); AllocArray(expOutNames, celCount); AllocArray(matrix, rowCount); AllocArray(probMatrix, rowCount); for(i=0; i<rowCount; i++) { AllocArray(matrix[i], celCount); AllocArray(probMatrix[i], celCount); } /* Read in the cel files. */ for(i=0; i<celCount; i++) { char *lastSlash = NULL; dotForUser(); expNames[i] = cloneString(celFiles[i]); lastSlash = strrchr(expNames[i], '/'); if(lastSlash != NULL) expNames[i] = lastSlash+1; fillInMatrix(matrix, i, rowCount, celFiles[i]); } if(optionExists("outputVals")) outputValues(matrix, rowArray, expNames, rowCount, celCount); rMapList = createReplicateMap(expNames, celCount); sampleCount = slCount(rMapList); /* Allocate enough memory for the maximum number of replicates. */ for(i = 0; i < rowCount; i++) { AllocArray(rowArray[i]->intensity, maxReplicates); AllocArray(rowArray[i]->pVal, maxReplicates); } warn("Calculating pVals"); //for(i=0; i<celCount; i++) i = 0; for(rMap = rMapList; rMap != NULL; rMap = rMap->next) { dotForUser(); for(j = 0; j < rMap->repCount; j++) expOutNames[i+j] = cloneString(expNames[rMap->repIndexes[j]]); fillInProbeSetPvals(matrix, rowCount, celCount, rMap->repCount, rMap->repIndexes, i++, rowArray, &probeSetPVals, &probeSetNames, &psCount, probMatrix); } if(optionExists("outputVals")) outputPvalValues(rowArray, probMatrix, expOutNames, rowCount, celCount); warn("Done."); warn("Found %d bad probes.", numBadProbes); warn("Writing out the results."); out = mustOpen(outFile, "w"); if(outputDuplicates) { /* Output each name, this only works if duplicates are next to each other. */ for(rMap = rMapList; rMap->next != NULL; rMap = rMap->next) { for(i = 0; i < rMap->repCount; i++) fprintf(out, "%s\t", expNames[rMap->repIndexes[i]]); } for(i = 0; i < rMap->repCount - 1; i++) fprintf(out, "%s\t", expNames[rMap->repIndexes[i]]); fprintf(out, "%s\n", expNames[rMap->repIndexes[i]]); for(i = 0; i < psCount; i++) { fprintf(out, "%s\t", probeSetNames[i]); for(j = 0; j < sampleCount; j++) { /* Output a column for each repetition. */ rMap = slElementFromIx(rMapList, j); for(k = 0; k < rMap->repCount -1; k++) fprintf(out, "%.5g\t", probeSetPVals[i][j]); /* If this is the last repetion then print the newline otherwise continue with tabs. */ if(j == sampleCount -1) fprintf(out, "%.5g\n", probeSetPVals[i][j]); else fprintf(out, "%.5g\t", probeSetPVals[i][j]); } } } else /* Only print one column per rMap. */ { for(rMap = rMapList; rMap->next != NULL; rMap = rMap->next) fprintf(out, "%s\t", rMap->rootName); fprintf(out, "%s\n", rMap->rootName); for(i = 0; i < psCount; i++) { fprintf(out, "%s\t", probeSetNames[i]); for(j = 0; j < sampleCount -1; j++) fprintf(out, "%.5g\t", probeSetPVals[i][j]); fprintf(out, "%.5g\n", probeSetPVals[i][j]); } } carefulClose(&out); warn("Done"); } void initCountFiles(char *prefix) /* open files for probe counts. */ { struct dyString *dy = newDyString(1024); dyStringClear(dy); dyStringPrintf(dy, "%s.gcCounts.tab", prefix); gcCountFile = mustOpen(dy->string, "w"); dyStringClear(dy); dyStringPrintf(dy, "%s.gCounts.tab", prefix); gCountsFile = mustOpen(dy->string, "w"); dyStringClear(dy); dyStringPrintf(dy, "%s.cCounts.tab", prefix); cCountsFile = mustOpen(dy->string, "w"); dyStringFree(&dy); } void closeCountFiles() /* Close the counting file handles. */ { carefulClose(&gcCountFile); carefulClose(&gCountsFile); carefulClose(&cCountsFile); } void setupTestRow(struct slRef **refList, double *array, int count) /* Create a test row and add it to the list. */ { int i = 0; struct row1lq *row = NULL; struct slRef *ref = NULL; AllocVar(row); row->repCount = count; AllocArray(row->pVal, row->repCount); for(i = 0; i < count; i++) row->pVal[i] = array[i]; AllocVar(ref); ref->val = row; slAddHead(refList, ref); } boolean sameDoubles(double a, double b) /* return TRUE if two doubles are the same to 6 significant digits. */ { char buffA[256]; char buffB[256]; safef(buffA, sizeof(buffA), "%.6f", a); safef(buffB, sizeof(buffB), "%.6f", b); return sameString(buffA, buffB); } void testMedian() /* Quick testing of the median function. */ { struct slRef *refList = NULL; int count = 0, i = 0; double first[] = {.7, .8, .9, .6, .5}; double second[] = {.8, .7, .6}; double third[] = {.6, .5}; double median = 0; /* set up the first guy. */ setupTestRow(&refList, first, ArraySize(first)); median = medianRefList(refList); if(!sameDoubles(median, .3)) errAbort("Median should be .3, but it isn't."); setupTestRow(&refList, second, ArraySize(second)); median = medianRefList(refList); if(!sameDoubles(median, .3)) errAbort("Median should still be .3, but it isn't."); setupTestRow(&refList, third, ArraySize(third)); median = medianRefList(refList); if(!sameDoubles(median, .35)) errAbort("Median should be .7, but it isn't."); warn("Passed all median tests."); exit(0); } void initOutputValsList() /* Read in the output vals list from the file and inititalize the outputValsHash. */ { struct lineFile *lf = NULL; char *s = NULL; char *fileName = optionVal("outputValsList", NULL); assert(fileName); lf = lineFileOpen(fileName, TRUE); outputValsHash = newHash(10); while(lineFileNextReal(lf, &s)) hashAdd(outputValsHash, s, NULL); lineFileClose(&lf); } void initOutputVals() /* Open two files for writing the probe level intensities and probabilities to. */ { struct dyString *s = newDyString(512); char *filePrefix = optionVal("outputVals", NULL); assert(filePrefix); dyStringPrintf(s, "%s.inten", filePrefix); outputIntenVals = mustOpen(s->string, "w"); dyStringClear(s); dyStringPrintf(s, "%s.pvals", filePrefix); outputPvals = mustOpen(s->string, "w"); dyStringFree(&s); } int main(int argc, char *argv[]) /* Everybodys favorite function. */ { char *affy1lqName = NULL; char *outFileName = NULL; int origCount = argc; optionInit(&argc, argv, optionSpecs); if(optionExists("testMedian")) testMedian(); if(optionExists("help") || origCount < 3) usage(); if(optionExists("countPrefix")) initCountFiles(optionVal("countPrefix", NULL)); if(optionExists("doMedianComb")) doMedianComb = TRUE; if(optionExists("doCombo")) doCombo = TRUE; if(optionExists("outputValsList")) initOutputValsList(); if(optionExists("outputVals")) initOutputVals(); if(optionExists("outputPsSetSeqs")) outputPsSetSeqs = mustOpen(optionVal("outputPsSetSeqs", NULL), "w"); affy1lqName = optionVal("1lqFile", NULL); outFileName = optionVal("outFile", NULL); if(optionExists("testVals")) doInvChiSq(argc, argv); else if(affy1lqName == NULL || outFileName == NULL) errAbort("Need to specify 1lqFile and outFile, use -help for usage."); else gcPresAbs(outFileName, affy1lqName, argc-1, argv+1); if(optionExists("countPrefix")) closeCountFiles(); return 0; }
{ "alphanum_fraction": 0.6440090674, "avg_line_length": 28.9681050657, "ext": "c", "hexsha": "0023e53c356f1d5305e94418e85dc49bf472a03d", "lang": "C", "max_forks_count": 80, "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z", "max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andypohl/kent", "max_forks_repo_path": "src/hg/altSplice/affySplice/gcPresAbs.c", "max_issues_count": 60, "max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andypohl/kent", "max_issues_repo_path": "src/hg/altSplice/affySplice/gcPresAbs.c", "max_line_length": 126, "max_stars_count": 171, "max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andypohl/kent", "max_stars_repo_path": "src/hg/altSplice/affySplice/gcPresAbs.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z", "num_tokens": 9208, "size": 30880 }
/*----------------------------------------------------------------------------*/ /* */ /* quad_golden.c */ /* */ /* Copyright (C) 2007 James Howse */ /* Copyright (C) 2009 Brian Gough */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 3 of the License, or (at */ /* your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, but */ /* WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, */ /* Boston, MA 02110-1301, USA. */ /* */ /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ /* */ /* This algorithm performs univariate minimization (i.e., line search). */ /* It requires only objective function values g(x) to compute the minimum. */ /* The algorithm maintains an interval of uncertainty [a,b] and a point x */ /* in the interval [a,b] such that a < x < b, and g(a) > g(x) and */ /* g(x) < g(b). The algorithm also maintains the three points with the */ /* smallest objective values x, v and w such that g(x) < g(v) < g(w). The */ /* algorithm terminates when max( x - a, b - x ) < 2(r |x| + t) where r */ /* and t are small positive reals. At a given iteration, the algorithm */ /* first fits a quadratic through the three points (x, g(x)), (v, g(v)) */ /* and (w, g(w)) and computes the location of the minimum u of the */ /* resulting quadratic. If u is in the interval [a,b] then g(u) is */ /* computed. If u is not in the interval [a,b], and either v < x and */ /* w < x, or v > x and w > x (i.e., the quadratic is extrapolating), then */ /* a point u' is computed using a safeguarding procedure and g(u') is */ /* computed. If u is not in the interval [a,b], and the quadratic is not */ /* extrapolating, then a point u'' is computed using approximate golden */ /* section and g(u'') is computed. After evaluating g() at the */ /* appropriate new point, a, b, x, v, and w are updated and the next */ /* iteration is performed. The algorithm is based on work presented in */ /* the following references. */ /* */ /* Algorithms for Minimization without derivatives */ /* Richard Brent */ /* Prentice-Hall Inc., Englewood Cliffs, NJ, 1973 */ /* */ /* Safeguarded Steplength Algorithms for Optimization using Descent Methods */ /* Philip E. Gill and Walter Murray */ /* Division of Numerical Analysis and Computing */ /* National Physical Laboratory, Teddington, United Kingdom */ /* NPL Report NAC 37, August 1974 */ /* */ /*----------------------------------------------------------------------------*/ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_min.h> #include "min.h" #define REL_ERR_VAL 1.0e-06 #define ABS_ERR_VAL 1.0e-10 #define GOLDEN_MEAN 0.3819660112501052 /* (3 - sqrt(5))/2 */ #define GOLDEN_RATIO 1.6180339887498950 /* (1 + sqrt(5))/2 */ #define DEBUG_PRINTF(x) /* do nothing */ typedef struct { double step_size, stored_step, prev_stored_step; double x_prev_small, f_prev_small, x_small, f_small; unsigned int num_iter; } quad_golden_state_t; static int quad_golden_init (void *vstate, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper) { quad_golden_state_t *state = (quad_golden_state_t *) vstate; /* For the original behavior, the first value for x_minimum_minimum passed in by the user should be a golden section step but we don't enforce this here. */ state->x_prev_small = x_minimum; state->x_small = x_minimum; state->f_prev_small = f_minimum; state->f_small = f_minimum; state->step_size = 0.0; state->stored_step = 0.0; state->prev_stored_step = 0.0; state->num_iter = 0; x_lower = 0 ; /* avoid warnings about unused variables */ x_upper = 0 ; f_lower = 0 ; f_upper = 0 ; f = 0; return GSL_SUCCESS; } static int quad_golden_iterate (void *vstate, gsl_function * f, double *x_minimum, double *f_minimum, double *x_lower, double *f_lower, double *x_upper, double *f_upper) { quad_golden_state_t *state = (quad_golden_state_t *) vstate; const double x_m = *x_minimum; const double f_m = *f_minimum; const double x_l = *x_lower; const double x_u = *x_upper; const double x_small = state->x_small; const double f_small = state->f_small; const double x_prev_small = state->x_prev_small; const double f_prev_small = state->f_prev_small; double stored_step = state->stored_step; /* update on exit */ double prev_stored_step = state->prev_stored_step; /* update on exit */ double step_size = state->step_size; /* update on exit */ double quad_step_size = prev_stored_step; double x_trial; double x_eval, f_eval; double x_midpoint = 0.5 * (x_l + x_u); double tol = REL_ERR_VAL * fabs (x_m) + ABS_ERR_VAL; /* total error tolerance */ if (fabs (stored_step) - tol > -2.0 * GSL_DBL_EPSILON) { /* Fit quadratic */ double c3 = (x_m - x_small) * (f_m - f_prev_small); double c2 = (x_m - x_prev_small) * (f_m - f_small); double c1 = (x_m - x_prev_small) * c2 - (x_m - x_small) * c3; c2 = 2.0 * (c2 - c3); if (fabs (c2) > GSL_DBL_EPSILON) /* if( c2 != 0 ) */ { if (c2 > 0.0) c1 = -c1; c2 = fabs (c2); quad_step_size = c1 / c2; } else { /* Handle case where c2 ~=~ 0 */ /* Insure that the line search will NOT take a quadratic interpolation step in this iteration */ quad_step_size = stored_step; } prev_stored_step = stored_step; stored_step = step_size; } x_trial = x_m + quad_step_size; if (fabs (quad_step_size) < fabs (0.5 * prev_stored_step) && x_trial > x_l && x_trial < x_u) { /* Take quadratic interpolation step */ step_size = quad_step_size; /* Do not evaluate function too close to x_l or x_u */ if ((x_trial - x_l) < 2.0 * tol || (x_u - x_trial) < 2.0 * tol) { step_size = (x_midpoint >= x_m ? +1.0 : -1.0) * fabs(tol); } DEBUG_PRINTF(("quadratic step: %g\n", step_size)); } else if ((x_small != x_prev_small && x_small < x_m && x_prev_small < x_m) || (x_small != x_prev_small && x_small > x_m && x_prev_small > x_m)) { /* Take safeguarded function comparison step */ double outside_interval, inside_interval; if (x_small < x_m) { outside_interval = x_l - x_m; inside_interval = x_u - x_m; } else { outside_interval = x_u - x_m; inside_interval = x_l - x_m; } if (fabs (inside_interval) <= tol) { /* Swap inside and outside intervals */ double tmp = outside_interval; outside_interval = inside_interval; inside_interval = tmp; } { double step = inside_interval; double scale_factor; if (fabs (outside_interval) < fabs (inside_interval)) { scale_factor = 0.5 * sqrt (-outside_interval / inside_interval); } else { scale_factor = (5.0 / 11.0) * (0.1 - inside_interval / outside_interval); } state->stored_step = step; step_size = scale_factor * step; } DEBUG_PRINTF(("safeguard step: %g\n", step_size)); } else { /* Take golden section step */ double step; if (x_m < x_midpoint) { step = x_u - x_m; } else { step = x_l - x_m; } state->stored_step = step; step_size = GOLDEN_MEAN * step; DEBUG_PRINTF(("golden step: %g\n", step_size)); } /* Do not evaluate function too close to x_minimum */ if (fabs (step_size) > tol) { x_eval = x_m + step_size; } else { x_eval = x_m + (step_size >= 0 ? +1.0 : -1.0) * fabs(tol); } /* Evaluate function at the new point x_eval */ SAFE_FUNC_CALL(f, x_eval, &f_eval); /* Update {x,f}_lower, {x,f}_upper, {x,f}_prev_small, {x,f}_small, and {x,f}_minimum */ if (f_eval <= f_m) { if (x_eval < x_m) { *x_upper = x_m; *f_upper = f_m; } else { *x_lower = x_m; *f_upper = f_m; } state->x_prev_small = x_small; state->f_prev_small = f_small; state->x_small = x_m; state->f_small = f_m; *x_minimum = x_eval; *f_minimum = f_eval; } else { if (x_eval < x_m) { *x_lower = x_eval; *f_lower = f_eval; } else { *x_upper = x_eval; *f_upper = f_eval; } if (f_eval <= f_small || fabs (x_small - x_m) < 2.0 * GSL_DBL_EPSILON) { state->x_prev_small = x_small; state->f_prev_small = f_small; state->x_small = x_eval; state->f_small = f_eval; } else if (f_eval <= f_prev_small || fabs (x_prev_small - x_m) < 2.0 * GSL_DBL_EPSILON || fabs (x_prev_small - x_small) < 2.0 * GSL_DBL_EPSILON) { state->x_prev_small = x_eval; state->f_prev_small = f_eval; } } /* Update stored values for next iteration */ state->stored_step = stored_step; state->prev_stored_step = prev_stored_step; state->step_size = step_size; state->num_iter++; DEBUG_PRINTF(("[%d] Final State: %g %g %g\n", state->num_iter, x_l, x_m, x_u)); return GSL_SUCCESS; } static const gsl_min_fminimizer_type quad_golden_type = { "quad-golden", /* name */ sizeof (quad_golden_state_t), &quad_golden_init, &quad_golden_iterate }; const gsl_min_fminimizer_type *gsl_min_fminimizer_quad_golden = &quad_golden_type;
{ "alphanum_fraction": 0.530114271, "avg_line_length": 33.8343023256, "ext": "c", "hexsha": "c078bd66e48110c4c5e9d1ad304c18ce7b58f7f6", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/min/quad_golden.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/min/quad_golden.c", "max_line_length": 94, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/min/quad_golden.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2915, "size": 11639 }
/* matrix/gsl_matrix_ushort.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_USHORT_H__ #define __GSL_MATRIX_USHORT_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_ushort.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; unsigned short * data; gsl_block_ushort * block; int owner; } gsl_matrix_ushort; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_view; typedef _gsl_matrix_ushort_view gsl_matrix_ushort_view; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_const_view; typedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view; /* Allocation */ GSL_EXPORT gsl_matrix_ushort * gsl_matrix_ushort_alloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_ushort * gsl_matrix_ushort_calloc (const size_t n1, const size_t n2); GSL_EXPORT gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_EXPORT gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_EXPORT gsl_vector_ushort * gsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m, const size_t i); GSL_EXPORT gsl_vector_ushort * gsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m, const size_t j); GSL_EXPORT void gsl_matrix_ushort_free (gsl_matrix_ushort * m); /* Views */ GSL_EXPORT _gsl_matrix_ushort_view gsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_ushort_view gsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i); GSL_EXPORT _gsl_vector_ushort_view gsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j); GSL_EXPORT _gsl_vector_ushort_view gsl_matrix_ushort_diagonal (gsl_matrix_ushort * m); GSL_EXPORT _gsl_vector_ushort_view gsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k); GSL_EXPORT _gsl_vector_ushort_view gsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k); GSL_EXPORT _gsl_matrix_ushort_view gsl_matrix_ushort_view_array (unsigned short * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ushort_view gsl_matrix_ushort_view_array_with_tda (unsigned short * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector (gsl_vector_ushort * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_EXPORT _gsl_vector_ushort_const_view gsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, const size_t i); GSL_EXPORT _gsl_vector_ushort_const_view gsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, const size_t j); GSL_EXPORT _gsl_vector_ushort_const_view gsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m); GSL_EXPORT _gsl_vector_ushort_const_view gsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, const size_t k); GSL_EXPORT _gsl_vector_ushort_const_view gsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, const size_t k); GSL_EXPORT _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array (const unsigned short * base, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, const size_t n1, const size_t n2, const size_t tda); GSL_EXPORT _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v, const size_t n1, const size_t n2); GSL_EXPORT _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_EXPORT unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x); GSL_EXPORT unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m); GSL_EXPORT void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m); GSL_EXPORT void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x); GSL_EXPORT int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ; GSL_EXPORT int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ; GSL_EXPORT int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m); GSL_EXPORT int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format); GSL_EXPORT int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); GSL_EXPORT int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2); GSL_EXPORT int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_EXPORT int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m); GSL_EXPORT int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); GSL_EXPORT unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m); GSL_EXPORT unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m); GSL_EXPORT void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out); GSL_EXPORT void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax); GSL_EXPORT void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin); GSL_EXPORT void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_EXPORT int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m); GSL_EXPORT int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_EXPORT int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_EXPORT int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_EXPORT int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_EXPORT int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x); GSL_EXPORT int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x); GSL_EXPORT int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_EXPORT int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i); GSL_EXPORT int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j); GSL_EXPORT int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v); GSL_EXPORT int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v); /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (unsigned short *) (m->data + (i * m->tda + j)) ; } extern inline const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const unsigned short *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_USHORT_H__ */
{ "alphanum_fraction": 0.687646468, "avg_line_length": 34.833819242, "ext": "h", "hexsha": "196baed5147fb946d9af5895fbba5895552e75df", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_ushort.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2987, "size": 11948 }
#define MPICH_SKIP_MPICXX 1 #define OMPI_SKIP_MPICXX 1 #include <Python.h> #include <petsc.h> #include "libpetsc4py/libpetsc4py.c"
{ "alphanum_fraction": 0.7938931298, "avg_line_length": 21.8333333333, "ext": "c", "hexsha": "d422b210b15e360e962e1958225d6282c407ffab", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_path": "src/libpetsc4py.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_path": "src/libpetsc4py.c", "max_line_length": 36, "max_stars_count": null, "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_path": "src/libpetsc4py.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 45, "size": 131 }
// // Created by pedram pakseresht on 2/18/21. // static char help[] = "Simple Petsc program"; #include <petsc.h> #include "incompressibleFlow.h" #include "mesh.h" #include "particleInertial.h" #include "particles.h" #include "particleInitializer.h" #include "petscviewer.h" static PetscErrorCode uniform_u(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) { //PetscInt d; //for (d = 0; d < Dim; ++d) // u[d] = 1.0; //return 0; if (X[1]==1.0){ u[0] = 1.0; } else { u[0] = 0.0; } u[1] =0.0; // u[0] = X[1] - X[1]*X[1] ; // u[1] = 0.0; return 0; } static PetscErrorCode uniform_u_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 0.0; u[1] = 0.0; return 0; } static PetscErrorCode uniform_p(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *p, void *ctx) { p[0] = 0.0; return 0; } static PetscErrorCode uniform_T(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) { T[0] = 0.0; return 0; } static PetscErrorCode uniform_T_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) { T[0] = 0.0; return 0; } static PetscErrorCode SetInitialConditions(TS ts, Vec u) { PetscErrorCode (*initFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx) = {uniform_u,uniform_p,uniform_T}; // u here is the solution vector including velocity, temperature and pressure fields. DM dm; PetscReal t; PetscErrorCode ierr; PetscFunctionBegin; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = TSGetTime(ts, &t); CHKERRQ(ierr); ierr = DMProjectFunction(dm, 0.0, initFuncs, NULL, INSERT_ALL_VALUES, u); CHKERRQ(ierr); // get the flow to apply the completeFlowInitialization method ierr = IncompressibleFlow_CompleteFlowInitialization(dm, u); CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode MonitorFlowAndParticleError(TS ts, PetscInt step, PetscReal crtime, Vec u, void *ctx) { // PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); // void *ctxs[3]; DM dm; PetscDS ds; Vec v; PetscReal ferrors[3]; PetscInt f; PetscErrorCode ierr; PetscInt num; PetscFunctionBeginUser; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = DMGetDS(dm, &ds); CHKERRQ(ierr); // get the particle data from the context ParticleData particlesData = (ParticleData)ctx; PetscInt particleCount; ierr = DMSwarmGetSize(particlesData->dm, &particleCount); CHKERRABORT(PETSC_COMM_WORLD, ierr); // compute the average particle location const PetscReal *coords; PetscInt dims; PetscReal avg[3] = {0.0, 0.0, 0.0}; ierr = DMSwarmGetField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords); CHKERRABORT(PETSC_COMM_WORLD, ierr); for (PetscInt p = 0; p < particleCount; p++) { for (PetscInt n = 0; n < dims; n++) { avg[n] += coords[p * dims + n] / particleCount; // PetscReal } } ierr = DMSwarmRestoreField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Timestep: %04d time = %-8.4g \t L_2 Error: [%2.3g, %2.3g, %2.3g] ParticleCount: %d\n", (int)step, (double)crtime, (double)ferrors[0], (double)ferrors[1], (double)ferrors[2], particleCount, (double)avg[0], (double)avg[1]); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Avg Particle Location: [%2.3g, %2.3g, %2.3g]\n", (double)avg[0], (double)avg[1], (double)avg[2]); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = VecViewFromOptions(u, NULL, "-vec_view"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = VecView(u, NULL);CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = PetscPrintf(PETSC_COMM_WORLD, "current time=%g\n", crtime);CHKERRQ(ierr); ierr = DMSetOutputSequenceNumber(particlesData->dm, step, crtime); CHKERRABORT(PETSC_COMM_WORLD, ierr); /* if (step == 0 ){ ierr = VecViewFromOptions(u, NULL, "-vec_init"); CHKERRABORT(PETSC_COMM_WORLD, ierr); } else { ierr = VecViewFromOptions(u, NULL, "-vec_view"); CHKERRABORT(PETSC_COMM_WORLD, ierr); } */ if (step == 0) { ierr = ParticleViewFromOptions(particlesData, NULL, "-particle_init"); CHKERRABORT(PETSC_COMM_WORLD, ierr); } else { ierr = ParticleViewFromOptions(particlesData, NULL, "-particle_view"); CHKERRABORT(PETSC_COMM_WORLD, ierr); } PetscFunctionReturn(0); } static PetscErrorCode ParticleSetInitialVelocity(DM particleDm) { PetscFunctionBeginUser; PetscErrorCode ierr; /* PetscScalar *vel; PetscInt dim, Npb, p, n; ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "", "Box Particle Initialization Options", NULL);CHKERRQ(ierr); ierr = PetscOptionsInt("-Npb", "The initial number of particles per box dimension", NULL, Npb, &Npb, NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); ierr = PetscPrintf(PETSC_COMM_WORLD, "***Npb=%D\n***", Npb);CHKERRQ(ierr); ierr = DMSwarmGetField(particleDm, ParticleVelocity, NULL, NULL, (void **) &vel);CHKERRQ(ierr); ierr = DMGetDimension(particleDm, &dim);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "***dim=%D\n***", dim);CHKERRQ(ierr); Npb *= dim; for (p = 0; p < Npb; ++p) { for (n = 0; n < dim; n++) { vel[p+n] = 0.0; } } ierr = DMSwarmRestoreField(particleDm, ParticleVelocity, NULL, NULL, (void **) &vel);CHKERRQ(ierr); */ Vec vel; ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr); ierr = VecSet(vel, 0.0);CHKERRQ(ierr); //ierr = VecView(vel, PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr); PetscFunctionReturn(0); } int main( int argc, char *argv[] ) { DM dm; // domain definition TS ts; // time-stepper PetscErrorCode ierr; PetscBag parameterBag; // constant flow parameters Vec flowField; // flow solution vector FlowData flowData; PetscReal t; PetscInt Dim=2; PetscReal dt=0.1; // dt for time stepper PetscInt max_steps=2; // maximum time steps PetscReal Re=1.0; // Reynolds number PetscReal St=1.0; // Strouhal number PetscReal Pe=1.0; // Peclet number PetscReal Mu=1.0; // viscosity PetscReal K_input=1.0; // thermal conductivity PetscReal Cp = 1.0; // heat capacity // PetscInt Np=10; // initialize Petsc ... ierr = PetscInitialize(&argc, &argv, NULL, "");CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "*** Set up a simple flow *** \n");CHKERRQ(ierr); // setup the ts ierr = TSCreate(PETSC_COMM_WORLD, &ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = CreateMesh(PETSC_COMM_WORLD, &dm, PETSC_TRUE, Dim); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetDM(ts, dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP); CHKERRABORT(PETSC_COMM_WORLD, ierr); //output the mesh ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the flow data ierr = FlowCreate(&flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); // setup problem ierr = IncompressibleFlow_SetupDiscretization(flowData, dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); IncompressibleFlowParameters flowParameters; // changing non-dimensional parameters manually here ... flowParameters.strouhal = St; flowParameters.reynolds = Re; flowParameters.peclet = Pe; flowParameters.mu = Mu; flowParameters.k = K_input; flowParameters.cp = Cp; // print out the parameters ierr = PetscPrintf(PETSC_COMM_WORLD, "*** non-dimensional parameters ***\n");CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "St=%g\n", flowParameters.strouhal);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Re=%g\n", flowParameters.reynolds);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Pe=%g\n", flowParameters.peclet);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Mu=%g\n", flowParameters.mu);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "K=%g\n", flowParameters.k);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Cp=%g\n", flowParameters.cp);CHKERRQ(ierr); // Start the problem setup PetscScalar constants[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS]; ierr = IncompressibleFlow_PackParameters(&flowParameters, constants); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = IncompressibleFlow_StartProblemSetup(flowData, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS, constants); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Override problem with source terms, boundary, and set the exact solution PetscDS prob; ierr = DMGetDS(dm, &prob); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup Boundary Conditions // Note: DM_BC_ESSENTIAL is a Dirichlet BC. PetscInt id; id = 3; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "top wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 1; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "bottom wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 2; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "right wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 4; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "left wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 3; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "top wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 1; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "bottom wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 2; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "right wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 4; ierr = PetscDSAddBoundary( prob, DM_BC_ESSENTIAL, "left wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = IncompressibleFlow_CompleteProblemSetup(flowData, ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Name the flow field ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = SetInitialConditions(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSGetTime(ts, &t); CHKERRABORT(PETSC_COMM_WORLD, ierr); // *** added by Pedram for dt and number of time steps *** ierr = TSSetTimeStep(ts,dt); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetMaxSteps(ts,max_steps); CHKERRABORT(PETSC_COMM_WORLD, ierr); // *********************************** ierr = DMSetOutputSequenceNumber(dm, 0, t); CHKERRABORT(PETSC_COMM_WORLD, ierr); // checks for convergence ... ierr = DMTSCheckFromOptions(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); ParticleData particles; // Setup the particle domain ierr = ParticleInertialCreate(&particles, Dim); //ierr = ParticleInertialCreate(&particles, Dim); CHKERRABORT(PETSC_COMM_WORLD, ierr); // link the flow to the particles ierr = ParticleInitializeFlow(particles, flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); // name the particle domain ierr = PetscObjectSetOptionsPrefix((PetscObject)(particles->dm), "particles_"); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscObjectSetName((PetscObject)particles->dm, "Particles"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // initialize the particles position and velocity ierr = ParticleInitialize(dm, particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = ParticleSetInitialVelocity(particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr); // setup the flow monitor to also check particles ierr = TSMonitorSet(ts, MonitorFlowAndParticleError, particles, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetFromOptions(ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup particle position integrator TS particleTs; ierr = TSCreate(PETSC_COMM_WORLD, &particleTs); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscObjectSetOptionsPrefix((PetscObject)particleTs, "particle_"); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = ParticleInertialSetupIntegrator(particles, particleTs, flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Solve the one way coupled system ierr = TSSolve(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Cleanup ierr = DMDestroy(&dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSDestroy(&ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSDestroy(&particleTs); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = FlowDestroy(&flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = ParticleInertialDestroy(&particles); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscFinalize(); exit(ierr); // _lower 0.25,0.25 _upper 0.75,0.75 // Npb 10 // _ts_dt 0.1 // _layout_type box // _ts_convergence_estimate // _num_refine 1 // -particle_ts_monitor_cancel // -ts_monitor_cancel // -particle_layout_type box // -particle_lower 0.1,0.1 // -particle_upper 0.3,0.3 // -Npb 5 // -particle_ts_max_steps 10 // -particle_ts_dt 0.05 /* -ksp_type fgmres -ksp_gmres_restart 10 -ksp_rtol 1.0e-9 -ksp_error_if_not_converged -pc_type fieldsplit -pc_fieldsplit_0_fields 0,2 -pc_fieldsplit_1_fields 1 -pc_fieldsplit_type schur -pc_fieldsplit_schur_factorization_type full -fieldsplit_0_pc_type lu -fieldsplit_pressure_ksp_rtol 1e-10 -fieldsplit_pressure_pc_type jacobi */ /* * -Npb 1 -particle_lower 0.05,0.1 -particle_upper 0.3,0.9 -particle_layout_type box -vec_init hdf5:/Users/pedram/scratch/sol.h5 -vec_view hdf5:/Users/pedram/scratch/sol.h5::append -dm_view hdf5:/Users/pedram/scratch/sol.h5 -dm_refine 2 -vel_petscspace_degree 2 -pres_petscspace_degree 1 -temp_petscspace_degree 1 -ksp_type fgmres -ksp_rtol 1.0e-9 -ksp_atol 1.0e-12 -ksp_error_if_not_converged -pc_type fieldsplit -pc_fieldsplit_0_fields 0,2 -pc_fieldsplit_1_fields 1 -pc_fieldsplit_type schur -pc_fieldsplit_schur_factorization_type full -fieldsplit_0_pc_type lu -fieldsplit_pressure_ksp_rtol 1e-10 -fieldsplit_pressure_pc_type jacobi -dm_plex_separate_marker -snes_monitor -ksp_monitor -snes_converged_reason -ksp_converged_reason -particle_view hdf5:/Users/pedram/scratch/solP.h5::append -particle_init hdf5:/Users/pedram/scratch/solP.h5 */ }
{ "alphanum_fraction": 0.6693005741, "avg_line_length": 34.1031578947, "ext": "c", "hexsha": "989472caff62bfe4b64ca77ecec795c6b7c819dc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_path": "cavity.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_path": "cavity.c", "max_line_length": 844, "max_stars_count": null, "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_path": "cavity.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4821, "size": 16199 }
/* Author: Lisandro Dalcin */ /* Contact: dalcinl@gmail.com */ #ifndef PETSC4PY_H #define PETSC4PY_H #include <Python.h> #include <petsc.h> #include "petsc4py.PETSc_api.h" static int import_petsc4py(void) { if (import_petsc4py__PETSc() < 0) goto bad; return 0; bad: return -1; } #endif /* !PETSC4PY_H */
{ "alphanum_fraction": 0.6855345912, "avg_line_length": 16.7368421053, "ext": "h", "hexsha": "45930b6275099b806c5a81bd3022850d82634cb5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_path": "src/include/petsc4py/petsc4py.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_path": "src/include/petsc4py/petsc4py.h", "max_line_length": 45, "max_stars_count": null, "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_path": "src/include/petsc4py/petsc4py.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 111, "size": 318 }
#if !defined(MAIN_H_INCLUDED) #define MAIN_H_INCLUDED #include "Exceptions.h" #include <cstdlib> #include <filesystem> #include <gsl/gsl> #include <iostream> #include <stdexcept> template <typename T> int commonMain(size_t argCount, const char*const*const argList) { using ::std::filesystem::path; using ::gsl::make_span; using ::std::cout; using ::std::endl; auto exitCode{EXIT_FAILURE}; try { // Pass the argument list, not including the program name (0th element): T program{make_span(argList + 1, argCount - 1)}; exitCode = program.run(); } catch (const CmdLineError& ex) { exitCode = T::usage(cout, path{argList[0]}.stem().generic_string(), ex.what()); } catch (const ::std::exception& ex) { cout << endl << "Exception of type " << typeid(ex).name() << endl << " " << ex.what() << endl << endl; } return exitCode; } #endif // MAIN_H_INCLUDED
{ "alphanum_fraction": 0.6681664792, "avg_line_length": 20.6744186047, "ext": "h", "hexsha": "623b5ae7ec39885b659e655788be214ff6e37648", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_path": "main.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "IanEmmons/CmdLineUtil", "max_issues_repo_path": "main.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_path": "main.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 253, "size": 889 }
#include <stdio.h> #include <gsl/gsl_multiset.h> int main (void) { gsl_multiset * c; size_t i; printf ("All multisets of {0,1,2,3} by size:\n") ; for (i = 0; i <= 4; i++) { c = gsl_multiset_calloc (4, i); do { printf ("{"); gsl_multiset_fprintf (stdout, c, " %u"); printf (" }\n"); } while (gsl_multiset_next (c) == GSL_SUCCESS); gsl_multiset_free (c); } return 0; }
{ "alphanum_fraction": 0.5021834061, "avg_line_length": 17.6153846154, "ext": "c", "hexsha": "6ac1e7c1499fe93c6d336bfa27eabf7cf778d146", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/multiset.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/multiset.c", "max_line_length": 52, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/multiset.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 150, "size": 458 }
/* multifit/fdjac.c * * Copyright (C) 2013 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * * This module contains routines for approximating the Jacobian with finite * differences for nonlinear least-squares fitting. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> static int fdjac(const gsl_vector *x, const gsl_vector *wts, gsl_multifit_function_fdf *fdf, const gsl_vector *f, gsl_matrix *J); /* fdjac() Compute approximate Jacobian using forward differences Inputs: x - parameter vector wts - data weights fdf - fdf struct f - (input) vector of function values f_i(x) J - (output) Jacobian matrix Return: success or error */ static int fdjac(const gsl_vector *x, const gsl_vector *wts, gsl_multifit_function_fdf *fdf, const gsl_vector *f, gsl_matrix *J) { int status = 0; size_t i, j; double h; const double epsfcn = 0.0; double eps = sqrt(GSL_MAX(epsfcn, GSL_DBL_EPSILON)); for (j = 0; j < fdf->p; ++j) { double xj = gsl_vector_get(x, j); /* use column j of J as temporary storage for f(x + dx) */ gsl_vector_view v = gsl_matrix_column(J, j); h = eps * fabs(xj); if (h == 0.0) h = eps; /* perturb x_j to compute forward difference */ gsl_vector_set((gsl_vector *) x, j, xj + h); status += gsl_multifit_eval_wf (fdf, x, wts, &v.vector); if (status) return status; /* restore x_j */ gsl_vector_set((gsl_vector *) x, j, xj); h = 1.0 / h; for (i = 0; i < fdf->n; ++i) { double fnext = gsl_vector_get(&v.vector, i); double fi = gsl_vector_get(f, i); gsl_matrix_set(J, i, j, (fnext - fi) * h); } } return status; } /* fdjac() */ /* gsl_multifit_fdfsolver_dif_df() Compute approximate Jacobian using finite differences Inputs: x - parameter vector wts - data weights (set to NULL if not needed) fdf - fdf f - (input) function values f_i(x) J - (output) approximate Jacobian matrix Return: success or error */ int gsl_multifit_fdfsolver_dif_df(const gsl_vector *x, const gsl_vector *wts, gsl_multifit_function_fdf *fdf, const gsl_vector *f, gsl_matrix *J) { return fdjac(x, wts, fdf, f, J); } /* gsl_multifit_fdfsolver_dif_df() */ #ifndef GSL_DISABLE_DEPRECATED /* gsl_multifit_fdfsolver_dif_fdf() Compute function values (analytic) and approximate Jacobian using finite differences Inputs: x - parameter vector fdf - fdf f - (output) function values f_i(x) J - (output) approximate Jacobian matrix Return: success or error */ int gsl_multifit_fdfsolver_dif_fdf(const gsl_vector *x, gsl_multifit_function_fdf *fdf, gsl_vector *f, gsl_matrix *J) { int status = 0; status = gsl_multifit_eval_wf(fdf, x, NULL, f); if (status) return status; status = fdjac(x, NULL, fdf, f, J); if (status) return status; return status; } /* gsl_multifit_fdfsolver_dif_fdf() */ #endif /* !GSL_DISABLE_DEPRECATED */
{ "alphanum_fraction": 0.6418884982, "avg_line_length": 27.2739726027, "ext": "c", "hexsha": "f00881e60d1fbf01b93df16c26f770e7929b12b4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/fdjac.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/fdjac.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multifit/fdjac.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1088, "size": 3982 }
#pragma once #include "parser.h" #include "format.h" #include "nameutils.h" #include "utils.h" #include <sfun/string_utils.h> #include <cmdlime/errors.h> #include <gsl/gsl> #include <algorithm> #include <sstream> #include <iomanip> #include <functional> #include <cassert> namespace cmdlime::detail{ namespace str = sfun::string_utils; template <FormatType formatType> class PosixParser : public Parser<formatType> { using Parser<formatType>::Parser; void processCommand(std::string command) { auto possibleNumberArg = command; command = str::after(command, "-"); if (isParamOrFlag(command)){ if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands){ if (!foundParam_.empty()) throw ParsingError{"Parameter '-" + foundParam_ + "' value can't be empty"}; if (argumentEncountered_) throw ParsingError{"Flags and parameters must precede arguments"}; } parseCommand(command); } else if (isNumber(possibleNumberArg)){ this->readArg(possibleNumberArg); argumentEncountered_ = true; } else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands) throw ParsingError{"Encountered unknown parameter or flag '-" + command + "'"}; } void preProcess() override { checkNames(); argumentEncountered_ = false; foundParam_.clear(); } void process(const std::string& token) override { if (str::startsWith(token, "-") && token.size() > 1) processCommand(token); else if (!foundParam_.empty()){ this->readParam(foundParam_, token); foundParam_.clear(); } else{ this->readArg(token); argumentEncountered_ = true; } } void postProcess() override { if (!foundParam_.empty()) throw ParsingError{"Parameter '-" + foundParam_ + "' value can't be empty"}; } void parseCommand(const std::string& command) { if (command.empty()) throw ParsingError{"Flags and parameters must have a name"}; auto paramValue = std::string{}; for(auto ch : command){ auto opt = std::string{ch}; if (!foundParam_.empty()) paramValue += opt; else if (this->findFlag(opt)) this->readFlag(opt); else if (this->findParam(opt) || this->findParamList(opt)) foundParam_ = opt; else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands) throw ParsingError{"Unknown option '" + opt + "' in command '-" + command + "'"}; } if (!foundParam_.empty() && !paramValue.empty()){ this->readParam(foundParam_, paramValue); foundParam_.clear(); } } void checkNames() { auto check = [](const OptionInfo& var, const std::string& varType){ if (var.name().size() != 1) throw ConfigError{varType + "'s name '" + var.name() + "' can't have more than one symbol"}; if (!std::isalnum(var.name().front())) throw ConfigError{varType + "'s name '" + var.name() + "' must be an alphanumeric character"}; }; this->forEachParamInfo([check](const OptionInfo& var){ check(var, "Parameter"); }); this->forEachParamListInfo([check](const OptionInfo& var){ check(var, "Parameter"); }); this->forEachFlagInfo([check](const OptionInfo& var){ check(var, "Flag"); }); } bool isParamOrFlag(const std::string& str) { if (str.empty()) return false; auto opt = str.substr(0,1); return this->findFlag(opt) || this->findParam(opt) || this->findParamList(opt); } private: bool argumentEncountered_ = false; std::string foundParam_; }; class PosixNameProvider{ public: static std::string name(const std::string& optionName) { Expects(!optionName.empty()); return std::string{static_cast<char>(std::tolower(optionName.front()))}; } static std::string shortName(const std::string& optionName) { Expects(!optionName.empty()); return {}; } static std::string fullName(const std::string& optionName) { Expects(!optionName.empty()); return toKebabCase(optionName); } static std::string valueName(const std::string& typeName) { Expects(!typeName.empty()); return toCamelCase(templateType(typeNameWithoutNamespace(typeName))); } }; class PosixOutputFormatter{ public: static std::string paramUsageName(const IParam& param) { auto stream = std::stringstream{}; if (param.isOptional()) stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">]"; else stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">"; return stream.str(); } static std::string paramListUsageName(const IParamList& param) { auto stream = std::stringstream{}; if (param.isOptional()) stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">...]"; else stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">..."; return stream.str(); } static std::string paramDescriptionName(const IParam& param, int indent = 0) { auto stream = std::stringstream{}; stream << std::setw(indent) << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">"; return stream.str(); } static std::string paramListDescriptionName(const IParamList& param, int indent = 0) { auto stream = std::stringstream{}; stream << std::setw(indent) << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">"; return stream.str(); } static std::string paramPrefix() { return "-"; } static std::string flagUsageName(const IFlag& flag) { auto stream = std::stringstream{}; stream << "[" << flagPrefix() << flag.info().name() << "]"; return stream.str(); } static std::string flagDescriptionName(const IFlag& flag, int indent = 0) { auto stream = std::stringstream{}; stream << std::setw(indent) << flagPrefix() << flag.info().name(); return stream.str(); } static std::string flagPrefix() { return "-"; } static std::string argUsageName(const IArg& arg) { auto stream = std::stringstream{}; stream << "<" << arg.info().name() << ">"; return stream.str(); } static std::string argDescriptionName(const IArg& arg, int indent = 0) { auto stream = std::stringstream{}; if (indent) stream << std::setw(indent) << " "; stream << "<" << arg.info().name() << "> (" << arg.info().valueName() << ")"; return stream.str(); } static std::string argListUsageName(const IArgList& argList) { auto stream = std::stringstream{}; if (argList.isOptional()) stream << "[" << argList.info().name() << "...]"; else stream << "<" << argList.info().name() << "...>"; return stream.str(); } static std::string argListDescriptionName(const IArgList& argList, int indent = 0) { auto stream = std::stringstream{}; if (indent) stream << std::setw(indent) << " "; stream << "<" << argList.info().name() << "> (" << argList.info().valueName() << ")"; return stream.str(); } }; template<> struct Format<FormatType::POSIX> { using parser = PosixParser<FormatType::POSIX>; using nameProvider = PosixNameProvider; using outputFormatter = PosixOutputFormatter; static constexpr bool shortNamesEnabled = false; }; }
{ "alphanum_fraction": 0.5577877284, "avg_line_length": 31.1811320755, "ext": "h", "hexsha": "f89d7effefc0691fe20af7307499d5e5032f5db7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_line_length": 113, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/posixformat.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 1885, "size": 8263 }
/** \file IRLS.h * * `IRLS' is a C++ implementation of the IRLS algorithm for GLM * Copyright (C) 2013 Xioaquan Wen, Timothee Flutre * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _IRLS_H_ #define _IRLS_H_ #include <vector> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "LinkFunc.h" class IRLS { private: gsl_vector * y; // response vector gsl_matrix * X; // design matrix gsl_vector * offset; // offset vector bool free_data; // depends on load_data() or set_data() size_t n; // sample size; size_t p; // number of parameters (including intercept) size_t rank; // of X (useful for p-values) gsl_vector * bv; // vector of estimated effect sizes gsl_matrix * VB; // covariance matrix of estimated effect sizes double psi; // dispersion public: LinkFunc * link; IRLS(const char * link_type); ~IRLS(); void load_data(const std::vector<double> & yv, const std::vector<std::vector<double> > &Xv, const std::vector<double> & offv); void set_data(gsl_vector * yv, gsl_matrix * Xv, gsl_vector * offv); void fit_model(); std::vector<double> get_coef(); std::vector<double> get_stderr(); size_t get_rank_X() { return rank; }; double get_dispersion() { return psi; }; private: void compute_variance(gsl_vector *w); }; // IRLS #endif // _IRLS_H_
{ "alphanum_fraction": 0.6852409639, "avg_line_length": 28.4571428571, "ext": "h", "hexsha": "8ad3d1fa315b5cdf214cf83059233166c23ec95a", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-05-07T02:16:27.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-15T09:15:46.000Z", "max_forks_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Lan-lab/Chrom-Lasso-", "max_forks_repo_path": "Code/IRLS_glm/IRLS.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Lan-lab/Chrom-Lasso-", "max_issues_repo_path": "Code/IRLS_glm/IRLS.h", "max_line_length": 70, "max_stars_count": null, "max_stars_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Lan-lab/Chrom-Lasso-", "max_stars_repo_path": "Code/IRLS_glm/IRLS.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 531, "size": 1992 }
/** * Cascade simulation based on pair production and bremsstrahlung interactions * * copyright (C) 2007 * the icecube collaboration * * $Id: I3CascadeSimulation.h 35916 2007-08-23 09:34:12Z bvoigt $ * * @version $Revision: 35916 $ * @date $LastChangedDate: 2007-08-23 03:34:12 -0600 (Thu, 23 Aug 2007) $ * @author Bernhard Voigt <bernhard.voigt@desy.de> Last changed by: $LastChangedBy: bvoigt $ */ #ifndef I3_CASCADE_SIMULATION_H_INCLUDED #define I3_CASCADE_SIMULATION_H_INCLUDED //Standard C/C++ includes #include <vector> #include <stack> // Gnu Scientific Library #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> // local includes #include "cmc/I3CascadeMCCommon.h" #include "cmc/I3CascadeDevelopment.h" #include "cmc/I3CascadeParametrization.h" #include "cmc/I3MetropolisHastings.h" // icetray includes #include "phys-services/I3RandomService.h" /** * @brief Local definition of a Particle struct * * The particle struct holds energy and postion informations * of particles in the simulation. */ struct Particle { static const short ELECTRON = 1; static const short PHOTON = 0; double energy; double x; short type; /** * Particle with energy, at position x (1-dimensional), of * type type (1 is electron, 0 is photon) * * @param energy * @param x * @param type */ Particle(double energy, double x, short type) : energy(energy), x(x), type(type) { } }; /** * @brief Local definition of beta distribution * * The struct defines a pdf function, ie. the beta distribtuion * not normed, though. * It provides a rvs method to draw random samples from * the beta distribution using gsl_rng * * The parameters used for the beta distribibution (alpha and beta) * are defined. * * Functions are passed to I3MetropolisHastings and need to be static. */ struct beta_dist { // define the logger name, use the same as for the simulation class SET_LOGGER("I3CascadeSimulation"); // parameter to beta function static double alpha; static double beta; /** * Beta Function \f$ x^{\alpha-1} (1-x)^{\beta-1}\f$ * * @param x */ static double pdf(const double& x) { log_trace("alpha %.2f, beta %.2f", alpha, beta); return pow(x, alpha-1) * pow(1-x, beta-1); } /** * Returns a random variate drawn from the beta distribution * * Uses the gsl_ran_beta method * * @param random gsl_rng instance */ static double rvs(const gsl_rng* random) { log_trace("alpha %.2f, beta %.2f", alpha, beta); return gsl_ran_beta(random, alpha, beta); } }; /** *@brief This class implements a Cascade development simulation including * the LPM effect * * Description of the simulation can be found here: * http://wiki.icecube.wisc.edu/index.php/Cascade_Simulation * * Cross section formulars used are defined in I3CascadeSimulationCrossSections * * * @author Bernhard Voigt */ class I3CascadeSimulation : public I3CascadeDevelopment, public I3CascadeMCCommon::Sampler { // define the logger name SET_LOGGER("I3CascadeSimulation"); public: /** * @brief Constructor * * @param random random number service from icetray frame */ I3CascadeSimulation(I3RandomServicePtr random); /** * @brief Destructor * * Frees the gsl objects */ ~I3CascadeSimulation(); virtual void SetRandomNumberGenerator(I3RandomServicePtr); /** * Simulates a cascade of the given energy * * @param energy */ void Simulate(I3Particle::ParticleType type, double energy); /** * Sets the energy threshold down to which particles are tracked (Default is 50 TeV) * * This shouldn't be lower than 1 GeV, since this is the limit for the Bremsstrahlung * interaction * * @param thresholdEnergy */ void SetThreshold(double thresholdEnergy) { threshold_ = thresholdEnergy; } /** * Returns the threshold energy down to which particles are tracked * * @return threshold energy */ double GetThreshold() { return threshold_; } /** * @brief default energy threshold down to which particles are tracked */ static const double DEFAULT_THRESHOLD; private: I3CascadeSimulation(const I3CascadeSimulation&); /** * Cacluates the pair productio mean free path for the given energy * * @param energy */ double PairProductionMeanFreePath(double energy); /** * Cacluates the bremsstrahlung radiation length (cut off energy is defined as 1 GeV) * * @param energy */ double BremsstrahlungMeanFreePath(double energy); /** * Samples the bremsstrahlung cross section to get a fractional energy * of a secondary particle produced in an interaction with a incident particle * of the given energy * * @see I3MetropolisHastings::Sample * * @param energy */ double SampleBremsstrahlungCrossSection(double energy); /** * Samples the pair production cross section to get a fractional energy * of a secondary particle produced in an interaction with a incident particle * of the given energy * * @see I3MetropolisHastings::Sample * * @param energy */ double SamplePairProductionCrossSection(double energy); /** * Inits the simulation * * Interpolation of the mean free paths is performed * The metropolis hastings random samplers are initialized */ void Init(); /** * Inits the metropolis hastings random samplers */ void InitMetropolisHastings(); /** * Draw and discard samples from the MH samplers * to make them independent of initial conditions */ void BurnIn(); /** * Calcuation and interpolation of the pair production mean free path * in an energy range specified by lower and upper (in log10) * The interpolation used the given number of points. * Default energy range is from 100 GeV to 10 EeV * * Uses the integration and interpolation routines from gsl * * @param lower * @param upper * @param points */ void InterpolPairProductionMeanFreePath(double lower=2., double upper=13.0, int points=100); /** * Calcuation and interpolation of the bremsstrahlung radiation length * in an energy range specified by lower and upper (in log10) * The interpolation used the given number of points. * Default energy range is from 100 GeV to 10 EeV * * Uses the integration and interpolation routines from gsl * * The integration of the cross section is done down to a lower edge of * I3CascadeSimulation::BREMSSTRAHLUNGCUTOFF * this is due to the infrared limit, where the cross section raises to infinite values. * * @param lower * @param upper * @param points */ void InterpolBremsstrahlungMeanFreePath(double lower=2., double upper=13.0, int points=100); /** * Returns the mean free path of a particle * * @param particle */ double MeanFreePath(Particle particle); /** * Propagates a particle * * Draws the next interaction point * Calls the interaction method to produce secondaries * * @param particle */ void Propagate(Particle particle); /** * Creates secondaries produced in an interaction of the given particle * * @param particle */ void Interaction(Particle particle); /** * Produces a secondary gamma */ void BremsstrahlungInteraction(Particle electron); /** * Produces a electron, positron pair */ void PairProductionInteraction(Particle photon); /** * Deposits the particle * * Calculates the energy loss profile of the given particle * and adds it to the total energy loss profile of this simulation */ void Deposit(Particle particle); /** * @brief stack holding particles that have to be propagated */ std::stack<Particle> particles_; /** * @brief counter how many particles have been created */ unsigned int particlesCreated_; /** * @brief counter how many particles have been deleted */ unsigned int particlesDeleted_; /** * @brief struct holding beta distribution parameters, provides function * evaluation and random numbers */ beta_dist betaDist_; /** * @brief random number sampler for low energy bremsstrahlung */ I3MetropolisHastings lowBremsSampler_; /** * @brief random number sampler for high energy bremsstrahlung */ I3MetropolisHastings highBremsSampler_; /** * @brief random number sampler for low energy pair production */ I3MetropolisHastings lowPairSampler_; /** * @brief random number sampler for high energy pair production */ I3MetropolisHastings highPairSampler_; /** * @brief parametrization of energy loss profile for low energy particles */ I3CascadeParametrization parametrization_; /** * @brief gsl spline accelerator object used for spline evaluation (bremsstrahlung) */ gsl_interp_accel* interpolAccBrems_; /** * @brief gsl spline - interpolation of Bresmstrahlung mean free path */ gsl_spline* splineBrems_; /** * @brief gsl spline accelerator object used for spline evaluation (pair production) */ gsl_interp_accel* interpolAccPair_; /** * @brief gsl spline - interpolation of Pairproduction mean free path */ gsl_spline* splinePair_; /** * @brief threshold down to which particles are tracked, default is 50 TeV */ double threshold_; /** * @brief repeat burn-in for each event * * This ensures that the events are truly independent and can be reproduced * given the state of the random number generator. */ bool perEventBurnIn_; /** * @brief lowest energy of bremsstrahlung photons */ static const double BREMSSTRAHLUNGCUTOFF; }; #endif
{ "alphanum_fraction": 0.696496067, "avg_line_length": 24.6574307305, "ext": "h", "hexsha": "17e74a20f8b47bc947e7145fab3dbd87fe8d6603", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_path": "cmc/private/cmc/I3CascadeSimulation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_path": "cmc/private/cmc/I3CascadeSimulation.h", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_path": "cmc/private/cmc/I3CascadeSimulation.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "num_tokens": 2486, "size": 9789 }
#include <config.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_test.h> #include <gsl/gsl_wavelet.h> #include <gsl/gsl_wavelet2d.h> #define N_BS 11 double urand (void); double urand (void) { static unsigned long int x = 1; x = (1103515245 * x + 12345) & 0x7fffffffUL; return x / 2147483648.0; } const size_t member[N_BS] = { 309, 307, 305, 303, 301, 208, 206, 204, 202, 105, 103 }; void test_1d (size_t N, size_t stride, const gsl_wavelet_type * T, size_t member); void test_2d (size_t N, size_t tda, const gsl_wavelet_type * T, size_t member, int type); int main (int argc, char **argv) { size_t i, N, stride, tda; const int S = 1, NS = 2; /* Standard & Non-standard transforms */ /* One-dimensional tests */ for (N = 1; N <= 16384; N *= 2) { for (stride = 1; stride <= 5; stride++) { for (i = 0; i < N_BS; i++) { test_1d (N, stride, gsl_wavelet_bspline, member[i]); test_1d (N, stride, gsl_wavelet_bspline_centered, member[i]); } for (i = 4; i <= 20; i += 2) { test_1d (N, stride, gsl_wavelet_daubechies, i); test_1d (N, stride, gsl_wavelet_daubechies_centered, i); } test_1d (N, stride, gsl_wavelet_haar, 2); test_1d (N, stride, gsl_wavelet_haar_centered, 2); } } /* Two-dimensional tests */ for (N = 1; N <= 64; N *= 2) { for (tda = N; tda <= N + 5; tda++) { for (i = 0; i < N_BS; i++) { test_2d (N, tda, gsl_wavelet_bspline, member[i], S); test_2d (N, tda, gsl_wavelet_bspline_centered, member[i], S); test_2d (N, tda, gsl_wavelet_bspline, member[i], NS); test_2d (N, tda, gsl_wavelet_bspline_centered, member[i], NS); } for (i = 4; i <= 20; i += 2) { test_2d (N, tda, gsl_wavelet_daubechies, i, S); test_2d (N, tda, gsl_wavelet_daubechies_centered, i, S); test_2d (N, tda, gsl_wavelet_daubechies, i, NS); test_2d (N, tda, gsl_wavelet_daubechies_centered, i, NS); } test_2d (N, tda, gsl_wavelet_haar, 2, S); test_2d (N, tda, gsl_wavelet_haar_centered, 2, S); test_2d (N, tda, gsl_wavelet_haar, 2, NS); test_2d (N, tda, gsl_wavelet_haar_centered, 2, NS); } } exit (gsl_test_summary ()); } void test_1d (size_t N, size_t stride, const gsl_wavelet_type * T, size_t member) { gsl_wavelet_workspace *work; gsl_vector *v1, *v2, *vdelta; gsl_vector_view v; gsl_wavelet *w; size_t i; double *data = malloc (N * stride * sizeof (double)); for (i = 0; i < N * stride; i++) data[i] = 12345.0 + i; v = gsl_vector_view_array_with_stride (data, stride, N); v1 = &(v.vector); for (i = 0; i < N; i++) { gsl_vector_set (v1, i, urand ()); } v2 = gsl_vector_alloc (N); gsl_vector_memcpy (v2, v1); vdelta = gsl_vector_alloc (N); work = gsl_wavelet_workspace_alloc (N); w = gsl_wavelet_alloc (T, member); gsl_wavelet_transform_forward (w, v2->data, v2->stride, v2->size, work); gsl_wavelet_transform_inverse (w, v2->data, v2->stride, v2->size, work); for (i = 0; i < N; i++) { double x1 = gsl_vector_get (v1, i); double x2 = gsl_vector_get (v2, i); gsl_vector_set (vdelta, i, fabs (x1 - x2)); } { double x1, x2; i = gsl_vector_max_index (vdelta); x1 = gsl_vector_get (v1, i); x2 = gsl_vector_get (v2, i); gsl_test (fabs (x2 - x1) > N * 1e-15, "%s(%d), n = %d, stride = %d, maxerr = %g", gsl_wavelet_name (w), member, N, stride, fabs (x2 - x1)); } if (stride > 1) { int status = 0; for (i = 0; i < N * stride; i++) { if (i % stride == 0) continue; status |= (data[i] != (12345.0 + i)); } gsl_test (status, "%s(%d) other data untouched, n = %d, stride = %d", gsl_wavelet_name (w), member, N, stride); } gsl_wavelet_workspace_free (work); gsl_wavelet_free (w); gsl_vector_free (vdelta); gsl_vector_free (v2); free (data); } void test_2d (size_t N, size_t tda, const gsl_wavelet_type * T, size_t member, int type) { gsl_wavelet_workspace *work; gsl_matrix *m2; gsl_wavelet *w; gsl_matrix *m1; gsl_matrix *mdelta; gsl_matrix_view m; size_t i; size_t j; double *data = malloc (N * tda * sizeof (double)); const char * typename; typename = (type == 1) ? "standard" : "nonstd" ; for (i = 0; i < N * tda; i++) data[i] = 12345.0 + i; m = gsl_matrix_view_array_with_tda (data, N, N, tda); m1 = &(m.matrix); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { gsl_matrix_set (m1, i, j, urand()); } } m2 = gsl_matrix_alloc (N, N); gsl_matrix_memcpy (m2, m1); mdelta = gsl_matrix_alloc (N, N); work = gsl_wavelet_workspace_alloc (N); w = gsl_wavelet_alloc (T, member); switch (type) { case 1: gsl_wavelet2d_transform_matrix_forward (w, m2, work); gsl_wavelet2d_transform_matrix_inverse (w, m2, work); break; case 2: gsl_wavelet2d_nstransform_matrix_forward (w, m2, work); gsl_wavelet2d_nstransform_matrix_inverse (w, m2, work); break; } for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { double x1 = gsl_matrix_get (m1, i, j); double x2 = gsl_matrix_get (m2, i, j ); gsl_matrix_set (mdelta, i, j, fabs (x1 - x2)); } } { double x1, x2; gsl_matrix_max_index (mdelta, &i, &j); x1 = gsl_matrix_get (m1, i, j); x2 = gsl_matrix_get (m2, i, j); gsl_test (fabs (x2 - x1) > N * 1e-15, "%s(%d)-2d %s, n = %d, tda = %d, maxerr = %g", gsl_wavelet_name (w), member, typename, N, tda, fabs (x2 - x1)); } if (tda > N) { int status = 0; for (i = 0; i < N ; i++) { for (j = N; j < tda; j++) { status |= (data[i*tda+j] != (12345.0 + (i*tda+j))); } } gsl_test (status, "%s(%d)-2d %s other data untouched, n = %d, tda = %d", gsl_wavelet_name (w), member, typename, N, tda); } free (data); gsl_wavelet_workspace_free (work); gsl_wavelet_free (w); gsl_matrix_free (m2); gsl_matrix_free (mdelta); }
{ "alphanum_fraction": 0.5462977041, "avg_line_length": 24.2693726937, "ext": "c", "hexsha": "997e4aab5e358715034d04831342e2399cd3b024", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/wavelet/test.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/wavelet/test.c", "max_line_length": 84, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/wavelet/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 2257, "size": 6577 }
/* * ----------------------------------------------------------------- * Partially Stirred Reaction Library --- pasr_lib.h * Version: 1.6180 * Date: Nov 16, 2010 * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010 by Americo Barbosa da Cunha Junior * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * A copy of the GNU General Public License is available in * LICENSE.txt or http://www.gnu.org/licenses/. * ----------------------------------------------------------------- * This is the header file for the PaSR model. * ----------------------------------------------------------------- */ #ifndef __PaSR_LIB_H__ #define __PaSR_LIB_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> /* * ------------------------------------------------------------ * Types: struct pasr, pasr_wrk * ------------------------------------------------------------ * This structure contains fields of PaSR model. * * last update: Nov 5, 2009 * ------------------------------------------------------------ */ typedef struct pasr { int *pasr_idx; /* particles index vector */ gsl_vector **pasr_ps; /* particle system */ } pasr_wrk; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ void pasr_title(); int pasr_input(unsigned long int *seed,unsigned int *Np,unsigned int *K, double *t0,double *delta_t,double *tau_res, double *tau_mix,double *Tmax,double *Tmin); pasr_wrk *pasr_alloc(); int pasr_init(int Np,int Neq,pasr_wrk *pasr); void pasr_free(int Np,void **pasr_bl); int pasr_set_all(int Np,gsl_vector *phi,pasr_wrk *pasr); int pasr_Nexc(int Np,double delta_t,double tau_res); void pasr_meanvar(int Np,int k,gsl_vector **ps,double *mean,double *var); void pasr_iem(int Np,int Neq,double delta_t,double tau_mix, double phi_m,int *idx,gsl_vector **ps); void pmsr_iops(int Np,int Nexc,int Npair,gsl_rng *r, gsl_vector *phi,pmsr_wrk *pmsr); #endif /* __PaSR_LIB_H__ */
{ "alphanum_fraction": 0.5285558385, "avg_line_length": 28.9368421053, "ext": "h", "hexsha": "bb64f158e50a1571ba6d37c480b34f42e111a36f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-1.0/include/pasr_lib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-1.0/include/pasr_lib.h", "max_line_length": 73, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-1.0/include/pasr_lib.h", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 621, "size": 2749 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_roots.h> #include "ccl.h" #include "ccl_params.h" /* --------- ROUTINE: h_over_h0 --------- INPUT: scale factor, cosmology TASK: Compute E(a)=H(a)/H0 */ static double h_over_h0(double a, ccl_cosmology * cosmo, int *status) { // Check if massive neutrinos are present - if not, we don't need to // compute their contribution double Om_mass_nu; if ((cosmo->params.N_nu_mass)>1e-12) { Om_mass_nu = ccl_Omeganuh2( a, cosmo->params.N_nu_mass, cosmo->params.mnu, cosmo->params.T_CMB, cosmo->data.accelerator, status) / (cosmo->params.h) / (cosmo->params.h); ccl_check_status(cosmo, status); } else { Om_mass_nu = 0; } /* Calculate h^2 using the formula (eqn 2 in the CCL paper): E(a)^2 = Omega_m a^-3 + Omega_l a^(-3*(1+w0+wa)) exp(3*wa*(a-1)) + Omega_k a^-2 + (Omega_g + Omega_n_rel) a^-4 + Om_mass_nu */ return sqrt( (cosmo->params.Omega_m + cosmo->params.Omega_l * pow(a,-3*(cosmo->params.w0+cosmo->params.wa)) * exp(3*cosmo->params.wa*(a-1)) + cosmo->params.Omega_k * a + (cosmo->params.Omega_g + cosmo->params.Omega_n_rel) / a + Om_mass_nu * a*a*a) / (a*a*a)); } /* --------- ROUTINE: ccl_omega_x --------- INPUT: cosmology object, scale factor, species label TASK: Compute the density relative to critical, Omega(a) for a given species. Possible values for "label": ccl_species_crit_label <- critical (physical) ccl_species_m_label <- matter ccl_species_l_label <- DE ccl_species_g_label <- radiation ccl_species_k_label <- curvature ccl_species_ur_label <- massless neutrinos ccl_species_nu_label <- massive neutrinos */ double ccl_omega_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int *status) { // If massive neutrinos are present, compute the phase-space integral and // get OmegaNuh2. If not, set OmegaNuh2 to zero. double OmNuh2; if ((cosmo->params.N_nu_mass) > 0.0001) { // Call the massive neutrino density function just once at this redshift. OmNuh2 = ccl_Omeganuh2(a, cosmo->params.N_nu_mass, cosmo->params.mnu, cosmo->params.T_CMB, cosmo->data.accelerator, status); ccl_check_status(cosmo, status); } else { OmNuh2 = 0.; } double hnorm = h_over_h0(a, cosmo, status); switch(label) { case ccl_species_crit_label : return 1.; case ccl_species_m_label : return cosmo->params.Omega_m / (a*a*a) / hnorm / hnorm; case ccl_species_l_label : return cosmo->params.Omega_l * pow(a,-3 * (1 + cosmo->params.w0 + cosmo->params.wa)) * exp(3 * cosmo->params.wa * (a-1)) / hnorm / hnorm; case ccl_species_g_label : return cosmo->params.Omega_g / (a*a*a*a) / hnorm / hnorm; case ccl_species_k_label : return cosmo->params.Omega_k / (a*a) / hnorm / hnorm; case ccl_species_ur_label : return cosmo->params.Omega_n_rel / (a*a*a*a) / hnorm / hnorm; case ccl_species_nu_label : return OmNuh2 / (cosmo->params.h) / (cosmo->params.h) / hnorm / hnorm; default: *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message( cosmo, "ccl_background.c: ccl_omega_x(): Species %d not supported\n", label); return NAN; } } /* --------- ROUTINE: ccl_rho_x --------- INPUT: cosmology object, scale factor, species label TASK: Compute rho_x(a), with x defined by species label. Possible values for "label": ccl_species_crit_label <- critical (physical) ccl_species_m_label <- matter (physical) ccl_species_l_label <- DE (physical) ccl_species_g_label <- radiation (physical) ccl_species_k_label <- curvature (physical) ccl_species_ur_label <- massless neutrinos (physical) ccl_species_nu_label <- massive neutrinos (physical) */ double ccl_rho_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int is_comoving, int *status) { double comfac; if (is_comoving) { comfac = a*a*a; } else { comfac = 1.0; } double hnorm = h_over_h0(a, cosmo, status); double rhocrit = RHO_CRITICAL * (cosmo->params.h) * (cosmo->params.h) * hnorm * hnorm * comfac; return rhocrit * ccl_omega_x(cosmo, a, label, status); } // Structure to hold parameters of chi_integrand typedef struct { ccl_cosmology *cosmo; int * status; } chipar; /* --------- ROUTINE: chi_integrand --------- INPUT: scale factor TASK: compute the integrand of the comoving distance */ static double chi_integrand(double a, void * params_void) { ccl_cosmology * cosmo = ((chipar *)params_void)->cosmo; int *status = ((chipar *)params_void)->status; return CLIGHT_HMPC/(a*a*h_over_h0(a, cosmo, status)); } /* --------- ROUTINE: growth_ode_system --------- INPUT: scale factor TASK: Define the ODE system to be solved in order to compute the growth (of the density) */ static int growth_ode_system(double a,const double y[],double dydt[],void *params) { int status = 0; ccl_cosmology * cosmo = params; double hnorm=h_over_h0(a,cosmo, &status); double om=ccl_omega_x(cosmo, a, ccl_species_m_label, &status); dydt[0]=y[1]/(a*a*a*hnorm); dydt[1]=1.5*hnorm*a*om*y[0]; return status; } /* --------- ROUTINE: df_integrand --------- INPUT: scale factor, spline object TASK: Compute integrand from modified growth function */ static double df_integrand(double a,void * spline_void) { if(a<=0) return 0; else { gsl_spline *df_a_spline=(gsl_spline *)spline_void; return gsl_spline_eval(df_a_spline,a,NULL)/a; } } /* --------- ROUTINE: growth_factor_and_growth_rate --------- INPUT: scale factor, cosmology TASK: compute the growth (D(z)) and the growth rate, logarithmic derivative (f?) */ static int growth_factor_and_growth_rate(double a,double *gf,double *fg,ccl_cosmology *cosmo, int *stat) { if(a<EPS_SCALEFAC_GROWTH) { *gf=a; *fg=1; return 0; } else { int gslstatus; double y[2]; double ainit=EPS_SCALEFAC_GROWTH; gsl_odeiv2_system sys={growth_ode_system,NULL,2,cosmo}; gsl_odeiv2_driver *d= gsl_odeiv2_driver_alloc_y_new(&sys,gsl_odeiv2_step_rkck,0.1*EPS_SCALEFAC_GROWTH,0,ccl_gsl->ODE_GROWTH_EPSREL); y[0]=EPS_SCALEFAC_GROWTH; y[1]=EPS_SCALEFAC_GROWTH*EPS_SCALEFAC_GROWTH*EPS_SCALEFAC_GROWTH* h_over_h0(EPS_SCALEFAC_GROWTH,cosmo, stat); gslstatus=gsl_odeiv2_driver_apply(d,&ainit,a,y); gsl_odeiv2_driver_free(d); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: growth_factor_and_growth_rate():"); return NAN; } *gf=y[0]; *fg=y[1]/(a*a*h_over_h0(a,cosmo, stat)*y[0]); return 0; } } /* --------- ROUTINE: compute_chi --------- INPUT: scale factor, cosmology OUTPUT: chi -> radial comoving distance TASK: compute radial comoving distance at a */ static void compute_chi(double a, ccl_cosmology *cosmo, double * chi, int * stat) { int gslstatus; double result; chipar p; p.cosmo=cosmo; p.status=stat; gsl_integration_cquad_workspace * workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION); gsl_function F; F.function = &chi_integrand; F.params = &p; //TODO: CQUAD is great, but slower than other methods. This could be sped up if it becomes an issue. gslstatus=gsl_integration_cquad( &F, a, 1.0, 0.0, ccl_gsl->INTEGRATION_DISTANCE_EPSREL, workspace, &result, NULL, NULL); *chi=result/cosmo->params.h; gsl_integration_cquad_workspace_free(workspace); if (gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: compute_chi():"); *stat = CCL_ERROR_COMPUTECHI; } } //Root finding for a(chi) typedef struct { double chi; ccl_cosmology *cosmo; int * status; } Fpar; static double fzero(double a,void *params) { double chi,chia,a_use=a; chi=((Fpar *)params)->chi; compute_chi(a_use,((Fpar *)params)->cosmo,&chia, ((Fpar *)params)->status); return chi-chia; } static double dfzero(double a,void *params) { ccl_cosmology *cosmo=((Fpar *)params)->cosmo; int *stat = ((Fpar *)params)->status; chipar p; p.cosmo=cosmo; p.status=stat; return chi_integrand(a,&p)/cosmo->params.h; } static void fdfzero(double a,void *params,double *f,double *df) { *f=fzero(a,params); *df=dfzero(a,params); } /* --------- ROUTINE: a_of_chi --------- INPUT: comoving distance chi, cosmology, stat, a_old, gsl_root_fdfsolver OUTPUT: scale factor TASK: compute the scale factor that corresponds to a given comoving distance chi Note: This routine uses a root solver to find an a such that compute_chi(a) = chi. The root solver uses the derivative of compute_chi (which is chi_integrand) and the value itself. */ static void a_of_chi(double chi, ccl_cosmology *cosmo, int* stat, double *a_old, gsl_root_fdfsolver *s) { if(chi==0) { *a_old=1; } else { Fpar p; gsl_function_fdf FDF; double a_previous,a_current=*a_old; p.cosmo=cosmo; p.chi=chi; p.status=stat; FDF.f=&fzero; FDF.df=&dfzero; FDF.fdf=&fdfzero; FDF.params=&p; gsl_root_fdfsolver_set(s,&FDF,a_current); int iter=0, gslstatus; do { iter++; gslstatus=gsl_root_fdfsolver_iterate(s); if(gslstatus!=GSL_SUCCESS) ccl_raise_gsl_warning(gslstatus, "ccl_background.c: a_of_chi():"); a_previous=a_current; a_current=gsl_root_fdfsolver_root(s); gslstatus=gsl_root_test_delta(a_current, a_previous, 0, ccl_gsl->ROOT_EPSREL); } while(gslstatus==GSL_CONTINUE && iter <= ccl_gsl->ROOT_N_ITERATION); *a_old=a_current; // Allows us to pass a status to h_over_h0 for the neutrino integral calculation. if(gslstatus==GSL_SUCCESS) { *stat = *(p.status); } else { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: a_of_chi():"); *stat = CCL_ERROR_COMPUTECHI; } } } /* ----- ROUTINE: ccl_cosmology_compute_distances ------ INPUT: cosmology TASK: if not already there, make a table of comoving distances and of E(a) */ void ccl_cosmology_compute_distances(ccl_cosmology * cosmo, int *status) { //Do nothing if everything is computed already if(cosmo->computed_distances) return; if(ccl_splines->A_SPLINE_MAX>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); return; } // Create logarithmically and then linearly-spaced values of the scale factor int na = ccl_splines->A_SPLINE_NA+ccl_splines->A_SPLINE_NLOG-1; double * a = ccl_linlog_spacing(ccl_splines->A_SPLINE_MINLOG, ccl_splines->A_SPLINE_MIN, ccl_splines->A_SPLINE_MAX, ccl_splines->A_SPLINE_NLOG, ccl_splines->A_SPLINE_NA); // Allocate arrays for all three of E(a), chi(a), and a(chi) double *E_a = malloc(sizeof(double)*na); double *chi_a = malloc(sizeof(double)*na); // Allocate E(a) and chi(a) splines gsl_spline * E = gsl_spline_alloc(A_SPLINE_TYPE, na); gsl_spline * chi = gsl_spline_alloc(A_SPLINE_TYPE, na); // a(chi) spline allocated below //Check for too little memory if (a==NULL || E_a==NULL || chi_a==NULL){ *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); } //Check for messed up scale factor conditions if (!*status){ if ((fabs(a[0]-ccl_splines->A_SPLINE_MINLOG)>1e-5) || (fabs(a[na-1]-ccl_splines->A_SPLINE_MAX)>1e-5) || (a[na-1]>1.0)) { *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating first logarithmic and then linear spacing in a\n"); } } // Fill in E(a) - note, this step cannot change the status variable if (!*status) for (int i=0; i<na; i++) E_a[i] = h_over_h0(a[i], cosmo, status); // Create a E(a) spline if (!*status){ if (gsl_spline_init(E, a, E_a, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating E(a) spline\n"); } } // Compute chi(a) if (!*status){ for (int i=0; i<na; i++) compute_chi(a[i], cosmo, &chi_a[i], status); if (*status){ *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): chi(a) integration error \n"); } } // Initialize chi(a) spline if (!*status){ if (gsl_spline_init(chi, a, chi_a, na)){//in Mpc *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating chi(a) spline\n"); } } if (*status){//If there was an error, free the GSL splines and return gsl_spline_free(E); //Note: you are allowed to call gsl_free() on NULL gsl_spline_free(chi); } // Set up the boundaries for the a(chi) spline double dchi, chi0, chif, a0, af; if(!*status){ dchi=5.; chi0=chi_a[na-1]; chif=chi_a[0]; a0=a[na-1]; af=a[0]; } //TODO: The interval in chi (5. Mpc) should be made a macro free(a); //Free these, in preparation for making a(chi) splines free(E_a); free(chi_a); //Note: you are allowed to call free() on NULL //////////////////////////////////////////////////////////////////////////////////////////////////// //Below here na (length of some arrays) changes, so this function has to be split at this point. //////////////////////////////////////////////////////////////////////////////////////////////////// na = (int)((chif-chi0)/dchi); dchi = (chif-chi0)/na; // <=5, since na is an integer //Allocate new arrays for a and chi(a) chi_a = ccl_linear_spacing(chi0, chif, na); a = malloc(sizeof(double)*na); //Allocate space for GSL root finders const gsl_root_fdfsolver_type *T=gsl_root_fdfsolver_newton; gsl_root_fdfsolver *s=gsl_root_fdfsolver_alloc(T); gsl_spline *achi; //Check for too little memory if (!*status){ achi=gsl_spline_alloc(A_SPLINE_TYPE, na); if (a==NULL || chi_a==NULL){ *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); }else if(fabs(chi_a[0]-chi0)>1e-5 || fabs(chi_a[na-1]-chif)>1e-5) { //Check for messed up chi conditions *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating linear spacing in chi\n"); } } // Calculate a(chi) if (!*status){ a[0]=a0; a[na-1]=af; for(int i=1;i<na-1;i++) { // we are using the previous value as a guess here to help the root finder // as long as we use small steps in a this should be fine a_of_chi(chi_a[i],cosmo, status, &a0, s); a[i]=a0; } if(*status) { *status = CCL_ERROR_ROOT; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): a(chi) root-finding error \n"); } } // Initialize the a(chi) spline if (!*status){ if(gsl_spline_init(achi, chi_a, a, na)){ *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): Error creating a(chi) spline\n"); } } free(a); free(chi_a); //Note: you are allowed to call free() on NULL gsl_root_fdfsolver_free(s); if (*status){//If there was an error, free the GSL splines and return gsl_spline_free(E); //Note: you are allowed to call gsl_free() on NULL gsl_spline_free(chi); gsl_spline_free(achi); return; } //If there were no errors, attach the splines to the cosmo struct and end the function. if(cosmo->data.accelerator==NULL) cosmo->data.accelerator=gsl_interp_accel_alloc(); cosmo->data.E = E; cosmo->data.chi = chi; cosmo->data.achi = achi; cosmo->computed_distances = true; } /* ----- ROUTINE: ccl_cosmology_compute_growth ------ INPUT: cosmology TASK: if not already there, make a table of growth function and growth rate normalize growth to input parameter growth0 */ void ccl_cosmology_compute_growth(ccl_cosmology * cosmo, int * status) { // This is not valid for massive neutrinos; if we have massive neutrinos, exit. if (cosmo->params.N_nu_mass>0){ *status = CCL_ERROR_NOT_IMPLEMENTED; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Support for the growth rate in cosmologies with massive neutrinos is not yet implemented.\n"); return; } if(cosmo->computed_growth) return; // Create logarithmically and then linearly-spaced values of the scale factor int chistatus = 0, na = ccl_splines->A_SPLINE_NA+ccl_splines->A_SPLINE_NLOG-1; double * a = ccl_linlog_spacing(ccl_splines->A_SPLINE_MINLOG, ccl_splines->A_SPLINE_MIN, ccl_splines->A_SPLINE_MAX, ccl_splines->A_SPLINE_NLOG, ccl_splines->A_SPLINE_NA); if (a==NULL || (fabs(a[0]-ccl_splines->A_SPLINE_MINLOG)>1e-5) || (fabs(a[na-1]-ccl_splines->A_SPLINE_MAX)>1e-5) || (a[na-1]>1.0) ) { free(a); *status = CCL_ERROR_LINSPACE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating logarithmically and then linear spacing in a\n"); return; } gsl_integration_cquad_workspace * workspace=NULL; gsl_function F; gsl_spline *df_a_spline=NULL; if(cosmo->params.has_mgrowth) { double *df_arr=malloc(na*sizeof(double)); if(df_arr==NULL) { free(a); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); return; } //Generate spline for Delta f(z) that we will then interpolate into an array of a gsl_spline *df_z_spline=gsl_spline_alloc(A_SPLINE_TYPE,cosmo->params.nz_mgrowth); chistatus=gsl_spline_init(df_z_spline,cosmo->params.z_mgrowth,cosmo->params.df_mgrowth, cosmo->params.nz_mgrowth); if(chistatus) { free(a); free(df_arr); gsl_spline_free(df_z_spline); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(z) spline\n"); return; } for (int i=0; i<na; i++) { if(a[i]>0) { double z=1./a[i]-1.; if(z<=cosmo->params.z_mgrowth[0]) df_arr[i]=cosmo->params.df_mgrowth[0]; else if(z>cosmo->params.z_mgrowth[cosmo->params.nz_mgrowth-1]) df_arr[i]=cosmo->params.df_mgrowth[cosmo->params.nz_mgrowth-1]; else chistatus |= gsl_spline_eval_e(df_z_spline,z,NULL,&df_arr[i]); } else { df_arr[i]=0; } } if(chistatus) { free(a); free(df_arr); gsl_spline_free(df_z_spline); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error evaluating Delta f(z) spline\n"); return; } gsl_spline_free(df_z_spline); //Generate Delta(f) spline df_a_spline=gsl_spline_alloc(A_SPLINE_TYPE,na); chistatus=gsl_spline_init(df_a_spline,a,df_arr,na); free(df_arr); if (chistatus) { free(a); gsl_spline_free(df_a_spline); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(a) spline\n"); return; } workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION); F.function=&df_integrand; F.params=df_a_spline; } // allocate space for y, which will be all three // of E(a), chi(a), D(a) and f(a) in turn. int status_mg=0, gslstatus; double growth0,fgrowth0; double *y = malloc(sizeof(double)*na); if(y==NULL) { free(a); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); return; } double *y2 = malloc(sizeof(double)*na); if(y2==NULL) { free(a); free(y); *status=CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\n"); return; } chistatus|=growth_factor_and_growth_rate(1.,&growth0,&fgrowth0,cosmo, status); for(int i=0; i<na; i++) { chistatus|=growth_factor_and_growth_rate(a[i],&(y[i]),&(y2[i]),cosmo, status); if(cosmo->params.has_mgrowth) { if(a[i]>0) { double df,integ; //Add modification to f gslstatus = gsl_spline_eval_e(df_a_spline,a[i],NULL,&df); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_cosmology_compute_growth():"); status_mg |= gslstatus; } y2[i]+=df; //Multiply D by exp(-int(df)) gslstatus = gsl_integration_cquad(&F,a[i],1.0,0.0,ccl_gsl->INTEGRATION_DISTANCE_EPSREL,workspace,&integ,NULL,NULL); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_cosmology_compute_growth():"); status_mg |= gslstatus; } y[i]*=exp(-integ); } } y[i]/=growth0; } if(chistatus || status_mg || *status) { free(a); free(y); free(y2); if(df_a_spline!=NULL) gsl_spline_free(df_a_spline); if(workspace!=NULL) gsl_integration_cquad_workspace_free(workspace); if (chistatus) { *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): integral for linear growth factor didn't converge\n"); } if(status_mg) { *status = CCL_ERROR_INTEG; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): integral for MG growth factor didn't converge\n"); } return; } if(cosmo->params.has_mgrowth) { gsl_spline_free(df_a_spline); gsl_integration_cquad_workspace_free(workspace); } gsl_spline * growth = gsl_spline_alloc(A_SPLINE_TYPE, na); chistatus = gsl_spline_init(growth, a, y, na); if(chistatus) { free(a); free(y); free(y2); gsl_spline_free(growth); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating D(a) spline\n"); return; } gsl_spline * fgrowth = gsl_spline_alloc(A_SPLINE_TYPE, na); chistatus = gsl_spline_init(fgrowth, a, y2, na); if(chistatus) { free(a); free(y); free(y2); gsl_spline_free(growth); gsl_spline_free(fgrowth); *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_cosmology_compute_growth(): Error creating f(a) spline\n"); return; } // Initialize the accelerator which speeds the splines and // assign all the splines we've just made to the structure. if(cosmo->data.accelerator==NULL) cosmo->data.accelerator=gsl_interp_accel_alloc(); cosmo->data.growth = growth; cosmo->data.fgrowth = fgrowth; cosmo->data.growth0 = growth0; cosmo->computed_growth = true; free(a); free(y); free(y2); return; } //Expansion rate normalized to 1 today double ccl_h_over_h0(ccl_cosmology * cosmo, double a, int* status) { if(!cosmo->computed_distances) { ccl_cosmology_compute_distances(cosmo,status); ccl_check_status(cosmo, status); } double h_over_h0; int gslstatus = gsl_spline_eval_e(cosmo->data.E, a, cosmo->data.accelerator,&h_over_h0); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_h_over_h0():"); *status = gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_h_over_h0(): Scale factor outside interpolation range.\n"); return NAN; } return h_over_h0; } void ccl_h_over_h0s(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_h_over_h0(cosmo, a[i], &_status); *status |= _status; } } // Distance-like function examples, all in Mpc double ccl_comoving_radial_distance(ccl_cosmology * cosmo, double a, int * status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { return 0.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); ccl_check_status(cosmo,status); return NAN; } else { if(!cosmo->computed_distances) { ccl_cosmology_compute_distances(cosmo, status); ccl_check_status(cosmo,status); } double crd; int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, cosmo->data.accelerator, &crd); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_comoving_radial_distance():"); *status = gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_comoving_radial_distance(): Scale factor outside interpolation range.\n"); return NAN; } return crd; } } void ccl_comoving_radial_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int* status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_comoving_radial_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_sinn(ccl_cosmology *cosmo, double chi, int *status) { ////// // { sin(x) , if k==1 // sinn(x)={ x , if k==0 // { sinh(x) , if k==-1 switch(cosmo->params.k_sign) { case -1: return sinh(cosmo->params.sqrtk * chi) / cosmo->params.sqrtk; case 1: return sin(cosmo->params.sqrtk*chi) / cosmo->params.sqrtk; case 0: return chi; default: *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_sinn: ill-defined cosmo->params.k_sign = %d", cosmo->params.k_sign); return NAN; } } double ccl_comoving_angular_distance(ccl_cosmology * cosmo, double a, int* status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { return 0.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); ccl_check_status(cosmo,status); return NAN; } else { if (!cosmo->computed_distances) { ccl_cosmology_compute_distances(cosmo, status); ccl_check_status(cosmo, status); } double chi; int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, cosmo->data.accelerator,&chi); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_comoving_angular_distance():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_comoving_angular_distance(): Scale factor outside interpolation range.\n"); return NAN; } return ccl_sinn(cosmo,chi,status); } } void ccl_comoving_angular_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int* status) { int _status; for (int i=0; i < na; i++) { _status = 0; output[i] = ccl_comoving_angular_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_luminosity_distance(ccl_cosmology * cosmo, double a, int* status) { return ccl_comoving_angular_distance(cosmo, a, status) / a; } void ccl_luminosity_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_luminosity_distance(cosmo, a[i], &_status); *status |= _status; } } double ccl_distance_modulus(ccl_cosmology * cosmo, double a, int* status) { if((a > (1.0 - 1.e-8)) && (a<=1.0)) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: distance_modulus undefined for a=1.\n"); ccl_check_status(cosmo,status); return NAN; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); ccl_check_status(cosmo,status); return NAN; } else { if (!cosmo->computed_distances) { ccl_cosmology_compute_distances(cosmo, status); ccl_check_status(cosmo, status); } /* distance modulus = 5 * log10(d) - 5 Since d in CCL is in Mpc, you get 5*log10(10^6) - 5 = 30 - 5 = 25 for the constant. */ return 5 * log10(ccl_luminosity_distance(cosmo, a, status)) + 25; } } void ccl_distance_moduli(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_distance_modulus(cosmo, a[i], &_status); *status |= _status; } } //Scale factor for a given distance double ccl_scale_factor_of_chi(ccl_cosmology * cosmo, double chi, int * status) { if((chi < 1.e-8) && (chi>=0.)) { return 1.; } else if(chi<0.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: distance cannot be smaller than 0.\n"); ccl_check_status(cosmo,status); return NAN; } else { if (!cosmo->computed_distances) { ccl_cosmology_compute_distances(cosmo,status); ccl_check_status(cosmo,status); } double a; int gslstatus = gsl_spline_eval_e(cosmo->data.achi, chi,cosmo->data.accelerator_achi, &a); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_scale_factor_of_chi():"); *status |= gslstatus; } return a; } } // void ccl_scale_factor_of_chis(ccl_cosmology * cosmo, int nchi, double chi[], double output[], int * status) { int _status; for (int i=0; i<nchi; i++) { _status = 0; output[i] = ccl_scale_factor_of_chi(cosmo, chi[i], &_status); *status |= _status; } } double ccl_growth_factor(ccl_cosmology * cosmo, double a, int * status) { if(a==1.){ return 1.; } else if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); ccl_check_status(cosmo,status); return NAN; } else { if (!cosmo->computed_growth) { ccl_cosmology_compute_growth(cosmo, status); ccl_check_status(cosmo, status); } if (*status!= CCL_ERROR_NOT_IMPLEMENTED) { double D; int gslstatus = gsl_spline_eval_e(cosmo->data.growth, a, cosmo->data.accelerator,&D); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_growth_factor():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_growth_factor(): Scale factor outside interpolation range.\n"); return NAN; } return D; } else { return NAN; } } } void ccl_growth_factors(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_factor(cosmo, a[i], &_status); *status |= _status; } } double ccl_growth_factor_unnorm(ccl_cosmology * cosmo, double a, int * status) { if (!cosmo->computed_growth) { ccl_cosmology_compute_growth(cosmo, status); ccl_check_status(cosmo, status); } if (*status != CCL_ERROR_NOT_IMPLEMENTED) { return cosmo->data.growth0 * ccl_growth_factor(cosmo, a, status); } else { return NAN; } } void ccl_growth_factors_unnorm(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_factor_unnorm(cosmo, a[i], &_status); *status |= _status; } } double ccl_growth_rate(ccl_cosmology * cosmo, double a, int * status) { if(a>1.) { *status = CCL_ERROR_COMPUTECHI; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: scale factor cannot be larger than 1.\n"); ccl_check_status(cosmo,status); return NAN; } else { if (!cosmo->computed_growth) { ccl_cosmology_compute_growth(cosmo, status); ccl_check_status(cosmo, status); } if(*status != CCL_ERROR_NOT_IMPLEMENTED) { double g; int gslstatus = gsl_spline_eval_e(cosmo->data.fgrowth, a, cosmo->data.accelerator,&g); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_background.c: ccl_growth_rate():"); *status |= gslstatus; ccl_cosmology_set_status_message(cosmo, "ccl_background.c: ccl_growth_rate(): Scale factor outside interpolation range.\n"); return NAN; } return g; } else { return NAN; } } } void ccl_growth_rates(ccl_cosmology * cosmo, int na, double a[], double output[], int * status) { int _status; for (int i=0; i<na; i++) { _status = 0; output[i] = ccl_growth_rate(cosmo, a[i], &_status); *status |= _status; } }
{ "alphanum_fraction": 0.6729130146, "avg_line_length": 31.3314393939, "ext": "c", "hexsha": "8d69ef7683481f40e361013f36984e13db30e0cc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_path": "src/ccl_background.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "vrastil/CCL", "max_issues_repo_path": "src/ccl_background.c", "max_line_length": 188, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_path": "src/ccl_background.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10055, "size": 33086 }
#ifndef EXECUTE_INCLUDE #define EXECUTE_INCLUDE #include <filesystem> #include <string> #include <vector> #include <gsl/string_span> #include "path.h" namespace execHelper { namespace test { namespace baseUtils { namespace execution { using CommandLine = std::vector<std::string>; int execute(const CommandLine& commandLine, const Path& workingDir = std::filesystem::current_path()) noexcept; } // namespace execution } // namespace baseUtils } // namespace test } // namespace execHelper #endif /* EXECUTE_INCLUDE */
{ "alphanum_fraction": 0.7406716418, "avg_line_length": 20.6153846154, "ext": "h", "hexsha": "082cf590706c0c409b2cbe60e74541265cd7aca1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "test/base-utils/include/base-utils/execution.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "exec-helper/source", "max_issues_repo_path": "test/base-utils/include/base-utils/execution.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "test/base-utils/include/base-utils/execution.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 110, "size": 536 }
/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ Copyright (c) 1999-2014 and onwards, Imperial College London All rights reserved. See LICENSE for details =========================================================================*/ #ifndef _IRTKMATRIX_H #define _IRTKMATRIX_H #include <float.h> #ifdef USE_VXL #include <vnl/vnl_matrix.h> #else #include <gsl/gsl_matrix.h> #endif #include <irtkObject.h> #include <iostream> #include <cmath> /** Matrix class. */ class irtkMatrix : public irtkObject { protected: /// Number of rows int _rows; /// Number of colums int _cols; /// Data double **_matrix; public: /// Default constructor irtkMatrix(); /// Constructor for given number of rows and columns irtkMatrix(int, int); /// Copy constructor irtkMatrix(const irtkMatrix &); /// Destructor ~irtkMatrix(); /// Initialize matrix with number of rows and columns void Initialize(int, int); // // Matrix access functions // /// Returns number of rows int Rows() const; /// Returns number of columns int Cols() const; /// Puts matrix value void Put(int, int, double); /// Gets matrix value double Get(int, int) const; // // Operators for matrix access // /// Puts matrix value double& operator()(int, int); /// Gets matrix value double operator()(int, int) const; /// Access matrix get operator irtkMatrix operator()(int, int, int, int); /// Access matrix put operator void operator()(irtkMatrix &, int, int); // // Matrix operators for doubles // /// Subtraction of a double irtkMatrix& operator-=(const double&); /// Addition of a double irtkMatrix& operator+=(const double&); /// Multiplication with a double irtkMatrix& operator*=(const double&); /// Division by a double irtkMatrix& operator/=(const double&); /// Return result of subtraction of a double irtkMatrix operator- (const double&); /// Return result of addition of a double irtkMatrix operator+ (const double&); /// Return result of multiplication with a double irtkMatrix operator* (const double&); /// Return result of division by a double irtkMatrix operator/ (const double&); // // Matrix operators for matrices // /// Matrix copy operator irtkMatrix& operator =(const irtkMatrix&); /// Matrix subtraction operator irtkMatrix& operator-=(const irtkMatrix&); /// Matrix addition operator irtkMatrix& operator+=(const irtkMatrix&); /// Matrix multiplication operator irtkMatrix& operator*=(const irtkMatrix&); /// Return result of matrix subtraction irtkMatrix operator- (const irtkMatrix&); /// Return result of matrix addition irtkMatrix operator+ (const irtkMatrix&); /// Return result of matrix multiplication irtkMatrix operator* (const irtkMatrix&); /// Matrix inversion operator irtkMatrix operator! (void); /// Matrix transpose operator irtkMatrix operator~ (void); /// Matrix comparison operator = int operator==(const irtkMatrix &); // Matrix exponential via Pade approximation. // See Golub and Van Loan, Matrix Computations, Algorithm 11.3-1. friend irtkMatrix expm(irtkMatrix); // Matrix logarithm. friend irtkMatrix logm(irtkMatrix); // Matrix square root. friend irtkMatrix sqrtm(irtkMatrix); friend irtkMatrix FrechetMean(irtkMatrix *, int, int = 10); friend irtkMatrix FrechetMean(irtkMatrix *, double *, int, int = 10); #ifndef USE_STL /// Comparison operator != (if USE_STL is defined, negate == operator) int operator!=(const irtkMatrix &); #endif // // Matrix functions // /// Calculate norm of matrix double Norm(void) const; /// Calculate trace of matrix double Trace(void) const; // The infinity norm is the maximum of the absolute value row sums. double InfinityNorm(void) const; /// Calculate determinant of matrix double Det() const; /* Calculate SVD of matrix * now does the same as Eigenvalues (but eigenvalues are in square root) * algorithm chosen according to matrix properties (symmetry, diagonizability) */ void SVD(irtkMatrix &, irtkVector &, irtkMatrix &); /// Identity matrix void Ident(); /// Returns true if the matrix is an identity matrix. bool IsIdentity() const; /// Invert of matrix void Invert(); /// Adjugate of matrix and return determine; void Adjugate(double &); /// Transpose matrix void Transpose(); /* Calculate eigenvalues and eigenvectors of matrix * now does the same as SVD (but eigenvalues are NOT in square root) * algorithm chosen according to matrix properties (symmetry, diagonizability) */ void Eigenvalues(irtkMatrix &, irtkVector &, irtkMatrix &); /// Calculate least square fit via SVD void LeastSquaresFit(const irtkVector &, irtkVector &); // // Matrix in- and output // /// Interface to output stream friend std::ostream& operator<< (std::ostream&, const irtkMatrix&); /// Interface to input stream friend std::istream& operator>> (std::istream&, irtkMatrix&); /// Print matrix void Print(); /// Read matrix from file void Read (char *); /// Write matrix to file void Write(char *); /// Import matrix from text file (requires no. of expected rows and cols) void Import (char *, int, int); #ifdef USE_VXL /// Conversion to VNL matrix template <class T> void Matrix2Vnl(vnl_matrix<T> *m) const; /// Conversion from VNL matrix template <class T> void Vnl2Matrix(vnl_matrix<T> *m); #else /// Conversion to GSL matrix (memory must be allocated) void Matrix2GSL(gsl_matrix *) const; /// Conversion from GSL matrix void GSL2Matrix(gsl_matrix *); // // Matrix operators for vectors // /// Return result of multiplication of matrix and vector irtkVector operator* (const irtkVector&); #endif }; // // Access operators // inline int irtkMatrix::Rows() const { return _rows; } inline int irtkMatrix::Cols() const { return _cols; } inline void irtkMatrix::Put(int rows, int cols, double matrix) { #ifdef NO_BOUNDS _matrix[cols][rows] = matrix; #else if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) { _matrix[cols][rows] = matrix; } else { cout << "irtkMatrix::Put: parameter out of range\n"; } #endif } inline double irtkMatrix::Get(int rows, int cols) const { #ifdef NO_BOUNDS return _matrix[cols][rows]; #else if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) { return _matrix[cols][rows]; } else { cout << "irtkMatrix::Get: parameter out of range\n"; return 0; } #endif } inline double &irtkMatrix::operator()(int rows, int cols) { #ifdef NO_BOUNDS return _matrix[cols][rows]; #else if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) { return _matrix[cols][rows]; } else { cout << "irtkMatrix::operator(): parameter out of range\n"; return _matrix[0][0]; } #endif } inline double irtkMatrix::operator()(int rows, int cols) const { #ifdef NO_BOUNDS return _matrix[cols][rows]; #else if ((rows >= 0) && (rows < _rows) && (cols >= 0) && (cols < _cols)) { return _matrix[cols][rows]; } else { cout << "irtkMatrix::operator(): parameter out of range\n"; return 0; } #endif } // // Matrix operators for doubles // inline irtkMatrix& irtkMatrix::operator-=(const double &x) { int i, j; for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { _matrix[j][i] -= x; } } return *this; } inline irtkMatrix& irtkMatrix::operator+=(const double &x) { int i, j; for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { _matrix[j][i] += x; } } return *this; } inline irtkMatrix& irtkMatrix::operator*=(const double &x) { int i, j; for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { _matrix[j][i] *= x; } } return *this; } inline irtkMatrix& irtkMatrix::operator/=(const double &x) { int i, j; for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { _matrix[j][i] /= x; } } return *this; } inline irtkMatrix irtkMatrix::operator-(const double &x) { int i, j; irtkMatrix m; m = *this; for (j = 0; j < _cols; j++) { for (i = 0; i < m._rows; i++) { m._matrix[j][i] = _matrix[j][i] - x; } } return m; } inline irtkMatrix irtkMatrix::operator+(const double &x) { int i, j; irtkMatrix m; m = *this; for (j = 0; j < _cols; j++) { for (i = 0; i < m._rows; i++) { m._matrix[j][i] = _matrix[j][i] + x; } } return m; } inline irtkMatrix irtkMatrix::operator*(const double &x) { int i, j; irtkMatrix m; m = *this; for (j = 0; j < _cols; j++) { for (i = 0; i < m._rows; i++) { m._matrix[j][i] = _matrix[j][i] * x; } } return m; } inline irtkMatrix irtkMatrix::operator/(const double &x) { int i, j; irtkMatrix m; m = *this; for (j = 0; j < _cols; j++) { for (i = 0; i < m._rows; i++) { m._matrix[j][i] = _matrix[j][i] / x; } } return m; } // // Matrix operators for matrices // inline int irtkMatrix::operator==(const irtkMatrix& m) { int i, j; if ((m._rows != _rows) || (m._cols != _cols)) return 0; for (j = 0; j < _cols; j++) { for (i = 0; i < m._rows; i++) { if (m._matrix[j][i] != _matrix[j][i]) return 0; } } return 1; } #ifndef USE_STL inline int irtkMatrix::operator!=(const irtkMatrix& m) { return !(*this == m); } #endif inline double irtkMatrix::Trace(void) const { int i, j; double trace = 0; if(_rows == _cols){ // The trace of a matrix for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { trace += _matrix[j][i]; } } return trace; }else{ std::cerr << "irtkMatrix::Trace() matrix number of col != row" << std::endl; return 0; } } inline double irtkMatrix::Norm(void) const { int i, j; double norm = 0; // The norm of a matrix M is defined as trace(M * M~) for (j = 0; j < _cols; j++) { for (i = 0; i < _rows; i++) { norm += _matrix[j][i]*_matrix[j][i]; } } return std::sqrt(norm); } inline double irtkMatrix::InfinityNorm(void) const { int i, j; double normInf = -1.0 * DBL_MAX; double sum; for (i = 0; i < _rows; ++i) { sum = 0; for (j = 0; j < _cols; ++j) { sum += abs(_matrix[j][i]); } if (sum > normInf) normInf = sum; } return normInf; } #endif
{ "alphanum_fraction": 0.6102435397, "avg_line_length": 20.1460674157, "ext": "h", "hexsha": "145cd0b828623eed4a266161e01f5bf294613c66", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_path": "source/IRTKSimple2/geometry++/include/irtkMatrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3221, "size": 10758 }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * --------------------------------------------------------------------------- * Copyright 2014 Nervana Systems Inc. All rights reserved. * * * Added sumabs, maxabs, save function headers * * Fixed numpy deprecation warnings * --------------------------------------------------------------------------- */ #ifndef MATRIX_H_ #define MATRIX_H_ #include "matrix_funcs.h" #include <sstream> #ifdef NUMPY_INTERFACE #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <arrayobject.h> #endif #include <limits> #include <assert.h> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <cuda_runtime.h> extern "C" { #include <cblas.h> } #ifdef DOUBLE_PRECISION #define CBLAS_GEMM cblas_dgemm #define CBLAS_SCAL cblas_dscal #define CBLAS_AXPY cblas_daxpy #else #define CBLAS_GEMM cblas_sgemm #define CBLAS_SCAL cblas_sscal #define CBLAS_AXPY cblas_saxpy #endif /* DOUBLE_PRECISION */ #define MTYPE_MAX numeric_limits<MTYPE>::max() typedef long long int int64; class Matrix { private: MTYPE* _data; bool _ownsData; int64 _numRows, _numCols; int64 _numElements; CBLAS_TRANSPOSE _trans; void _init(MTYPE* data, int64 numRows, int64 numCols, bool transpose, bool ownsData); void _tileTo2(Matrix& target) const; void _copyAllTo(Matrix& target) const; MTYPE _sum_column(int64 col) const; MTYPE _sum_row(int64 row) const; MTYPE _aggregate(MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; void _aggregate(int64 axis, Matrix& target, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; MTYPE _aggregateRow(int64 row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; MTYPE _aggregateCol(int64 row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; void _updateDims(int64 numRows, int64 numCols); void _applyLoop(MTYPE(*func)(MTYPE)); void _applyLoop(MTYPE (*func)(MTYPE), Matrix& target); void _applyLoop2(const Matrix& a, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const; void _applyLoop2(const Matrix& a, MTYPE (*func)(MTYPE,MTYPE, MTYPE), MTYPE scalar, Matrix& target) const; void _applyLoop2(const Matrix& a, MTYPE (*func)(MTYPE,MTYPE, MTYPE, MTYPE), MTYPE scalar1, MTYPE scalar2, Matrix& target) const; void _applyLoopScalar(const MTYPE scalar, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const; void _checkBounds(int64 startRow, int64 endRow, int64 startCol, int64 endCol) const; void _divideByVector(const Matrix& vec, Matrix& target); inline int64 _getNumColsBackEnd() const { return _trans == CblasNoTrans ? _numCols : _numRows; } public: enum FUNCTION { TANH, RECIPROCAL, SQUARE, ABS, EXP, LOG, ZERO, ONE, LOGISTIC1, LOGISTIC2, SIGN }; Matrix(); Matrix(int64 numRows, int64 numCols); Matrix(int64 numRows, int64 numCols, bool transpose); #ifdef NUMPY_INTERFACE Matrix(PyArrayObject *src); void _initpy(PyArrayObject *src); #endif Matrix(const Matrix &like); Matrix(MTYPE* data, int64 numRows, int64 numCols); Matrix(float *buffer, int64 numRows, int64 numCols, int nil); Matrix(MTYPE* data, int64 numRows, int64 numCols, bool transpose); ~Matrix(); inline MTYPE& getCell(int64 i, int64 j) const { assert(i >= 0 && i < _numRows); assert(j >= 0 && j < _numCols); if (_trans == CblasTrans) { return _data[j * _numRows + i]; } return _data[i * _numCols + j]; } MTYPE& operator()(int64 i, int64 j) const { return getCell(i, j); } inline MTYPE* getData() const { return _data; } inline bool isView() const { return !_ownsData; } inline int64 getNumRows() const { return _numRows; } inline int64 getNumCols() const { return _numCols; } inline int64 getNumDataBytes() const { return _numElements * sizeof(MTYPE); } inline int64 getNumElements() const { return _numElements; } inline int64 getLeadingDim() const { return _trans == CblasTrans ? _numRows : _numCols; } inline int64 getFollowingDim() const { return _trans == CblasTrans ? _numCols : _numRows; } inline CBLAS_TRANSPOSE getBLASTrans() const { return _trans; } inline bool isSameDims(const Matrix& a) const { return a.getNumRows() == getNumRows() && a.getNumCols() == getNumCols(); } inline bool isTrans() const { return _trans == CblasTrans; } /* * Only use if you know what you're doing! * Does not update any dimensions. Just flips the _trans flag. * * Use transpose() if you want to get the transpose of this matrix. */ inline void setTrans(bool trans) { assert(isTrans() == trans || !isView()); _trans = trans ? CblasTrans : CblasNoTrans; } void apply(FUNCTION f); void apply(Matrix::FUNCTION f, Matrix& target); void subtractFromScalar(MTYPE scalar); void subtractFromScalar(MTYPE scalar, Matrix &target) const; void biggerThanScalar(MTYPE scalar); void smallerThanScalar(MTYPE scalar); void equalsScalar(MTYPE scalar); void biggerThanScalar(MTYPE scalar, Matrix& target) const; void smallerThanScalar(MTYPE scalar, Matrix& target) const; void equalsScalar(MTYPE scalar, Matrix& target) const; void biggerThan(Matrix& a); void biggerThan(Matrix& a, Matrix& target) const; void smallerThan(Matrix& a); void smallerThan(Matrix& a, Matrix& target) const; void minWith(Matrix &a); void minWith(Matrix &a, Matrix &target) const; void maxWith(Matrix &a); void maxWith(Matrix &a, Matrix &target) const; void equals(Matrix& a); void equals(Matrix& a, Matrix& target) const; void notEquals(Matrix& a) ; void notEquals(Matrix& a, Matrix& target) const; void add(const Matrix &m); void add(const Matrix &m, MTYPE scale); void add(const Matrix &m, MTYPE scaleThis, MTYPE scaleM); void add(const Matrix &m, Matrix& target); void add(const Matrix &m, MTYPE scaleM, Matrix &target); void add(const Matrix &m, MTYPE scaleThis, MTYPE scaleM, Matrix &target); void subtract(const Matrix &m); void subtract(const Matrix &m, Matrix& target); void subtract(const Matrix &m, MTYPE scale); void subtract(const Matrix &m, MTYPE scale, Matrix& target); void addVector(const Matrix& vec, MTYPE scale); void addVector(const Matrix& vec, MTYPE scale, Matrix& target); void addVector(const Matrix& vec); void addVector(const Matrix& vec, Matrix& target); void addScalar(MTYPE scalar); void addScalar(MTYPE scalar, Matrix& target) const; void maxWithScalar(MTYPE scalar); void maxWithScalar(MTYPE scalar, Matrix &target) const; void minWithScalar(MTYPE scalar); void minWithScalar(MTYPE scalar, Matrix &target) const; void eltWiseMultByVector(const Matrix& vec); void eltWiseMultByVector(const Matrix& vec, Matrix& target); void eltWiseDivideByVector(const Matrix& vec); void eltWiseDivideByVector(const Matrix& vec, Matrix& target); void resize(int64 newNumRows, int64 newNumCols); void resize(const Matrix& like); Matrix& slice(int64 startRow, int64 endRow, int64 startCol, int64 endCol) const; void slice(int64 startRow, int64 endRow, int64 startCol, int64 endCol, Matrix &target) const; Matrix& sliceRows(int64 startRow, int64 endRow) const; void sliceRows(int64 startRow, int64 endRow, Matrix& target) const; Matrix& sliceCols(int64 startCol, int64 endCol) const; void sliceCols(int64 startCol, int64 endCol, Matrix& target) const; void rightMult(const Matrix &b, MTYPE scale); void rightMult(const Matrix &b, Matrix &target) const; void rightMult(const Matrix &b); void rightMult(const Matrix &b, MTYPE scaleAB, Matrix &target) const; void addProduct(const Matrix &a, const Matrix &b, MTYPE scaleAB, MTYPE scaleThis); void addProduct(const Matrix& a, const Matrix& b); void eltWiseMult(const Matrix& a); void eltWiseMult(const Matrix& a, Matrix& target) const; void eltWiseDivide(const Matrix& a); void eltWiseDivide(const Matrix& a, Matrix &target) const; Matrix& transpose() const; Matrix& transpose(bool hard) const; Matrix& tile(int64 timesY, int64 timesX) const; void tile(int64 timesY, int64 timesX, Matrix& target) const; void copy(Matrix &dest, int64 srcStartRow, int64 srcEndRow, int64 srcStartCol, int64 srcEndCol, int64 destStartRow, int64 destStartCol) const; Matrix& copy() const; void copy(Matrix& target) const; Matrix& sum(int64 axis) const; void sum(int64 axis, Matrix &target) const; MTYPE sum() const; MTYPE sumabs() const; MTYPE max() const; MTYPE maxabs() const; Matrix& max(int64 axis) const; void max(int64 axis, Matrix& target) const; MTYPE min() const; Matrix& min(int64 axis) const; void min(int64 axis, Matrix& target) const; MTYPE norm() const; MTYPE norm2() const; void scale(MTYPE scale); void scale(MTYPE alpha, Matrix& target); void reshape(int64 numRows, int64 numCols); Matrix& reshaped(int64 numRows, int64 numCols); void printShape(const char* name) const; bool hasNan() const; bool hasInf() const; void randomizeNormal(MTYPE mean, MTYPE stdev); void randomizeUniform(); void randomizeNormal(); void print() const; void print(int64 startRow,int64 rows, int64 startCol,int64 cols) const; void print(int64 rows, int64 cols) const; }; typedef std::vector<Matrix*> MatrixV; #endif /* MATRIX_H_ */
{ "alphanum_fraction": 0.6844210321, "avg_line_length": 37.0072202166, "ext": "h", "hexsha": "030242eda06287415a5a46cdc18ad47ddb6014ff", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "975b6977e61cf02508199ccd97b294ee0238639f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "TimDettmers/dlearndb", "max_forks_repo_path": "util/include/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "975b6977e61cf02508199ccd97b294ee0238639f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "TimDettmers/dlearndb", "max_issues_repo_path": "util/include/matrix.h", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "975b6977e61cf02508199ccd97b294ee0238639f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "TimDettmers/dlearndb", "max_stars_repo_path": "util/include/matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2711, "size": 10251 }
#include <gsl/span> namespace engine { template <class ElementType, std::ptrdiff_t Extent = gsl::dynamic_extent> using span = gsl::span<ElementType, Extent>; }
{ "alphanum_fraction": 0.7423312883, "avg_line_length": 20.375, "ext": "h", "hexsha": "704e4e1f60d6f9ecefca1960eeee7ddb3fa60b71", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z", "max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gaspardpetit/INF740-GameEngine", "max_forks_repo_path": "Core/span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "gaspardpetit/INF740-GameEngine", "max_issues_repo_path": "Core/span.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gaspardpetit/INF740-GameEngine", "max_stars_repo_path": "Core/span.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 40, "size": 163 }
/* * ----------------------------------------------------------------- * isat_lib.h * In Situ Adaptive Tabulation Library * Version: 2.0 * Last Update: Nov 3, 2019 * * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior * All rights reserved. * ----------------------------------------------------------------- * This is the header file for ISAT_LIB module, a computational * library with In Situ Adaptive Tabulation (ISAT) algorithm * routines. * ----------------------------------------------------------------- */ #ifndef __ISAT_LIB_H__ #define __ISAT_LIB_H__ #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include "../include/bst_lib.h" /* *------------------------------------------------------------ * structure for ISAT workspace * * last update: Oct 9, 2019 *------------------------------------------------------------ */ typedef struct isat_struct { bst_node *root; /* binary search tree root */ unsigned int lf; /* # of leaves */ unsigned int nd; /* # of nodes */ unsigned int add; /* # of adds */ unsigned int grw; /* # of grows */ unsigned int rtv; /* # of retrieves */ unsigned int dev; /* # of direct evaluations */ unsigned int hgt; /* tree height */ unsigned int maxleaves; /* max. # of leaves in the tree */ clock_t time_add; /* CPU clock spent by additions */ clock_t time_grw; /* CPU clock spent by growths */ clock_t time_rtv; /* CPU clock spent by retrieves */ clock_t time_dev; /* CPU clock spent by dir. eval. */ } isat_wrk; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ isat_wrk *isat_alloc(); void isat_free(void **isat_bl); int isat_bst_init(isat_wrk *isat); void isat_statistics(isat_wrk *isat); int isat_input(unsigned int *max_lf, double *etol); void isat_eoa_mtrx(gsl_matrix *A, double etol, gsl_matrix *L); double isat_lerror(gsl_vector *Rphi, gsl_vector *Rphi0, gsl_matrix *A, gsl_vector *phi, gsl_vector *phi0); int isat4(isat_wrk *isat_mem, void *cvode_mem, double etol, double t0, double delta_t, gsl_vector *phi, gsl_matrix *A, gsl_matrix *L, gsl_vector *Rphi); #endif /* __ISAT_LIB_H__ */
{ "alphanum_fraction": 0.4478912513, "avg_line_length": 27.5865384615, "ext": "h", "hexsha": "672de843b1ef764bc80556c09a3a4c8d1423bfdb", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-2.0/include/isat_lib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-2.0/include/isat_lib.h", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-2.0/include/isat_lib.h", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 631, "size": 2869 }
/* specfunc/bessel_i.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_bessel.h> #include "error.h" #include "bessel.h" /* i_{l+1}/i_l */ static int bessel_il_CF1(const int l, const double x, const double threshold, double * ratio) { const int kmax = 2000; double tk = 1.0; double sum = 1.0; double rhok = 0.0; int k; for(k=1; k<=kmax; k++) { double ak = (x/(2.0*l+1.0+2.0*k)) * (x/(2.0*l+3.0+2.0*k)); rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok)); tk *= rhok; sum += tk; if(fabs(tk/sum) < threshold) break; } *ratio = x/(2.0*l+3.0) * sum; if(k == kmax) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result) { double ax = fabs(x); /* CHECK_POINTER(result) */ if(x == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(ax < 0.2) { const double eax = exp(-ax); const double y = ax*ax; const double c1 = 1.0/6.0; const double c2 = 1.0/120.0; const double c3 = 1.0/5040.0; const double c4 = 1.0/362880.0; const double c5 = 1.0/39916800.0; const double sum = 1.0 + y*(c1 + y*(c2 + y*(c3 + y*(c4 + y*c5)))); result->val = eax * sum; result->err = 2.0 * GSL_DBL_EPSILON * result->val; } else if(ax < -0.5*GSL_LOG_DBL_EPSILON) { result->val = (1.0 - exp(-2.0*ax))/(2.0*ax); result->err = 2.0 * GSL_DBL_EPSILON * result->val; } else { result->val = 1.0/(2.0*ax); result->err = 2.0 * GSL_DBL_EPSILON * result->val; } return GSL_SUCCESS; } int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result) { double ax = fabs(x); /* CHECK_POINTER(result) */ if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(ax < 3.0*GSL_DBL_MIN) { UNDERFLOW_ERROR(result); } else if(ax < 0.25) { const double eax = exp(-ax); const double y = x*x; const double c1 = 1.0/10.0; const double c2 = 1.0/280.0; const double c3 = 1.0/15120.0; const double c4 = 1.0/1330560.0; const double c5 = 1.0/172972800.0; const double sum = 1.0 + y*(c1 + y*(c2 + y*(c3 + y*(c4 + y*c5)))); result->val = eax * x/3.0 * sum; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { double ex = exp(-2.0*ax); result->val = 0.5 * (ax*(1.0+ex) - (1.0-ex)) / (ax*ax); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); if(x < 0.0) result->val = -result->val; return GSL_SUCCESS; } } int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result) { double ax = fabs(x); /* CHECK_POINTER(result) */ if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(ax < 4.0*GSL_SQRT_DBL_MIN) { UNDERFLOW_ERROR(result); } else if(ax < 0.25) { const double y = x*x; const double c1 = 1.0/14.0; const double c2 = 1.0/504.0; const double c3 = 1.0/33264.0; const double c4 = 1.0/3459456.0; const double c5 = 1.0/518918400.0; const double sum = 1.0 + y*(c1 + y*(c2 + y*(c3 + y*(c4 + y*c5)))); const double pre = exp(-ax) * x*x/15.0; result->val = pre * sum; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { double ex = exp(-2.0*ax); double x2 = x*x; result->val = 0.5 * ((3.0+x2)*(1.0-ex) - 3.0*ax*(1.0+ex))/(ax*ax*ax); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result) { double sgn = 1.0; double ax = fabs(x); if(x < 0.0) { /* i_l(-x) = (-1)^l i_l(x) */ sgn = ( GSL_IS_ODD(l) ? -1.0 : 1.0 ); x = -x; } if(l < 0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = ( l == 0 ? 1.0 : 0.0 ); result->err = 0.0; return GSL_SUCCESS; } else if(l == 0) { gsl_sf_result il; int stat_il = gsl_sf_bessel_i0_scaled_e(x, &il); result->val = sgn * il.val; result->err = il.err; return stat_il; } else if(l == 1) { gsl_sf_result il; int stat_il = gsl_sf_bessel_i1_scaled_e(x, &il); result->val = sgn * il.val; result->err = il.err; return stat_il; } else if(l == 2) { gsl_sf_result il; int stat_il = gsl_sf_bessel_i2_scaled_e(x, &il); result->val = sgn * il.val; result->err = il.err; return stat_il; } else if(x*x < 10.0*(l+1.5)/M_E) { gsl_sf_result b; int stat = gsl_sf_bessel_IJ_taylor_e(l+0.5, x, 1, 50, GSL_DBL_EPSILON, &b); double pre = exp(-ax) * sqrt((0.5*M_PI)/x); result->val = sgn * pre * b.val; result->err = pre * b.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat; } else if(l < 150) { gsl_sf_result i0_scaled; int stat_i0 = gsl_sf_bessel_i0_scaled_e(ax, &i0_scaled); double rat; int stat_CF1 = bessel_il_CF1(l, ax, GSL_DBL_EPSILON, &rat); double iellp1 = rat * GSL_SQRT_DBL_MIN; double iell = GSL_SQRT_DBL_MIN; double iellm1; int ell; for(ell = l; ell >= 1; ell--) { iellm1 = iellp1 + (2*ell + 1)/x * iell; iellp1 = iell; iell = iellm1; } result->val = sgn * i0_scaled.val * (GSL_SQRT_DBL_MIN / iell); result->err = i0_scaled.err * (GSL_SQRT_DBL_MIN / iell); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_i0, stat_CF1); } else if(GSL_MIN(0.29/(l*l+1.0), 0.5/(l*l+1.0+x*x)) < 0.5*GSL_ROOT3_DBL_EPSILON) { int status = gsl_sf_bessel_Inu_scaled_asymp_unif_e(l + 0.5, x, result); double pre = sqrt((0.5*M_PI)/x); result->val *= sgn * pre; result->err *= pre; return status; } else { /* recurse down from safe values */ double rt_term = sqrt((0.5*M_PI)/x); const int LMAX = 2 + (int) (1.2 / GSL_ROOT6_DBL_EPSILON); gsl_sf_result r_iellp1; gsl_sf_result r_iell; int stat_a1 = gsl_sf_bessel_Inu_scaled_asymp_unif_e(LMAX + 1 + 0.5, x, &r_iellp1); int stat_a2 = gsl_sf_bessel_Inu_scaled_asymp_unif_e(LMAX + 0.5, x, &r_iell); double iellp1 = r_iellp1.val; double iell = r_iell.val; double iellm1 = 0.0; int ell; iellp1 *= rt_term; iell *= rt_term; for(ell = LMAX; ell >= l+1; ell--) { iellm1 = iellp1 + (2*ell + 1)/x * iell; iellp1 = iell; iell = iellm1; } result->val = sgn * iellm1; result->err = fabs(result->val)*(GSL_DBL_EPSILON + fabs(r_iellp1.err/r_iellp1.val) + fabs(r_iell.err/r_iell.val)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_a1, stat_a2); } } int gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array) { if(x == 0.0) { int ell; result_array[0] = 1.0; for (ell = lmax; ell >= 1; ell--) { result_array[ell] = 0.0; }; return GSL_SUCCESS; } else { int ell; gsl_sf_result r_iellp1; gsl_sf_result r_iell; int stat_0 = gsl_sf_bessel_il_scaled_e(lmax+1, x, &r_iellp1); int stat_1 = gsl_sf_bessel_il_scaled_e(lmax, x, &r_iell); double iellp1 = r_iellp1.val; double iell = r_iell.val; double iellm1; result_array[lmax] = iell; for(ell = lmax; ell >= 1; ell--) { iellm1 = iellp1 + (2*ell + 1)/x * iell; iellp1 = iell; iell = iellm1; result_array[ell-1] = iellm1; } return GSL_ERROR_SELECT_2(stat_0, stat_1); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_i0_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_i0_scaled_e(x, &result)); } double gsl_sf_bessel_i1_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_i1_scaled_e(x, &result)); } double gsl_sf_bessel_i2_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_i2_scaled_e(x, &result)); } double gsl_sf_bessel_il_scaled(const int l, const double x) { EVAL_RESULT(gsl_sf_bessel_il_scaled_e(l, x, &result)); }
{ "alphanum_fraction": 0.6036794858, "avg_line_length": 27.3424242424, "ext": "c", "hexsha": "2d39f2cef7905c98911230d31974fdc8b6c81ca6", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_i.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_i.c", "max_line_length": 119, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_i.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 3304, "size": 9023 }
/* * BSD 3-Clause License * * Copyright (c) 2018, mtezych * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CL_COMMAND_QUEUE #define CL_COMMAND_QUEUE #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #include <cl/Kernel.h> #include <cl/Event.h> #include <cl/Memory.h> #include <util/util.h> #include <gsl/span> #include <array> #include <vector> #include <cstddef> namespace cl { struct Context; struct Device; enum NDRange : cl_uint { Range1D = 1, Range2D = 2, Range3D = 3, }; struct Range { std::size_t offset; std::size_t size; }; enum class ExecMode : cl_command_queue_properties { InOrder = 0, OutOfOrder = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, }; enum class Profiling : cl_command_queue_properties { Enable = CL_QUEUE_PROFILING_ENABLE, Disable = 0, }; struct CommandQueue { cl_command_queue clCommandQueue; CommandQueue ( const Context& context, const Device& device, ExecMode execMode = ExecMode::InOrder, Profiling profiling = Profiling::Disable ); ~CommandQueue (); CommandQueue (CommandQueue&& commandQueue); CommandQueue (const CommandQueue& commandQueue) = delete; CommandQueue& operator = (CommandQueue&& commandQueue); CommandQueue& operator = (const CommandQueue& commandQueue) = delete; struct Properties { ExecMode execMode; Profiling profiling; }; enum class Info : cl_command_queue_info { ReferenceCount = CL_QUEUE_REFERENCE_COUNT, Properties = CL_QUEUE_PROPERTIES, }; template <Info info> auto GetInfo() const { auto infoSize = std::size_t { 0 }; auto result = clGetCommandQueueInfo ( clCommandQueue, util::enum_cast(info), 0, nullptr, &infoSize ); assert(result == CL_SUCCESS); auto infoBytes = std::vector<std::byte> { infoSize, std::byte { 0x00 } }; result = clGetCommandQueueInfo ( clCommandQueue, util::enum_cast(info), infoBytes.size(), infoBytes.data(), nullptr ); assert(result == CL_SUCCESS); return InfoResult<info>::FromBytes(infoBytes); } template <NDRange WorkDimension> Event EnqueueKernel ( const Kernel& kernel, const std::array<size_t, WorkDimension>& globalWorkSize, const std::array<size_t, WorkDimension>& localWorkSize, const std::vector<Event>& waitEvents ) { static_assert(sizeof(Event) == sizeof(cl_event)); const auto globalWorkOffset = std::array<size_t, WorkDimension> { }; auto signalEvent = cl_event { }; auto result = clEnqueueNDRangeKernel ( clCommandQueue, kernel.clKernel, WorkDimension, globalWorkOffset.data(), globalWorkSize.data(), localWorkSize.data(), static_cast<cl_uint>(waitEvents.size()), reinterpret_cast<const cl_event*>(util::data_or_null(waitEvents)), &signalEvent ); assert(result == CL_SUCCESS); return Event { signalEvent }; } template <typename ValueType> Event EnqueueReadBuffer ( const Memory<ValueType>& memory, const gsl::span<ValueType> buffer, const Range& range, const std::vector<Event>& waitEvents ) { assert(buffer.size() >= static_cast<std::ptrdiff_t>(range.size)); auto signalEvent = cl_event { }; auto result = clEnqueueReadBuffer ( clCommandQueue, memory.clMemory, cl_bool { CL_BLOCKING }, range.offset, sizeof(ValueType) * range.size, buffer.data(), static_cast<cl_uint>(waitEvents.size()), reinterpret_cast<const cl_event*>(util::data_or_null(waitEvents)), &signalEvent ); assert(result == CL_SUCCESS); return Event { signalEvent }; } private: template <Info info> struct InfoResult; }; template <> struct CommandQueue::InfoResult<CommandQueue::Info::ReferenceCount> { static cl_uint FromBytes (const std::vector<std::byte>& infoBytes); }; template <> struct CommandQueue::InfoResult<CommandQueue::Info::Properties> { static CommandQueue::Properties FromBytes (const std::vector<std::byte>& infoBytes); }; } #endif
{ "alphanum_fraction": 0.7143896671, "avg_line_length": 24.7612612613, "ext": "h", "hexsha": "bb6a0acd45839137d8bee1097dfd298cf493f87d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-07-14T23:16:23.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-21T00:31:17.000Z", "max_forks_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mtezych/cpp", "max_forks_repo_path": "cl/include/cl/CommandQueue.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mtezych/cpp", "max_issues_repo_path": "cl/include/cl/CommandQueue.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mtezych/cpp", "max_stars_repo_path": "cl/include/cl/CommandQueue.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1363, "size": 5497 }
/* segSiteHMM v. 0.1 !!! / / / Andrew Kern 3/14/07 */ #include "../hmm/hmm.h" #include "../hmm/adkGSL.h" #include "../hmm/popGenTools.h" #include "segSites.h" #include "segSiteHMM.h" #include <math.h> #include <assert.h> #include <string.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_min.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #define MAXSNPS 100000000 char modeFlag, *outfileName, smoothFlag; int snpNumber, maxSampleSize, states, verboseFlag = 0, fixedEmisFlag = 0, sampleSize; gsl_vector *sampleSizes, *piStart, *piEnd; struct snp data[MAXSNPS]; gsl_matrix *m, *sfsCounts, *emisMatrix; double gamma1, theta1; gsl_vector *gammas; double priorCons = 0; double omega = 0; int outputLevel = 0; int main(int argc, char *argv[]){ gsl_matrix *alphas, *betas, *posts, *logPosts; gsl_vector *vits, *locs, *include, *include2; gsl_matrix *emisLogs; double score1, sum, pFor; HMM *h; FILE *outfile; int i, j, **elements, elementCount, transitionPowerFlag; printf("segSiteHMM v0.3 -- thank you for playing thermonuclear war\n"); printf("getting parameters/data\n"); getParameters(argc,argv); //find max sampleSize maxSampleSize = 0; for(j = 0; j < snpNumber; j++){ if (data[j].n > maxSampleSize){ maxSampleSize = data[j].n; } } //transition gaps? transitionPowerFlag = 0; //make sampleSize vector and summarize sfs sampleSizes = sampleSizeVector(data,snpNumber,maxSampleSize); sfsCounts = summarizeSFSBool(maxSampleSize, data, snpNumber); //was smoothing used? if(smoothFlag == 'f'){ //init with equal starting probs sum = 1.0 / states; for (i = 0; i < states; i++){ gsl_vector_set(piStart, i, sum); gsl_vector_set(piEnd, i, sum); } } else if(smoothFlag == 's'){ //set start and end probs based on smoothing gsl_vector_set(piStart, 1, priorCons); gsl_vector_set(piStart, 0, 1.0 - gsl_vector_get(piStart, 1)); gsl_vector_set(piEnd, 0, gsl_vector_get(piStart,0)); gsl_vector_set(piEnd, 1, gsl_vector_get(piStart,1)); //define transition probs based on omega and gamma gsl_matrix_set(m, 1, 0, 1.0 / omega); gsl_matrix_set(m, 1, 1, 1.0 - gsl_matrix_get(m, 1, 0)); gsl_matrix_set(m, 0, 1, (gsl_matrix_get(m, 1, 0) / gsl_vector_get(piStart, 0)) \ - gsl_matrix_get(m, 1,0)); gsl_matrix_set(m, 0, 0, 1.0 - gsl_matrix_get(m, 0, 1)); } printf("path is %d SNPs long\n",snpNumber); locs = gsl_vector_alloc(snpNumber); //fill up locs vector for use in calculating transition powers for(i = 0; i < snpNumber; i++){ gsl_vector_set(locs, i, data[i].pos); } //initialize HMM printf("initializing model\n"); h = newHMM(m, piStart,piEnd,locs); initHMM(h); printHMM(h); switch(modeFlag){ case 't' : printf("training mode\nEM iterations follow:\n"); fflush(stdout); emAlg(h, gammas,snpNumber, data, transitionPowerFlag); //output selection coefficient strcat(outfileName,".alphas"); outfile = fopen(outfileName, "w"); gsl_vector_fprintf(outfile,gammas,"%f"); fclose(outfile); //output transition matrix strcat(outfileName,".trainedTransMat"); printTransitions(h, outfileName); break; case 'b' : printf("train and decode mode\nEM iterations follow:\n"); fflush(stdout); emAlg(h, gammas,snpNumber, data, transitionPowerFlag); if(outputLevel>0){ //output selection coefficient strcat(outfileName,".alphas"); outfile = fopen(outfileName, "w"); fprintf(outfile,"%f",gsl_vector_get(gammas,1)); fclose(outfile); //output transition matrix strcat(outfileName,".trainedTransMat"); printTransitions(h, outfileName); } strcat(outfileName,".decoding"); printf("Viterbi decoding mode\nelement predicition will be stored in a file called \"%s\"\nPosterior Probs and Viterbi calls follow:\n",outfileName); vits = gsl_vector_alloc(snpNumber); if(!fixedEmisFlag) { emisLogs = gsl_matrix_alloc(h->nstates, snpNumber); calculateEmissions(h, emisLogs, gammas, theta1, snpNumber, data); } alphas = gsl_matrix_alloc(h->nstates,snpNumber); betas = gsl_matrix_alloc(h->nstates,snpNumber); posts = gsl_matrix_alloc(h->nstates, snpNumber); logPosts = gsl_matrix_alloc(h->nstates, snpNumber); pFor = forwardAlg(h, alphas, emisLogs, snpNumber, transitionPowerFlag); backwardAlg(h, betas, emisLogs, snpNumber, transitionPowerFlag); posteriorProbsReduced(h, posts, pFor, alphas, betas, emisLogs, snpNumber, transitionPowerFlag); viterbi(h, vits, emisLogs, snpNumber, transitionPowerFlag); //print out likelihood printf("Likelihood = %lf\n",pFor); if (outputLevel > 0){ //output posteriors and viterbi calls outfile = fopen(outfileName, "w"); for(i = 0; i < emisLogs->size2; i++){ fprintf(outfile,"%d",(int)gsl_vector_get(h->otherData,i)); for(j = 0; j < h->nstates; j++){ fprintf(outfile,"\t%lf",gsl_matrix_get(posts, j, i)); } fprintf(outfile,"\t%d\n",(int)gsl_vector_get(vits, i)); } fclose(outfile); } //score elements strcat(outfileName,".elements"); scoreElements(h, emisLogs, vits, outfileName, transitionPowerFlag); break; case 'v' : printf("Viterbi decoding mode\nelement predicition will be stored in a file called \"%s\"\nPosterior Probs and Viterbi calls follow:\n",outfileName); vits = gsl_vector_alloc(snpNumber); emisLogs = gsl_matrix_alloc(h->nstates, snpNumber); if (fixedEmisFlag) { initializeEmissions(emisLogs, emisMatrix, snpNumber, data); } else { calculateEmissions(h, emisLogs, gammas, theta1, snpNumber, data); } alphas = gsl_matrix_alloc(h->nstates,snpNumber); betas = gsl_matrix_alloc(h->nstates,snpNumber); posts = gsl_matrix_alloc(h->nstates, snpNumber); logPosts = gsl_matrix_alloc(h->nstates, snpNumber); pFor = forwardAlg(h, alphas, emisLogs, snpNumber, transitionPowerFlag); backwardAlg(h, betas, emisLogs, snpNumber, transitionPowerFlag); posteriorProbsReduced(h, posts, pFor, alphas, betas, emisLogs, snpNumber, transitionPowerFlag); viterbi(h, vits, emisLogs, snpNumber, transitionPowerFlag); //print out likelihood printf("Likelihood = %lf\n",pFor); if(outputLevel > 0){ //output posteriors and viterbi calls outfile = fopen("snpPosts", "w"); for(i = 0; i < emisLogs->size2; i++){ fprintf(outfile,"%d",(int)gsl_vector_get(h->otherData,i)); for(j = 0; j < h->nstates; j++){ fprintf(outfile,"\t%lf",gsl_matrix_get(posts, j, i)); } fprintf(outfile,"\t%d\n",(int)gsl_vector_get(vits, i)); } fclose(outfile); scoreElements(h, emisLogs, vits, outfileName, transitionPowerFlag); break; } } freeHMM(h); return 0; } void usage(){ fprintf(stderr,"usage: pgHMM - population genetic HMMs\nrun modes:\n\t-t train mode -- EM training for model\n\t-v viterbi decoding mode\n\t-b both train and decode\n\ninput control\n\t-S stateNumber\n\t-d dataFile\n\t-p transitionMatrix\n\t-s startProbs\n\t-e endProbs\n\t-g prior probability of being in selected state\n\t-E emissionMatrixFile sampleSize -- specifies a file containing an SFS for each state (including frequencies of monomorphic sites); entires must sum to 1, and data must have constant sampleSize\n\t-w omega smoothing parameter (note either transitionMatrix or gamma and omega need to be defined)\n\t-a beta1 beta2 -- value for selected classes\n\t-u 4Nu initial value\n\t-o outfile name (trained matrix or elements)\n\t-V verbose\n\t-O output level (default= 0)\n"); exit(1); } /* sets the parameters/run mode and then opens data */ void getParameters(int argc, char *argv[]){ FILE *infile; int i, j, n, args; long int pos; if (argc < 2){ usage(); } else{ args = 1; while(args < argc){ switch(argv[args][1]){ case 't' : /* train mode? */ modeFlag = 't'; smoothFlag = 'f'; break; case 'v' : /* viterbi decode */ modeFlag = 'v'; smoothFlag = 'f'; break; case 'b' : /*both train and decode */ modeFlag = 'b'; smoothFlag = 'f'; break; case 'a' : /*set alphas for selected class */ for(j = 1; j < states; j++){ gsl_vector_set(gammas,j,atof(argv[++args])); } break; case 'u' : //set theta theta1 = atof(argv[++args]); break; case 'O' : //set outputLevel outputLevel = atoi(argv[++args]); break; case 'S' : //set state number states = atoi(argv[++args]); m = gsl_matrix_alloc(states,states); gsl_matrix_set_zero(m); //initialize selection params and allocate stuff gammas = gsl_vector_alloc(states); piStart = gsl_vector_alloc(states); piEnd = gsl_vector_alloc(states); break; case 'd' : /* open data file, errors? */ infile = fopen(argv[++args], "r"); printf("%s is datafile\n",argv[args]); if (infile == NULL){ fprintf(stderr,"Error opening infile! ARRRRR!!!!\n"); exit(1); } /* go through infile and get snp info; expect pos, i, n */ snpNumber = 0; maxSampleSize = 0; while (fscanf(infile, "%ld\t%d\t%d", &pos, &i, &n) != EOF){ data[snpNumber].pos = pos; data[snpNumber].i = i; data[snpNumber].n = n; snpNumber++; if(n > maxSampleSize){ maxSampleSize = n; } } fclose(infile); break; //either whole transition matrix needs to be defined or gamma and omega case 'p': //get transition matrix infile = fopen(argv[++args], "r"); if (infile == NULL){ fprintf(stderr,"Error opening matrixfile! ARRRRR!!!!\n"); exit(1); } printf("%s is matrixfile\n",argv[args]); gsl_matrix_fscanf(infile, m); //gsl_matrix_fprintf(stdout,m,"%f"); fclose(infile); break; case's': //get start vector infile = fopen(argv[++args], "r"); if (infile == NULL){ fprintf(stderr,"Error opening start prob. file! ARRRRR!!!!\n"); exit(1); } printf("%s is start prob. file\n",argv[args]); gsl_vector_fscanf(infile, piStart); fclose(infile); smoothFlag = 'piSet'; break; case'e': //get end vector infile = fopen(argv[++args], "r"); if (infile == NULL){ fprintf(stderr,"Error opening end prob. file! ARRRRR!!!!\n"); exit(1); } printf("%s is end prob. file\n",argv[args]); gsl_vector_fscanf(infile, piEnd); smoothFlag = 'piSet'; fclose(infile); break; case 'E': //get emission matrix infile = fopen(argv[++args],"r"); sampleSize = atoi(argv[++args]); if (infile == NULL){ fprintf(stderr,"Error opening end emission prob. file! ARRRRR!!!!\n"); exit(1); } printf("%s is emission prob. file; sampleSize=%d\n",argv[args-1],sampleSize); emisMatrix = gsl_matrix_alloc(states,sampleSize); gsl_matrix_fscanf(infile, emisMatrix); printf("finished reading emission prob. matrix\n"); for (i=0;i<states;i++) { for (j=0;j<sampleSize;j++) { printf("%f ",gsl_matrix_get(emisMatrix,i,j)); } printf("\n"); } fixedEmisFlag = 1; fclose(infile); break; case 'g': //get gamma for transitions priorCons = atof(argv[++args]); printf("prior probability of conservation defined\n"); break; case 'w': //get omega for transitions omega = atof(argv[++args]); smoothFlag = 's'; break; case 'o': //get outfile name outfileName = argv[++args]; break; case 'V': //verbose training verboseFlag = 1; break; } args++; } } if (omega == 0 && gsl_matrix_get(m, 0, 0) == 0){ usage(); exit(1); } } /* calculateEmissions- this fills up a matrix of Nstates * L observations where the elements are the computed allele frequency probabilities drawn from the stationary distribution of Wright's genic selection model. The population is assumed to be at equilibrium and all snps are considered to be independent draws from the same distributions */ void calculateEmissions(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *gammas, double theta,\ int snpNumber, struct snp theData[MAXSNPS]){ int i, j; gsl_matrix *probs; gsl_vector *pVector; //error check assert(emisLogs->size1 == hmm->nstates); assert(emisLogs->size2 == snpNumber); //alloc pVector pVector = gsl_vector_alloc(hmm->nstates); probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize); //calculate emissions and fill up matrix for(i = 0; i < emisLogs->size1; i++){ gsl_vector_set(pVector,0,gsl_vector_get(gammas,i)); gsl_vector_set(pVector,1,theta); //make prob matrix (note this is in logs) siteProbMatrix(probs,pVector,maxSampleSize, sampleSizes); //go through snps, calculate probs for(j=0; j < emisLogs->size2; j++){ gsl_matrix_set(emisLogs, i, j, gsl_matrix_get(probs, data[j].n, data[j].i)); } } gsl_vector_free(pVector); gsl_matrix_free(probs); } void initializeEmissions(gsl_matrix *emisLogs, gsl_matrix *emisMatrix, int snpNumber, struct snp theData[MAXSNPS]){ int i, j; int freq; double logProb; //calculate emissions and fill up matrix for(i = 0; i < emisLogs->size1; i++){ for(j=0; j < emisLogs->size2; j++){ //need to get the allele frequency here, and then extract the probs from the corresponding emisMatrix elements freq = data[j].i; logProb = log(gsl_matrix_get(emisMatrix, i, freq)); //if (emisLogs->size2 - j <= 10) //{ // fprintf(stderr,"emission probability for state %d, position %d: %f; log=%f\n",i,j,gsl_matrix_get(emisMatrix, i, freq),logProb); //} gsl_matrix_set(emisLogs, i, j, logProb); } } } /* emAlg- this is mean to train the emissions (the parameter gamma) using the EM algorithm. it returns the trained up gamma value */ double emAlg(HMM *hmm, gsl_vector *startGammas, int snpNumber, struct snp theData[MAXSNPS], int transitionPowerFlag){ gsl_matrix *alphas, *betas, *posts, *logPosts, *emisLogs, *tempTrans, *powTrans, **jpMatArray; gsl_vector *rowSums, *estimateVector; double lastLik, newLik, delta, dummy, val, pFor, pBack; gsl_function likFunc; struct my_jointLik_params paramSet; int i, j, k, count; //initialize and allocate emisLogs = gsl_matrix_alloc(hmm->nstates,snpNumber); if(fixedEmisFlag) { initializeEmissions(emisLogs, emisMatrix, snpNumber, theData); } else { calculateEmissions(hmm, emisLogs, startGammas, theta1, snpNumber, theData); } posts = gsl_matrix_alloc(hmm->nstates,snpNumber); logPosts = gsl_matrix_alloc(hmm->nstates,snpNumber); alphas = gsl_matrix_alloc(hmm->nstates,snpNumber); betas = gsl_matrix_alloc(hmm->nstates,snpNumber); rowSums = gsl_vector_alloc(hmm->nstates); delta = 1e-4; newLik = 1 ; lastLik = 0; tempTrans = gsl_matrix_alloc(hmm->nstates,hmm->nstates); //make jpMatArray jpMatArray = malloc(sizeof(gsl_matrix) * snpNumber); for(i = 0; i < snpNumber; i++){ //each is nstate x nstate transition matrix jpMatArray[i] = gsl_matrix_alloc(hmm->nstates,hmm->nstates); gsl_matrix_set_all(jpMatArray[i],0.0); } //setup parameter estimate vector estimateVector = gsl_vector_alloc(hmm->nstates); // 1 mutation parameter, n-1 selection parameters gsl_vector_set(estimateVector,0,theta1); for(i = 1; i < hmm->nstates; i++){ gsl_vector_set(estimateVector,i,gsl_vector_get(startGammas,i)); } //initializing joint lik params paramSet.data = theData; paramSet.snpNumber = snpNumber; paramSet.nstates = hmm->nstates; paramSet.maxSampleSize = maxSampleSize; paramSet.sampleSizeVector = sampleSizes; paramSet.sfsBools = sfsCounts; paramSet.startingPoint = estimateVector; //main loop count = 0; while ( fabs(newLik - lastLik) > delta){ transitionPowerFlag = 0; //E step //set lastLik to newLik dummy = newLik; lastLik = dummy; //recalculate emissions if (!fixedEmisFlag) { calculateEmissions(hmm, emisLogs, startGammas, theta1, snpNumber, theData); } //run forwards/backwards and calculate posterior probs pFor = forwardAlg(hmm, alphas, emisLogs, snpNumber, transitionPowerFlag); pBack = backwardAlg(hmm, betas, emisLogs, snpNumber,transitionPowerFlag); //print current status printf("%d\tlik= %f\t\ttheta_hat= %f", count,pFor,theta1); for(i = 1; i < hmm->nstates; i++){ printf("\tgamma_hat= %f",gsl_vector_get(startGammas, i)); } printf("\n"); fflush(stdout); //check probs; calculate posterior probs; set "weights" assert(fabs(pFor - pBack) < 0.1); posteriorProbsReduced(hmm, posts, pFor, alphas, betas, emisLogs, snpNumber,transitionPowerFlag); posteriorProbsReducedLog(hmm, logPosts, pFor, alphas, betas, emisLogs, snpNumber,transitionPowerFlag); //reestimate the new shiny way reestimateTransitions(hmm, posts, jpMatArray, pFor, alphas, betas, emisLogs, snpNumber,transitionPowerFlag); //update start and end vectors based on posteriors for(j = 0; j < hmm->nstates; j++){ gsl_vector_set(hmm->piStart,j,gsl_matrix_get(posts,j,0)); gsl_vector_set(hmm->piEnd,j,gsl_matrix_get(posts,j,snpNumber - 1)); gsl_vector_set(hmm->piStart_scores, j, log(gsl_vector_get(hmm->piStart,j))); gsl_vector_set(hmm->piEnd_scores, j, log(gsl_vector_get(hmm->piEnd,j))); } // M step for other params if (!fixedEmisFlag) { paramSet.posts = posts; paramSet.startingPoint = estimateVector; likFunc.params = &paramSet; jointMLEstNState(estimateVector, &newLik, &paramSet); //maximization theta1 = gsl_vector_get(estimateVector,0); for(j = 1; j < hmm->nstates; j++){ gsl_vector_set(startGammas,j, gsl_vector_get(estimateVector, j)); } } newLik = pFor; count += 1; if (verboseFlag) printHMM(hmm); } //free jpMatArray for(i = 0; i < snpNumber; i++){ //each is nstate x nstate transition matrix gsl_matrix_free(jpMatArray[i]); } //free(jpMatArray); gsl_matrix_free(emisLogs); gsl_matrix_free(posts); gsl_matrix_free(alphas); gsl_matrix_free(betas); gsl_vector_free(rowSums); gsl_vector_free(estimateVector); printHMM(hmm); return(gsl_vector_get(startGammas,1)); } /*This returns an array of arrays of ints which indicate the Viterbi decoded elements from the model. The arrays returned are in the format startIndex, stopIndex */ int **elementArray(gsl_vector *vits, double state, int *pCount){ int i, **array, elementCount, size, last; //allocate storage for element arrays array = malloc(vits->size * sizeof(int *)); for(i = 0; i < vits->size; i++){ array[i] = malloc(3 * sizeof(int)); } //set last to initial obs elementCount = 0; size = state; //this is the first one we're about to find! //find first occurence of state for(last = 0; last < vits->size; last++){ if (gsl_vector_get(vits,last) == state){ break; } } //iterate through Viterbi's, find runs for(i = last+1; i < vits->size; i++){ if (gsl_vector_get(vits,last) == gsl_vector_get(vits,i)){ if (size == 0){ //new one? last = i; } size++; if ( i == vits->size - 1 && size > 1){ array[elementCount][0] = last; array[elementCount][1] = i; elementCount++; } } else{ if (size > 1){ array[elementCount][0] = last; array[elementCount][1] = i - 1; array[elementCount][2] = size; elementCount++; size = 0; last = i - 1 ; } else{ size = 0; } } } *pCount = elementCount; return(array); } void scoreElements(HMM *h, gsl_matrix *emisLogs, gsl_matrix *vits, char *outfileName, int transitionPowerFlag){ gsl_vector *include, *include2; FILE *outfile; int elementCount, **elements, i, j; double score1; //open file to print to outfile = fopen(outfileName, "w"); if (outfile == NULL){ fprintf(stderr,"Error opening outfile! ARRRRR!!!!\n"); exit(1); } //print header fprintf(outfile,"state\tstart\tstop\tlog_odds_score\tlength\n"); //alloc state inclusion vectors include = gsl_vector_alloc(h->nstates); include2 = gsl_vector_alloc(h->nstates); //iterate across states for(j = 0; j < h->nstates; j++){ //get state elements from Viterbi elementCount = 0; elements = elementArray(vits, j, &elementCount); //set up state sets for element scoring gsl_vector_set_all(include,0); gsl_vector_set(include, j, 1); gsl_vector_set_all(include2,1); gsl_vector_set(include2, j, 0); //score elements for(i=0; i < elementCount; i++){ score1 = hmm_subpath_log_odds(h, emisLogs, include,include2, elements[i][0], \ elements[i][1] - elements[i][0] + 1 , transitionPowerFlag); fprintf(outfile,"%d\t%d\t%d\t%f\t%d\n",j,(int) gsl_vector_get(h->otherData,elements[i][0]), \ (int) gsl_vector_get(h->otherData,elements[i][1]),score1, (int) elements[i][2]); free(elements[i]); } free(elements); } fclose(outfile); }
{ "alphanum_fraction": 0.6641304865, "avg_line_length": 31.3865671642, "ext": "c", "hexsha": "5ae2dfb5bac2a8f163faabc8bc7568389807f670", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "segSiteHMM/segSiteHMM3.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_path": "segSiteHMM/segSiteHMM3.c", "max_line_length": 793, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "segSiteHMM/segSiteHMM3.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6196, "size": 21029 }
/** * * @file pcunmqr_blgtrd.c * * PLASMA auxiliary routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Azzam Haidar * @date 2011-05-15 * @generated c Tue Jan 7 11:45:13 2014 * **/ #include <lapacke.h> #include <cblas.h> #include "common.h" #undef REAL #define COMPLEX #define E(_m, _n) (E + (_m) + LDE * (_n) ) #define V(_m) (V + (_m)) #define T(_m) (T + (_m)) #define TAU(_m) (TAU + (_m)) /*************************************************************************** * Parallel apply Q2 from bulgechasing matrices - static scheduling * Lower case is treated **/ /* * side == PlasmaLeft: * meaning apply E = Q*E = (q_1*q_2*.....*q_n) * E ==> so * traverse Vs in reverse order (forward) from q_n to q_1 Also * E is splitten by block of col over cores because each apply * consist in a block of row (horizontal block) */ /* * side == PlasmaRight: * meaning apply E = E*Q = E * (q_1*q_2*.....*q_n) ==> so * traverse Vs in normal order (forward) from q_1 to q_n Also * E is splitten by block of row over core because each apply * consist in a block of col (vertical block) */ /***************************************************************************/ void plasma_pcunmqr_blgtrd(plasma_context_t *plasma) { int my_core_id = PLASMA_RANK; int cores_num = plasma->world_size; /*===========================*/ int N, NB, NE, LDE, Vblksiz, WANTZ; PLASMA_enum side; PLASMA_enum trans; PLASMA_Complex32_t *V; PLASMA_Complex32_t *T; PLASMA_Complex32_t *TAU; PLASMA_Complex32_t *E; PLASMA_sequence *sequence; PLASMA_request *request; /*=========================== * local variables *===========================*/ PLASMA_Complex32_t *WORK; int LDT, LDV; int Vm, Vn, mt, nt; int myrow, mycol, blkj, blki; int firstrow, nbcolinvolvd; int blkid, vpos, taupos, tpos; int chunkid, nbchunk, colpercore, corest, corelen, len, col; int coreid, allcoresnb, maxrequiredcores; int lchunkid, rchunkid, halfchunk, nbportion, sw; int LWORK; int standalonework = 0 ; int versionL, versionR; plasma_unpack_args_14(side, trans, N, NB, NE, Vblksiz, WANTZ, V, T, TAU, E, LDE, sequence, request); if (sequence->status != PLASMA_SUCCESS) return; /* Quick return */ if ( N == 0 ) { return; } if ( NB == 0 ) { return; } if ( NE == 0 ) { return; } /* ========================================== * some infor for developer * Initialisation and checking nb of cores * ==========================================*/ /* we have to 2 algo for left (113 114) and 2 algo for right (91 92) * which correspond to versionL versionR. * They ae very similar (detail explained in tech report and matlab code) * however version 114 and 92 improve locality. * while version 113 is used in case WNATZ=1 (construct Q2) which allow * the construction to be done in an optimized way taking into * consideration that the matrix is Identity so making less flops. * */ versionL = 113; versionR = 92; LDT = Vblksiz; LDV = NB+Vblksiz-1; /* use colpercore = N/cores_num; :if i want to split E into * cores_num chunk so I will have large chunk for each core. * However I prefer to split E into chunk of small size where * I guarantee that blas3 occur and the size of chunk remain into * cache, I think it is better. than I will have different chunk of * small size per core and i will do each chunk till the end and * then move to the second one for data locality * * version v1: for each chunck it apply all the V's then move to * the other chunck. the locality here inside each * chunck meaning that thread "t" apply V_k then move * to V_k+1 which overlap with V_k meaning that the * E_k+1 overlap with E_k. so here is the * locality however thread t had to read V_k+1 and * T_k+1 at each apply. note that all thread if they * run at same speed they might reading the same V_k * and T_k at the same time. * * version v2: for each V_k and T_k thread t apply those V_k and * T_k to E_k for all its chunck, then move to V_k+1 * T_k+1 and apply them to E_k+1 on all the chunck, * and so on. the difference is that, thread keep V_k * and T_K while move over the E_k. * both version look like similar in perf. * * THIS IS v1 CODE * */ if(WANTZ==1) colpercore = plasma_ceildiv(NE,2*cores_num); else colpercore = plasma_ceildiv(NE,cores_num); if(colpercore>1000) colpercore = plasma_ceildiv(colpercore,10); else if(colpercore>800) colpercore = plasma_ceildiv(colpercore,8); else if(colpercore>600) colpercore = plasma_ceildiv(colpercore,6); else if(colpercore>400) colpercore = plasma_ceildiv(colpercore,4); else if(colpercore>200) colpercore = plasma_ceildiv(colpercore,2); if(colpercore>200) colpercore=120; if(colpercore<30) colpercore=32; /*colpercore = N make the code sequential running on thread=0;*/ nbchunk = plasma_ceildiv(NE, colpercore); allcoresnb = cores_num; maxrequiredcores = nbchunk; if( maxrequiredcores < 1 ) maxrequiredcores = 1; if(allcoresnb > maxrequiredcores) allcoresnb = maxrequiredcores; #if defined (ENABLE_DEBUG) if(my_core_id==0) printf(" APPLY Q_v1 parallel with threads %d nbchunk %d colpercore %d N %d NB %d Vblksiz %d SIDE %c TRANS %c versionL %d versionR %d WANTZ %d \n", cores_num,nbchunk,colpercore,N,NB,Vblksiz,lapack_const(side),lapack_const(trans),versionL,versionR,WANTZ); #endif /* ========================================= * case NB = 1 special case. * just make the element real for complex * ========================================= */ if ( NB == 1 ) { /* NOTE in CASE USED STANDALONE FUNCTION * In COMPLEX matrix Z need to be scaled by the TAU * generated during the make off-diagonal elements real */ /* * In case where the first stage has been done we are sure * that all element of E are real so no need to go through * NB=1. However in case where this function need to be used * for only band matrices meaning only stage2 has been called * then it require to make all off-diagonal elements real and * so remove the return from here and from the bulgechasing * function */ if(WANTZ==1){ PLASMA_Complex32_t zone = 1.0; memset(E, 0, LDE*N*sizeof(PLASMA_Complex32_t)); for(sw=0; sw<NE; sw++) E[sw+sw*LDE] = zone; } if(standalonework==0){ return; } else{ #ifdef COMPLEX for (chunkid = 0; chunkid<nbchunk; chunkid++) { coreid = chunkid%allcoresnb; corest = chunkid*colpercore; corelen = min(colpercore, (NE-(chunkid*colpercore))); if( my_core_id==coreid ){ if( side==PlasmaLeft ){ for (mycol =1; mycol<NE; mycol++){ cblas_cscal(corelen, TAU(mycol), E(mycol, corest), LDE); } }else{ PLASMA_Complex32_t ztmp; /*Upper case need to be checked*/ for (mycol = corest; mycol<corest+corelen; mycol++){ ztmp = conjf(*TAU(mycol)); cblas_cscal(N, &ztmp, E(0,mycol), 1); } } } } #endif return; } } /* ========================================= * case NB >1 main code * ========================================= */ LWORK = 2*colpercore*max(Vblksiz,64); WORK = (PLASMA_Complex32_t*) plasma_private_alloc(plasma, LWORK, PlasmaComplexFloat); /* WANTZ = 1 meaning E is IDENTITY so form Q using optimized update. * So we use the reverse order from small q to large one, * so from q_n to q_1 so Left update to Identity. * Use version 113 because in 114 we need to update the whole matrix and not in icreasing order. * WANTZ = 2 meaning E is a full matrix and need to be updated from Left or Right so use normal update * */ if ( WANTZ==1 ) { versionL = 113; halfchunk = plasma_ceildiv(nbchunk,2); for (lchunkid = 0; lchunkid<halfchunk; lchunkid++) { rchunkid = (nbchunk-1) - lchunkid; nbportion = lchunkid == rchunkid ? 1 : 2; /* sw is the switch between left and right side chunk * it is used to have same load distribution of work */ for (sw = 0; sw<nbportion; sw++) { chunkid = sw == 0 ? lchunkid : rchunkid; coreid = lchunkid%allcoresnb; corest = chunkid*colpercore; corelen = min(colpercore, (NE-(chunkid*colpercore))); if( my_core_id == coreid ) { /* * Version 113: * loop over the block_col (nt) and for each find the * number of tiles (mt) in this block_col. then loop over mt, find * the size of the V's(Vm,Vn) and apply it to the corresponding * portion of E. */ nt = plasma_ceildiv((N-1),Vblksiz); for (blkj=nt-1; blkj>=0; blkj--) { /* the index of the first row on the top of block (blkj) */ firstrow = blkj * Vblksiz + 1; /*find the number of tile for this block */ if( blkj == nt-1 ) mt = plasma_ceildiv( N - firstrow, NB); else mt = plasma_ceildiv( N - (firstrow+1), NB); /*loop over the tiles find the size of the Vs and apply it */ for (blki=mt; blki>0; blki--) { /*calculate the size of each losange of Vs= (Vm,Vn)*/ myrow = firstrow + (mt-blki)*NB; mycol = blkj*Vblksiz; Vm = min( NB+Vblksiz-1, N-myrow); if( ( blkj == nt-1 ) && ( blki == mt ) ){ Vn = min (Vblksiz, Vm); } else { Vn = min (Vblksiz, Vm-1); } /*calculate the pointer to the Vs and the Ts. * Note that Vs and Ts have special storage done * by the bulgechasing function*/ findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid); if((Vm>0)&&(Vn>0)){ col = max(mycol,corest); len = corelen - (col-corest); if(side==PlasmaLeft){ if( len > 0 ) CORE_clarfb_gemm( side, trans, PlasmaForward, PlasmaColumnwise, Vm, len, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,col), LDE, WORK, len); } else{ if( len > 0 ) CORE_clarfb_gemm( side, trans, PlasmaForward, PlasmaColumnwise, len, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(col, myrow), LDE, WORK, len); } } } } } /* END my_core_id=coreid */ } /* END of sw */ } /* END loop over the chunk */ } /* END if WANTZ=1 */ else{ /* * WANTZ != 1 */ for (chunkid = 0; chunkid<nbchunk; chunkid++) { coreid = chunkid%allcoresnb; corest = chunkid*colpercore; corelen = min(colpercore, (NE-(chunkid*colpercore))); if(corelen < 0) corelen = 0; if( my_core_id == coreid ) { /* * PlasmaLeft */ //if( side == PlasmaLeft ) { if( versionL == 113 ) { /* * Version 113: * loop over the block_col (nt) and for each find the * number of tiles (mt) in this block_col. then loop over mt, find * the size of the V's(Vm,Vn) and apply it to the corresponding * portion of E. */ if( versionL == 113 ) { nt = plasma_ceildiv((N-1),Vblksiz); for (blkj=nt-1; blkj>=0; blkj--) { /* the index of the first row on the top of block (blkj) */ firstrow = blkj * Vblksiz + 1; /*find the number of tile for this block */ if( blkj == nt-1 ) mt = plasma_ceildiv( N - firstrow, NB); else mt = plasma_ceildiv( N - (firstrow+1), NB); /*loop over the tiles find the size of the Vs and apply it */ for (blki=mt; blki>0; blki--) { /*calculate the size of each losange of Vs= (Vm,Vn)*/ myrow = firstrow + (mt-blki)*NB; mycol = blkj*Vblksiz; Vm = min( NB+Vblksiz-1, N-myrow); if( ( blkj == nt-1 ) && ( blki == mt ) ){ Vn = min (Vblksiz, Vm); } else { Vn = min (Vblksiz, Vm-1); } /*calculate the pointer to the Vs and the Ts. * Note that Vs and Ts have special storage done * by the bulgechasing function*/ findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid); if((Vm>0)&&(Vn>0)){ if( side == PlasmaLeft ){ CORE_clarfb_gemm( PlasmaLeft, trans, PlasmaForward, PlasmaColumnwise, Vm, corelen, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,corest), LDE, WORK, corelen); }else{ CORE_clarfb_gemm( PlasmaRight, trans, PlasmaForward, PlasmaColumnwise, corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest, myrow), LDE, WORK, corelen); } } } } } /* * Version 114: * loop over the block_row (mt) and for each find diagonally the * number of tiles (nt) in this block_row. then loop over nt, find * the size of the V's(Vm,Vn) and apply it to the corresponding * portion of E. */ else { mt = plasma_ceildiv((N-1),NB); for (blki = mt; blki>0; blki--) { /* nbcolinvolvd = number of column corresponding to this block_row (blki) */ nbcolinvolvd = min(N-1, blki*NB); /*find the number of tile for this block (diagonal row of tiles) */ nt = plasma_ceildiv(nbcolinvolvd,Vblksiz); /*loop over the tiles find the size of the Vs and apply it */ for (blkj = nt-1; blkj>=0; blkj--) { /* the index of the first row of the first col meaning * the block on the top left (blki) */ firstrow = (mt-blki)*NB+1; /*calculate the size of each losange of Vs= (Vm,Vn)*/ myrow = firstrow + blkj*Vblksiz; mycol = blkj*Vblksiz; Vm = min( NB+Vblksiz-1, N-myrow); if( ( blkj == nt-1 ) && ( blki == mt ) ){ Vn = min (Vblksiz, Vm); }else{ Vn = min (Vblksiz, Vm-1); } /*calculate the pointer to the Vs and the Ts. * Note that Vs and Ts have special storage done * by the bulgechasing function*/ findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid); if((Vm>0)&&(Vn>0)) { CORE_clarfb_gemm( PlasmaLeft, trans, PlasmaForward, PlasmaColumnwise, Vm, corelen, Vn, V(vpos), LDV, T(tpos), LDT, E(myrow,corest), LDE, WORK, corelen); } } } } } /* * PlasmaRight */ else { /* * Version 91: */ if( versionR == 91 ) { nt = plasma_ceildiv((N-1),Vblksiz); for (blkj=0; blkj<nt; blkj++) { /* the index of the first myrow on the top of block (blkj) */ firstrow = blkj * Vblksiz + 1; /*find the number of tile for this block */ if( blkj == nt-1 ) mt = plasma_ceildiv( N - firstrow, NB); else mt = plasma_ceildiv( N - (firstrow+1), NB); /*loop over the tiles find the size of the Vs and apply it */ for (blki=1; blki<=mt; blki++) { /*calculate the size of each losange of Vs= (Vm,Vn)*/ myrow = firstrow + (mt-blki)*NB; Vm = min( NB+Vblksiz-1, N-myrow); if( ( blkj == nt-1 ) && ( blki == mt ) ) { Vn = min (Vblksiz, Vm); }else{ Vn = min (Vblksiz, Vm-1); } /*calculate the pointer to the Vs and the Ts. * Note that Vs and Ts have special storage done * by the bulgechasing function*/ mycol = blkj*Vblksiz; findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid); if((Vm>0)&&(Vn>0)){ CORE_clarfb_gemm( PlasmaRight, trans, PlasmaForward, PlasmaColumnwise, corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest,myrow), LDE, WORK, corelen); } } } } /*trans * Version 92: */ else { mt = plasma_ceildiv((N-1),NB); for (blki = 1; blki<=mt; blki++) { /* nbcolinvolvd = number of column corresponding to this block_row (blki) */ nbcolinvolvd = min(N-1, blki*NB); /*find the number of tile for this block (diagonal row of tiles) */ nt = plasma_ceildiv(nbcolinvolvd,Vblksiz); /*loop over the tiles find the size of the Vs and apply it */ for (blkj = 0; blkj<nt; blkj++) { /* the index of the first row of the first col meaning * the block on the top left (blki) */ firstrow = (mt-blki)*NB+1; /*calculate the size of each losange of Vs= (Vm,Vn)*/ myrow = firstrow + blkj*Vblksiz; mycol = blkj*Vblksiz; Vm = min( NB+Vblksiz-1, N-myrow); if( ( blkj == nt-1 ) && ( blki == mt ) ){ Vn = min (Vblksiz, Vm); }else{ Vn = min (Vblksiz, Vm-1); } /*calculate the pointer to the Vs and the Ts. * Note that Vs and Ts have special storage done * by the bulgechasing function*/ findVTpos(N,NB,Vblksiz,mycol,myrow, &vpos, &taupos, &tpos, &blkid); if((Vm>0)&&(Vn>0)) { CORE_clarfb_gemm( PlasmaRight, trans, PlasmaForward, PlasmaColumnwise, corelen, Vm, Vn, V(vpos), LDV, T(tpos), LDT, E(corest,myrow), LDE, WORK, corelen); } } } } } } /* END my_core_id=coreid */ } /* END loop over the chunk */ } /* END ELSE of WANTZ == 1 */ plasma_private_free(plasma, WORK); } #undef E #undef V #undef T #undef TAU /***************************************************************************/ #undef COMPLEX
{ "alphanum_fraction": 0.4196324144, "avg_line_length": 47.5, "ext": "c", "hexsha": "16c6677efe9f6ef43ef836da939bfbaa335bc299", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "compute/pcunmqr_blgtrd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "compute/pcunmqr_blgtrd.c", "max_line_length": 165, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "compute/pcunmqr_blgtrd.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5532, "size": 23940 }
#include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <math.h> #include <options/options.h> #include "../csm/csm_all.h" struct ld_exp_tro1_params { int seed; double max_xy_error; double max_theta_error_deg; const char* file_input; const char* file_output1; const char* file_output2; int num_per_scan; int debug; }; const char * banner = "This program prepares the data for one of the experiments. \n\n" "The input is any sensor log (Carmen or JSON format) \n" "The output are two files that contain laser_ref and laser_sens\n" "(you have to match the i-th scan in the first file with the i-th\n" " in the second).\n\n" "The two files contain exactly the same date but for the 'odometry' field\n" "The odometry error is uniform in the intervals given.\n"; int main(int argc, const char ** argv) { sm_set_program_name(argv[0]); struct ld_exp_tro1_params p; options_banner(banner); struct option* ops = options_allocate(10); options_double(ops, "max_xy_error", &p.max_xy_error, 10.0, "Maximum error for x,y (m)"); options_double(ops, "max_theta_error_deg", &p.max_theta_error_deg, 10.0, "Maximum error for orientation (deg)"); options_int (ops, "seed", &p.seed, 0, "Seed for random number generator (if 0, use GSL_RNG_SEED env. variable)."); options_int(ops, "num_per_scan", &p.num_per_scan, 10, "Number of trials for each scan."); options_string(ops, "in", &p.file_input, "stdin", "Input file "); options_string(ops, "out1", &p.file_output1, "stdout", "Output file for first scan"); options_string(ops, "out2", &p.file_output2, "stdout", "Output file for second scan"); options_int(ops, "debug", &p.debug, 0, "Shows debug information"); if(!options_parse_args(ops, argc, argv)) { options_print_help(ops, stderr); return -1; } sm_debug_write(p.debug); gsl_rng_env_setup(); gsl_rng * rng = gsl_rng_alloc (gsl_rng_ranlxs0); if(p.seed != 0) gsl_rng_set(rng, (unsigned int) p.seed); /* Open the two output files (possibly the same one) */ FILE * in = open_file_for_reading(p.file_input); if(!in) return -3; FILE * out1 = open_file_for_writing(p.file_output1); if(!out1) return -2; FILE * out2; if(!strcmp(p.file_output1, p.file_output2)) { out1 = out2; } else { out2 = open_file_for_writing(p.file_output2); if(!out2) return -2; } /* Read laser data from input file */ LDP ld; int count=0; while( (ld = ld_read_smart(in))) { count++; if(!ld_valid_fields(ld)) { sm_error("Invalid laser data (#%d in file)\n", count); continue; } for(int n=0; n < p.num_per_scan; n++) { ld->true_pose[0] = 0; ld->true_pose[1] = 0; ld->true_pose[2] = 0; ld->odometry[0] = 0; ld->odometry[1] = 0; ld->odometry[2] = 0; ld_write_as_json(ld, out1); ld->odometry[0] = 2*(gsl_rng_uniform(rng)-0.5) * p.max_xy_error; ld->odometry[1] = 2*(gsl_rng_uniform(rng)-0.5) * p.max_xy_error; ld->odometry[2] = 2*(gsl_rng_uniform(rng)-0.5) * deg2rad(p.max_theta_error_deg); ld_write_as_json(ld, out2); } ld_free(ld); } return 0; }
{ "alphanum_fraction": 0.6786401539, "avg_line_length": 27.350877193, "ext": "c", "hexsha": "6ec0ff88c101ce6b2c0be8fcdb7cc7e95df1e545", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_path": "csm/sm/apps/ld_exp_tro1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_path": "csm/sm/apps/ld_exp_tro1.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_path": "csm/sm/apps/ld_exp_tro1.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 988, "size": 3118 }
/* These tests are based on the NIST Statistical Reference Datasets See http://www.nist.gov/itl/div898/strd/index.html for more information. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_ieee_utils.h> #include "test_longley.c" #include "test_filip.c" #include "test_pontius.c" #include "test_brown.c" #include "test_enso.c" #include "test_kirby2.c" #include "test_hahn1.c" #include "test_nelson.c" #include "test_fn.c" #include "test_estimator.c" void test_lmder (gsl_multifit_function_fdf * f, double x0[], double * X, double F[], double * cov); void test_fdf (const char * name, gsl_multifit_function_fdf * f, double x0[], double x[], double sumsq, double sigma[]); int main (void) { gsl_ieee_env_setup(); test_longley(); test_filip(); test_pontius(); test_estimator(); { gsl_multifit_function_fdf f = make_fdf (&brown_f, &brown_df, &brown_fdf, brown_N, brown_P, 0); test_lmder(&f, brown_x0, &brown_X[0][0], brown_F, &brown_cov[0][0]); } { gsl_multifit_function_fdf f = make_fdf (&enso_f, &enso_df, &enso_fdf, enso_N, enso_P, 0); test_fdf("nist-ENSO", &f, enso_x0, enso_x, enso_sumsq, enso_sigma); } { gsl_multifit_function_fdf f = make_fdf (&kirby2_f, &kirby2_df, &kirby2_fdf, kirby2_N, kirby2_P, 0); test_fdf("nist-kirby2", &f, kirby2_x0, kirby2_x, kirby2_sumsq, kirby2_sigma); } { gsl_multifit_function_fdf f = make_fdf (&hahn1_f, &hahn1_df, &hahn1_fdf, hahn1_N, hahn1_P, 0); test_fdf("nist-hahn1", &f, hahn1_x0, hahn1_x, hahn1_sumsq, hahn1_sigma); } #ifdef JUNK { gsl_multifit_function_fdf f = make_fdf (&nelson_f, &nelson_df, &nelson_fdf, nelson_N, nelson_P, 0); test_fdf("nist-nelson", &f, nelson_x0, nelson_x, nelson_sumsq, nelson_sigma); } #endif /* now summarize the results */ exit (gsl_test_summary ()); } void test_lmder (gsl_multifit_function_fdf * f, double x0[], double * X, double F[], double * cov) { const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; const size_t n = f->n; const size_t p = f->p; int status; size_t iter = 0, i; gsl_vector_view x = gsl_vector_view_array (x0, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, f, &x.vector); do { status = gsl_multifit_fdfsolver_iterate (s); for (i = 0 ; i < p; i++) { gsl_test_rel (gsl_vector_get (s->x, i), X[p*iter+i], 1e-5, "lmsder, iter=%u, x%u", iter, i); } gsl_test_rel (gsl_blas_dnrm2 (s->f), F[iter], 1e-5, "lmsder, iter=%u, f", iter); iter++; } while (iter < 20); { size_t i, j; gsl_matrix * covar = gsl_matrix_alloc (4, 4); gsl_multifit_covar (s->J, 0.0, covar); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { gsl_test_rel (gsl_matrix_get(covar,i,j), cov[i*p + j], 1e-7, "gsl_multifit_covar cov(%d,%d)", i, j) ; } } gsl_matrix_free (covar); } gsl_multifit_fdfsolver_free (s); } void test_fdf (const char * name, gsl_multifit_function_fdf * f, double x0[], double x_final[], double f_sumsq, double sigma[]) { const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; const size_t n = f->n; const size_t p = f->p; int status; size_t iter = 0; gsl_vector_view x = gsl_vector_view_array (x0, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, f, &x.vector); do { status = gsl_multifit_fdfsolver_iterate (s); #ifdef DEBUG printf("iter = %d status = %d |f| = %.18e x = \n", iter, status, gsl_blas_dnrm2 (s->f)); gsl_vector_fprintf(stdout, s->x, "%.8e"); #endif status = gsl_multifit_test_delta (s->dx, s->x, 0.0, 1e-7); iter++; } while (status == GSL_CONTINUE && iter < 1000); { size_t i; gsl_matrix * covar = gsl_matrix_alloc (p, p); gsl_multifit_covar (s->J, 0.0, covar); for (i = 0 ; i < p; i++) { gsl_test_rel (gsl_vector_get (s->x, i), x_final[i], 1e-5, "%s, lmsder, x%u", name, i); } { double s2 = pow(gsl_blas_dnrm2 (s->f), 2.0); gsl_test_rel (s2, f_sumsq, 1e-5, "%s, lmsder, |f|^2", name); for (i = 0; i < p; i++) { double ei = sqrt(s2/(n-p))*sqrt(gsl_matrix_get(covar,i,i)); gsl_test_rel (ei, sigma[i], 1e-4, "%s, sigma(%d)", name, i) ; } } gsl_matrix_free (covar); } gsl_multifit_fdfsolver_free (s); }
{ "alphanum_fraction": 0.5760954617, "avg_line_length": 24.2274881517, "ext": "c", "hexsha": "fede15afdaa21ab899a6ccf706b468b915e68df5", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/multifit/test.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/multifit/test.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/multifit/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1717, "size": 5112 }
/* NAME: minmax PURPOSE: returns the (finite) minimum and the maximum of a vector which is the row/column of a matrix CALLING SEQUENCE: minmax(gsl_matrix * q, int row, bool isrow, double * min, double * max, bool partial, int partial_indx[3]) INPUT: q - matrix which holds the vector row - row/column which holds the vector isrow - is it the row or is it the column OUTPUT: min - finite minimum max - finite maximum REVISION HISTORY: 2008-09-21 - Written Bovy */ #include <gsl/gsl_matrix.h> #include <float.h> #include <stdbool.h> #include <proj_gauss_mixtures.h> void minmax(gsl_matrix * q, int row, bool isrow, double * min, double * max){ *max = -DBL_MAX; *min = DBL_MAX; int dd; double temp; if (isrow) { for (dd = 0; dd != q->size2; ++dd){ temp = gsl_matrix_get(q,row,dd); if (temp > *max && bovy_isfin(temp)) *max = temp; if (temp < *min && bovy_isfin(temp)) *min = temp; } } else { for (dd = 0; dd != q->size1; ++dd){ temp = gsl_matrix_get(q,dd,row); if (temp > *max && bovy_isfin(temp)) *max = temp; if (temp < *min && bovy_isfin(temp)) *min = temp; } } return ; }
{ "alphanum_fraction": 0.5942857143, "avg_line_length": 23.5576923077, "ext": "c", "hexsha": "03f3052a9ba55ecacbbdcd110e3a83e1a642ff48", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_path": "src/minmax.c", "max_issues_count": 24, "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_path": "src/minmax.c", "max_line_length": 111, "max_stars_count": 73, "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_path": "src/minmax.c", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "num_tokens": 382, "size": 1225 }
//Roots of polynomial using compan matrix, as in Matlab/Octave. //This does roots for each vector X. //The roots are from an eig using LAPACKE, //and are tested to match Octave, except sometimes for sorting order. //For the complex case with non-contiguous vecs in X and Y, //the answers are correct except for a mysterious sign change. #include <stdio.h> #include <stdlib.h> #include <lapacke.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int poly2roots_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int poly2roots_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int poly2roots_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int poly2roots_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim); int poly2roots_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in poly2roots_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N==0u || Lx<2u) {} else if (Lx==2u) { if (Lx==N) { *Y = -*(X+1); *++Y = 0.0f; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, ++X, ++Y) { ++X; *Y = -*X; *++Y = 0.0f; } } else { for (size_t g=G; g>0u; --g, X+=B) { for (size_t b=B; b>0u; --b, ++X, ++Y) { *Y = -*(X+K); *++Y = 0.0f; } } } } } else { const size_t Ly = Lx - 1u; float x0; const int job = 'E', compz = 'N'; //eigenvalues only const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1; const lapack_int ilo = 1, ihi = n; //avoids balancing lapack_int info; float *compan, *wr, *wi, zz[1]; if (!(wr=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in poly2roots_s: problem with malloc. "); perror("malloc"); return 1; } if (!(wi=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in poly2roots_s: problem with malloc. "); perror("malloc"); return 1; } if (!(compan=(float *)calloc((size_t)(n*n),sizeof(float)))) { fprintf(stderr,"error in poly2roots_s: problem with calloc. "); perror("calloc"); return 1; } if (Lx==N) { ++compan; for (size_t l=Ly; l>0u; --l, compan+=Lx) { *compan = 1.0f; } compan -= Lx*Ly + 1u; x0 = -*X++; for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_s: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; } wr -= Ly; wi -= Ly; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v) { for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0f; } compan -= Lx; for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0f; } *compan-- = 1.0f; x0 = -*X++; for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_s: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; } wr -= Ly; wi -= Ly; } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(Ly-1u)) { for (size_t b=B; b>0u; --b, X-=K*Lx-1u, Y-=2u*K*Ly-2u) { for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0f; } compan -= Lx; for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0f; } *compan-- = 1.0f; x0 = -*X; X += K; for (size_t l=Ly; l>0u; --l, X+=K, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_s: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l, Y+=2u*K-1u) { *Y = *wr++; *++Y = *wi++; } wr -= Ly; wi -= Ly; } } } } free(compan); free(wr); free(wi); } return 0; } int poly2roots_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in poly2roots_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N==0u || Lx<2u) {} else if (Lx==2u) { if (Lx==N) { *Y = -*(X+1); *++Y = 0.0; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, ++X, ++Y) { ++X; *Y = -*X; *++Y = 0.0; } } else { for (size_t g=G; g>0u; --g, X+=B) { for (size_t b=B; b>0u; --b, ++X, ++Y) { *Y = -*(X+K); *++Y = 0.0; } } } } } else { const size_t Ly = Lx - 1u; double x0; const int job = 'E', compz = 'N'; //eigenvalues only const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1; const lapack_int ilo = 1, ihi = n; //avoids balancing lapack_int info; double *compan, *wr, *wi, zz[1]; if (!(wr=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in poly2roots_d: problem with malloc. "); perror("malloc"); return 1; } if (!(wi=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in poly2roots_d: problem with malloc. "); perror("malloc"); return 1; } if (!(compan=(double *)calloc((size_t)(n*n),sizeof(double)))) { fprintf(stderr,"error in poly2roots_d: problem with calloc. "); perror("calloc"); return 1; } if (Lx==N) { ++compan; for (size_t l=Ly; l>0u; --l, compan+=Lx) { *compan = 1.0; } compan -= Lx*Ly + 1u; x0 = -*X++; for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_d: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; } wr -= Ly; wi -= Ly; } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v) { for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0; } compan -= Lx; for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0; } *compan-- = 1.0; x0 = -*X++; for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_d: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; } wr -= Ly; wi -= Ly; } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(Ly-1u)) { for (size_t b=B; b>0u; --b, X-=K*Lx-1u, Y-=2u*K*Ly-2u) { for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0; } compan -= Lx; for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0; } *compan-- = 1.0; x0 = -*X; X += K; for (size_t l=Ly; l>0u; --l, X+=K, compan+=Ly) { *compan = *X / x0; } compan -= Ly*Ly; info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig if (info) { fprintf(stderr,"error in poly2roots_d: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l, Y+=2u*K-1u) { *Y = *wr++; *++Y = *wi++; } wr -= Ly; wi -= Ly; } } } } free(compan); free(wr); free(wi); } return 0; } int poly2roots_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in poly2roots_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N==0u || Lx<2u) {} else { const size_t Ly = Lx - 1u; const int job = 'E', compz = 'N'; //eigenvalues only const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1; const lapack_int ilo = 1, ihi = n; //avoids balancing lapack_int info; float *compan, zz[2], scr, sci; if (!(compan=(float *)calloc((size_t)(4*n*n),sizeof(float)))) { fprintf(stderr,"error in poly2roots_c: problem with calloc. "); perror("calloc"); return 1; } if (Lx==N) { compan += 2; for (size_t l=Ly; l>0u; --l, compan+=2u*Lx) { *compan = 1.0f; } compan -= 2u*Lx*Ly + 2u; scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2; for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)Y,(lapack_complex_float *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_c: lapacke decomposition failed\n"); return 1; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, Y+=2u*Ly) { if (Ly>1u) { for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0f; } compan -= 2u*Lx; for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0f; } *compan = 1.0f; compan -= 2; } scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2; for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)Y,(lapack_complex_float *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_c: lapacke decomposition failed\n"); return 1; } } } else { float *roots; if (!(roots=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in poly2roots_c: problem with malloc. "); perror("malloc"); return 1; } for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(Ly-1u)) { for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*Ly-2u) { if (Ly>1u) { for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0f; } compan -= 2u*Lx; for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0f; } *compan = 1.0f; compan -= 2; } scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2u*K; for (size_t l=Ly; l>0u; --l, X+=2u*K, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)roots,(lapack_complex_float *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_c: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l, ++roots, Y+=2u*K-1u) { *Y++ = *roots++; *Y = *roots; } roots -= 2u*Ly; } } free(roots); } } free(compan); } return 0; } int poly2roots_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim) { if (dim>3u) { fprintf(stderr,"error in poly2roots_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (N==0u || Lx<2u) {} else { const size_t Ly = Lx - 1u; const int job = 'E', compz = 'N'; //eigenvalues only const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1; const lapack_int ilo = 1, ihi = n; //avoids balancing lapack_int info; double *compan, zz[2], scr, sci; if (!(compan=(double *)calloc((size_t)(4*n*n),sizeof(double)))) { fprintf(stderr,"error in poly2roots_z: problem with calloc. "); perror("calloc"); return 1; } if (Lx==N) { compan += 2; for (size_t l=Ly; l>0u; --l, compan+=2u*Lx) { *compan = 1.0; } compan -= 2u*Lx*Ly + 2u; scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2; for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)Y,(lapack_complex_double *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_z: lapacke decomposition failed\n"); return 1; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=V; v>0u; --v, Y+=2u*Ly) { if (Ly>1u) { for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0; } compan -= 2u*Lx; for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0; } *compan = 1.0; compan -= 2; } scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2; for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)Y,(lapack_complex_double *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_z: lapacke decomposition failed\n"); return 1; } } } else { double *roots; if (!(roots=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in poly2roots_z: problem with malloc. "); perror("malloc"); return 1; } for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(Ly-1u)) { for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*Ly-2u) { if (Ly>1u) { for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0; } compan -= 2u*Lx; for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0; } *compan = 1.0; compan -= 2; } scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X; X += 2u*K; for (size_t l=Ly; l>0u; --l, X+=2u*K, compan+=2u*Ly-1u) { *compan = *X*scr - *(X+1)*sci; *++compan = *X*sci + *(X+1)*scr; } compan -= 2u*Ly*Ly; info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)roots,(lapack_complex_double *)zz,ldz); if (info) { fprintf(stderr,"error in poly2roots_z: lapacke decomposition failed\n"); return 1; } for (size_t l=Ly; l>0u; --l, ++roots, Y+=2u*K-1u) { *Y++ = *roots++; *Y = *roots; } roots -= 2u*Ly; } } free(roots); } } free(compan); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4350987, "avg_line_length": 46.0532150776, "ext": "c", "hexsha": "572dba8276291fb9c1efc30465ce9db26c15cd67", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_path": "c/poly2roots.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/dsp", "max_issues_repo_path": "c/poly2roots.c", "max_line_length": 183, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_path": "c/poly2roots.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "num_tokens": 6872, "size": 20770 }
/*System includes*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> /*GSL includes*/ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_statistics_double.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_multimin.h> #include <pthread.h> /*User includes*/ #include "Subsample.h" static char *usage[] = {"Subsample - Subsamples an emprical rarefraction curve by resampling\n", "Required parameters:\n", " -in filename parameter file \n", " -i integer sample to subsample from\n", " -r integer number of samples to generate\n", " -n integer new sample size\n", "Optional:\n", " -seed long seed random number generator\n", " -v verbose\n"}; static int nLines = 9; static int verbose = FALSE; void setCP(double* adP, double *adC, int *anN, int nS, int nL) { int i = 0; for(i = 0; i < nS; i++){ adP[i] = ((double) anN[i])/((double) nL); } adC[i] = 0; for(i = 1; i <= nS; i++){ adC[i] = adP[i - 1] + adC[i - 1]; } } int sampleSpecies(gsl_rng *ptGSLRNG, double *adC, int nS) { double dRand = gsl_rng_uniform(ptGSLRNG); int nRet = ((double) nS)*dRand; while(dRand <= adC[nRet]) nRet--; while(dRand > adC[nRet + 1]) nRet++; return nRet; } void writeSample(t_Params *ptParams, int nSample, int nR, int nS, int* anF) { FILE *ofp = NULL; int i = 0; char szFileName[MAX_LINE_LENGTH]; sprintf(szFileName, "%s_%d_%d.dat",ptParams->szOutFileStub,nR, nSample); ofp = fopen(szFileName, "w"); for(i = 0; i < nS; i++){ fprintf(ofp,"%d %d\n",i, anF[i]); } fclose(ofp); } int main(int argc, char* argv[]) { int i = 0, j = 0, r = 0; int nCount = 0, nRS = 0, nD = 0; t_Params tParams; int nS = 0, nL = 0; double *adP = NULL; double *adC = NULL; int *anN = NULL; int **aanF = NULL; gsl_rng *ptGSLRNG = NULL; const gsl_rng_type *ptGSLRNGType = NULL; gsl_rng_env_setup(); gsl_set_error_handler_off(); /*get command line params*/ getCommandLineParams(&tParams, argc, argv); ptGSLRNGType = gsl_rng_default; ptGSLRNG = gsl_rng_alloc(ptGSLRNGType); gsl_rng_set(ptGSLRNG, tParams.lSeed); /*read in abundance distribution*/ readAbundanceData(tParams.nI, tParams.szInputFile,&anN,&nS); for(i = 0; i < nS; i++){ nL += anN[i]; } adP = (double *) malloc(sizeof(double)*nS); adC = (double *) malloc(sizeof(double)*(nS + 1)); aanF = (int **) malloc(sizeof(int*)*nS); for(i = 0; i < nS; i++){ aanF[i] = (int *) malloc(tParams.nR*sizeof(int)); } setCP(adP, adC, anN, nS, nL); while(r < tParams.nR){ for(i = 0; i < nS; i++){ aanF[i][r] = 0; } for(i = 0; i < tParams.nN; i++){ nD = sampleSpecies(ptGSLRNG, adC, nS); aanF[nD][r]++; }/*sample*/ r++; } gsl_rng_free(ptGSLRNG); printf("OTU,"); for(r = 0; r < tParams.nR - 1; r++){ printf("r%d,",r); } printf("r%d\n",r); for(i = 0; i < nS; i++){ printf("C%d,",i); for(r = 0; r < tParams.nR - 1; r++){ printf("%d,",aanF[i][r]); } printf("%d\n",aanF[i][r]); } for(i = 0; i < nS; i++){ free(aanF[i]); } free(aanF); free(anN); free(adC); free(adP); exit(EXIT_SUCCESS); } void writeUsage(FILE* ofp) { int i = 0; char *line; for(i = 0; i < nLines; i++){ line = usage[i]; fputs(line,ofp); } } char *extractParameter(int argc, char **argv, char *param,int when) { int i = 0; while((i < argc) && (strcmp(param,argv[i]))){ i++; } if(i < argc - 1){ return(argv[i + 1]); } if((i == argc - 1) && (when == OPTION)){ return ""; } if(when == ALWAYS){ fprintf(stdout,"Can't find asked option %s\n",param); } return (char *) NULL; } void getCommandLineParams(t_Params *ptParams,int argc,char *argv[]) { char *szTemp = NULL; char *cError = NULL; /*get parameter file name*/ ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS); if(ptParams->szInputFile == NULL) goto error; /*get out file stub*/ //ptParams->szOutFileStub = extractParameter(argc,argv,OUT_FILE_STUB,ALWAYS); //if(ptParams->szOutFileStub == NULL) //goto error; szTemp = extractParameter(argc,argv,SAMPLE,OPTION); if(szTemp != NULL){ ptParams->nI = strtol(szTemp,&cError,10); if(*cError != '\0'){ goto error; } } else{ ptParams->nI = 1; } szTemp = extractParameter(argc,argv,N_SAMPLES,OPTION); if(szTemp != NULL){ ptParams->nR = strtol(szTemp,&cError,10); if(*cError != '\0'){ goto error; } } else{ ptParams->nR = 10; } szTemp = extractParameter(argc,argv,N_SIZE,OPTION); if(szTemp != NULL){ ptParams->nN = strtol(szTemp,&cError,10); if(*cError != '\0'){ goto error; } } else{ ptParams->nN = 1000; } /*get out file stub*/ szTemp = extractParameter(argc,argv,SEED,OPTION); if(szTemp != NULL){ ptParams->lSeed = strtol(szTemp,&cError,10); if(*cError != '\0'){ goto error; } } else{ ptParams->lSeed = 0; } /*verbosity*/ szTemp = extractParameter(argc, argv, VERBOSE, OPTION); if(szTemp != NULL){ verbose = TRUE; } return; error: writeUsage(stdout); exit(EXIT_FAILURE); } void readAbundanceData(int nI, const char *szFile, int **panN, int *pnS) { int *anN = NULL; int i = 0, j = 0, nS = 0; char szLine[MAX_LINE_LENGTH]; FILE* ifp = NULL; ifp = fopen(szFile, "r"); if(ifp){ char* szTok = NULL; char* pcError = NULL; fgets(szLine, MAX_LINE_LENGTH, ifp); while(fgets(szLine, MAX_LINE_LENGTH, ifp) != NULL){ nS++; } fclose(ifp); ifp = fopen(szFile, "r"); fgets(szLine, MAX_LINE_LENGTH, ifp); anN = (int *) malloc(nS*sizeof(int)); for(i = 0; i < nS; i++){ fgets(szLine, MAX_LINE_LENGTH, ifp); szTok = strtok(szLine, DELIM); for(j = 0; j < nI; j++){ szTok = strtok(NULL, DELIM); } anN[i] = strtol(szTok,&pcError,10); if(*pcError != '\0'){ goto formatError; } } } else{ fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile); fflush(stderr); exit(EXIT_FAILURE); } (*pnS) = nS; (*panN) = anN; return; formatError: fprintf(stderr, "Incorrectly formatted abundance data file\n"); fflush(stderr); exit(EXIT_FAILURE); } int compare_doubles(const void* a, const void* b) { double* arg1 = (double *) a; double* arg2 = (double *) b; if( *arg1 < *arg2 ) return -1; else if( *arg1 == *arg2 ) return 0; else return 1; }
{ "alphanum_fraction": 0.5719610092, "avg_line_length": 20.5781710914, "ext": "c", "hexsha": "360d3fb7a038a9926270e7b9b1e1258ab868e87d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chrisquince/DiversityEstimates", "max_forks_repo_path": "Subsample/Subsample.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chrisquince/DiversityEstimates", "max_issues_repo_path": "Subsample/Subsample.c", "max_line_length": 96, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chrisquince/DiversityEstimates", "max_stars_repo_path": "Subsample/Subsample.c", "max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z", "num_tokens": 2348, "size": 6976 }
/* interpolation/spline2d.c * * Copyright 2012 David Zaslavsky * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> gsl_spline2d * gsl_spline2d_alloc(const gsl_interp2d_type * T, size_t xsize, size_t ysize) { double * array_mem; gsl_spline2d * interp; if (xsize < T->min_size || ysize < T->min_size) { GSL_ERROR_NULL("insufficient number of points for interpolation type", GSL_EINVAL); } interp = calloc(1, sizeof(gsl_spline2d)); if (interp == NULL) { GSL_ERROR_NULL("failed to allocate space for gsl_spline2d struct", GSL_ENOMEM); } interp->interp_object.type = T; interp->interp_object.xsize = xsize; interp->interp_object.ysize = ysize; if (interp->interp_object.type->alloc == NULL) { interp->interp_object.state = NULL; } else { interp->interp_object.state = interp->interp_object.type->alloc(xsize, ysize); if (interp->interp_object.state == NULL) { gsl_spline2d_free(interp); GSL_ERROR_NULL("failed to allocate space for gsl_spline2d state", GSL_ENOMEM); } } /* * Use one contiguous block of memory for all three data arrays. * That way the code fails immediately if there isn't sufficient space for everything, * rather than allocating one or two and then having to free them. */ array_mem = (double *)calloc(xsize + ysize + xsize * ysize, sizeof(double)); if (array_mem == NULL) { gsl_spline2d_free(interp); GSL_ERROR_NULL("failed to allocate space for data arrays", GSL_ENOMEM); } interp->xarr = array_mem; interp->yarr = array_mem + xsize; interp->zarr = array_mem + xsize + ysize; return interp; } /* gsl_spline2d_alloc() */ int gsl_spline2d_init(gsl_spline2d * interp, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize) { int status = gsl_interp2d_init(&(interp->interp_object), xarr, yarr, zarr, xsize, ysize); memcpy(interp->xarr, xarr, xsize * sizeof(double)); memcpy(interp->yarr, yarr, ysize * sizeof(double)); memcpy(interp->zarr, zarr, xsize * ysize * sizeof(double)); return status; } /* gsl_spline2d_init() */ void gsl_spline2d_free(gsl_spline2d * interp) { RETURN_IF_NULL(interp); if (interp->interp_object.type->free) interp->interp_object.type->free(interp->interp_object.state); /* * interp->xarr points to the beginning of one contiguous block of memory * that holds interp->xarr, interp->yarr, and interp->zarr. So it all gets * freed with one call. cf. gsl_spline2d_alloc() implementation */ if (interp->xarr) free(interp->xarr); free(interp); } /* gsl_spline2d_free() */ double gsl_spline2d_eval(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_extrap(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_extrap(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_extrap_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_extrap_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_deriv_x(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_deriv_x(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_deriv_x_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_deriv_x_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_deriv_y(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_deriv_y(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_deriv_y_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_deriv_y_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_deriv_xx(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_deriv_xx(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_deriv_xx_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_deriv_xx_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_deriv_yy(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_deriv_yy(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_deriv_yy_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_deriv_yy_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } double gsl_spline2d_eval_deriv_xy(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { return gsl_interp2d_eval_deriv_xy(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya); } int gsl_spline2d_eval_deriv_xy_e(const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return gsl_interp2d_eval_deriv_xy_e(&(interp->interp_object), interp->xarr, interp->yarr, interp->zarr, x, y, xa, ya, z); } size_t gsl_spline2d_min_size(const gsl_spline2d * interp) { return gsl_interp2d_min_size(&(interp->interp_object)); } const char * gsl_spline2d_name(const gsl_spline2d * interp) { return gsl_interp2d_name(&(interp->interp_object)); } int gsl_spline2d_set(const gsl_spline2d * interp, double zarr[], const size_t i, const size_t j, const double z) { return gsl_interp2d_set(&(interp->interp_object), zarr, i, j, z); } /* gsl_spline2d_set() */ double gsl_spline2d_get(const gsl_spline2d * interp, const double zarr[], const size_t i, const size_t j) { return gsl_interp2d_get(&(interp->interp_object), zarr, i, j); } /* gsl_spline2d_get() */
{ "alphanum_fraction": 0.6389470206, "avg_line_length": 35.0540540541, "ext": "c", "hexsha": "9d8f2d0e5082858be95972518e0f2ea3fbd63b18", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "igormcoelho/optstats", "max_issues_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_path": "thirdparty/gsl-2.7/interpolation/spline2d.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2376, "size": 9079 }
#include "np.h" #include "main.h" #include "argv.h" #include "memory.h" #include "utf8.h" #include "module_categorical.h" #include "module_lde.h" #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> #include <gsl/gsl_sf.h> #include "gslsupp.h" #include "sort.h" #ifndef TEST_DEACTIVATE # include "test.h" # include "test_ll.h" # include "test_np.h" # include "test_sort.h" # include "test_utf8.h" static bool test_main(struct log *log) { const struct test_group group_arr[] = { { NULL, sizeof(struct test_ll_a), CLII((test_generator_callback[]) { test_ll_generator_a, }), CLII((test_callback[]) { test_ll_a_1, test_ll_a_2, test_ll_a_3 }) }, { NULL, sizeof(struct test_ll_a), CLII((test_generator_callback[]) { test_ll_generator_b, }), CLII((test_callback[]) { test_ll_b, }) }, { test_np_disposer_a, sizeof(struct test_np_a), CLII((test_generator_callback[]) { test_np_generator_a, }), CLII((test_callback[]) { test_np_a, }) }, { test_sort_disposer_a, sizeof(struct test_sort_a), CLII((test_generator_callback[]) { test_sort_generator_a_1, test_sort_generator_a_2, test_sort_generator_a_3 }), CLII((test_callback[]) { test_sort_a, }) }, { test_sort_disposer_b, sizeof(struct test_sort_b), CLII((test_generator_callback[]) { test_sort_generator_b_1 }), CLII((test_callback[]) { test_sort_b_1, test_sort_b_2 }) }, { test_sort_disposer_c, sizeof(struct test_sort_c), CLII((test_generator_callback[]) { test_sort_generator_c_1 }), CLII((test_callback[]) { test_sort_c_1, test_sort_c_2 }) }, { NULL, sizeof(struct test_utf8), CLII((test_generator_callback[]) { test_utf8_generator, }), CLII((test_callback[]) { test_utf8_len, test_utf8_encode, test_utf8_decode, test_utf16_encode, test_utf16_decode }) } }; log_message_generic(log, CODE_METRIC, MESSAGE_NOTE, "Test mode triggered!\n"); return test(group_arr, countof(group_arr), log); } #else static bool test_main(struct log *log) { log_message_generic(log, CODE_METRIC, MESSAGE_NOTE, "Test mode deactivated!\n"); return 1; } #endif // Main routine arguments management struct main_args main_args_default() { struct main_args res = { .thread_cnt = get_processor_count() }; uint8_bit_set(res.bits, MAIN_ARGS_BIT_POS_THREAD_CNT); return res; } struct main_args main_args_override(struct main_args args_hi, struct main_args args_lo) { struct main_args res = { .log_path = args_hi.log_path ? args_hi.log_path : args_lo.log_path }; if (res.log_path && !strcmp(res.log_path, "stderr")) res.log_path = NULL; memcpy(res.bits, args_hi.bits, UINT8_CNT(MAIN_ARGS_BIT_CNT)); if (uint8_bit_test(args_hi.bits, MAIN_ARGS_BIT_POS_THREAD_CNT)) res.thread_cnt = args_hi.thread_cnt; else { res.thread_cnt = args_lo.thread_cnt; uint8_bit_set(res.bits, MAIN_ARGS_BIT_POS_THREAD_CNT); } return res; } // Main routine (see below for actual entry point) static int Main(int argc, char **argv) { /*const char *strings[] = { __FUNCTION__, "NOTE (%s): No input data specified.\n", "INFO (%s): Help mode triggered.\n", "WARNING (%s): Unable to compile XML document \"%s\"!\n", "WARNING (%s): Unable to execute one or more branches of the XML document \"%s\"!\n", "Overall program execution" }; enum { STR_FN = 0, STR_FR_ND, STR_FR_IH, STR_FR_WC, STR_FR_WE, STR_M_EXE }; */ // All names should be sorted according to 'strncmp'!!! struct argv_par_sch argv_par_sch = { CLII((struct tag[]) { { STRI("help"), 0 }, { STRI("log"), 1 }, { STRI("test"), 2 }, { STRI("threads"), 3 }}), CLII((struct tag[]) { { STRI("C"), 4 }, { STRI("L"), 5 }, { STRI("T"), 2 }, { STRI("h"), 0 }, { STRI("l"), 1 }, { STRI("t"), 3 } }), CLII((struct par_sch[]) { { 0, &(struct handler_context) { offsetof(struct main_args, bits), MAIN_ARGS_BIT_POS_HELP }, empty_handler, 1 }, { offsetof(struct main_args, log_path), NULL, p_str_handler, 0 }, { 0, &(struct handler_context) { offsetof(struct main_args, bits), MAIN_ARGS_BIT_POS_TEST }, empty_handler, 1 }, { offsetof(struct main_args, thread_cnt), &(struct handler_context) { offsetof(struct main_args, bits), MAIN_ARGS_BIT_POS_THREAD_CNT }, size_handler, 0 }, { 0, &(struct handler_context) { offsetof(struct main_args, bits), MAIN_ARGS_BIT_POS_CAT }, empty_handler, 1 }, { 0, &(struct handler_context) { offsetof(struct main_args, bits), MAIN_ARGS_BIT_POS_LDE }, empty_handler, 1 }, }) }; /* // All names on every sub-level should be sorted according to 'strncmp'!!! struct { xmlNode *node; size_t cnt; } dscsch = CLII((xmlNode[]) { { .name = STRI("Density"), .sz = sizeof(densityContext), .prologue = (prologueCallback) densityPrologue, .epilogue = (epilogueCallback) densityEpilogue, .dispose = (disposeCallback) densityContextDispose, CLII((struct att[]) { { STRI("pos"), 0, &(handlerContext) { offsetof(densityContext, bits), DENSITYCONTEXT_BIT_POS_POS }, (readHandlerCallback) boolHandler }, { STRI("radius"), offsetof(densityContext, radius), &(handlerContext) { offsetof(densityContext, bits) - offsetof(densityContext, radius), DENSITYCONTEXT_BIT_POS_RADIUS }, (readHandlerCallback) uint32Handler }, { STRI("type"), offsetof(densityContext, type), NULL, (readHandlerCallback) densityTypeHandler } }), CLII((xmlNode[]) { { .name = STRI("Fold"), .sz = sizeof(densityFoldContext), .prologue = (prologueCallback) densityFoldPrologue, .epilogue = (epilogueCallback) densityFoldEpilogue, .dispose = (disposeCallback) densityFoldContextDispose, CLII((struct att[]) { { STRI("group"), offsetof(densityFoldContext, group), NULL, (readHandlerCallback) strHandler }, { STRI("type"), offsetof(densityFoldContext, type), NULL, (readHandlerCallback) densityFoldHandler } }), CLII((xmlNode[]) { { .name = STRI("Report"), .sz = sizeof(dfReportContext), .prologue = (prologueCallback) dfReportPrologue, .epilogue = (epilogueCallback) dfReportEpilogue, .dispose = (disposeCallback) dfReportContextDispose, CLII((struct att[]) { { STRI("header"), 0, &(handlerContext) { offsetof(dfReportContext, bits), DFREPORTCONTEXT_BIT_POS_HEADER }, (readHandlerCallback) boolHandler }, { STRI("limit"), offsetof(dfReportContext, limit), &(handlerContext) { offsetof(dfReportContext, bits) - offsetof(dfReportContext, limit), DFREPORTCONTEXT_BIT_POS_LIMIT }, (readHandlerCallback) uint32Handler }, { STRI("path"), offsetof(dfReportContext, path), NULL, (readHandlerCallback) strHandler }, { STRI("semicolon"), 0, &(handlerContext) { offsetof(dfReportContext, bits), DFREPORTCONTEXT_BIT_POS_SEMICOLON }, (readHandlerCallback) boolHandler }, { STRI("threshold"), offsetof(dfReportContext, threshold), &(handlerContext) { offsetof(dfReportContext, bits) - offsetof(dfReportContext, threshold), DFREPORTCONTEXT_BIT_POS_THRESHOLD }, (readHandlerCallback) float64Handler }, { STRI("type"), offsetof(dfReportContext, type), NULL, (readHandlerCallback) dfReportHandler } }) } }) }, { .name = STRI("Regions"), .sz = sizeof(regionsContext), .prologue = (prologueCallback) regionsPrologue, .epilogue = (epilogueCallback) regionsEpilogue, .dispose = (disposeCallback) regionsContextDispose, CLII((struct att[]) { { STRI("decay"), offsetof(regionsContext, decay), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, decay), REGIONSCONTEXT_BIT_POS_DECAY }, (readHandlerCallback) uint32Handler }, { STRI("depth"), offsetof(regionsContext, depth), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, depth), REGIONSCONTEXT_BIT_POS_DEPTH }, (readHandlerCallback) uint32Handler }, { STRI("length"), offsetof(regionsContext, length), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, length), REGIONSCONTEXT_BIT_POS_LENGTH }, (readHandlerCallback) uint32Handler }, { STRI("threshold"), offsetof(regionsContext, threshold), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, threshold), REGIONSCONTEXT_BIT_POS_THRESHOLD }, (readHandlerCallback) float64Handler }, { STRI("tolerance"), offsetof(regionsContext, tolerance), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, tolerance), REGIONSCONTEXT_BIT_POS_TOLERANCE }, (readHandlerCallback) float64Handler }, { STRI("slope"), offsetof(regionsContext, slope), &(handlerContext) { offsetof(regionsContext, bits) - offsetof(regionsContext, slope), REGIONSCONTEXT_BIT_POS_SLOPE }, (readHandlerCallback) float64Handler } }) }, { .name = STRI("Report"), .sz = sizeof(dReportContext), .prologue = (prologueCallback) dReportPrologue, .epilogue = (epilogueCallback) dReportEpilogue, .dispose = (disposeCallback) dReportContextDispose, CLII((struct att[]) { { STRI("header"), 0, &(handlerContext) { offsetof(dReportContext, bits), DREPORTCONTEXT_BIT_POS_HEADER }, (readHandlerCallback) boolHandler }, { STRI("limit"), offsetof(dReportContext, limit), &(handlerContext) { offsetof(dReportContext, bits) - offsetof(dReportContext, limit), DREPORTCONTEXT_BIT_POS_LIMIT }, (readHandlerCallback) uint32Handler }, { STRI("path"), offsetof(dReportContext, path), NULL, (readHandlerCallback) strHandler }, { STRI("semicolon"), 0, &(handlerContext) { offsetof(dReportContext, bits), DREPORTCONTEXT_BIT_POS_SEMICOLON }, (readHandlerCallback) boolHandler }, { STRI("threshold"), offsetof(dReportContext, threshold), &(handlerContext) { offsetof(dReportContext, bits) - offsetof(dReportContext, threshold), DREPORTCONTEXT_BIT_POS_THRESHOLD }, (readHandlerCallback) float64Handler } }) } }) }, { .name = STRI("MySQL.Dispatch"), .sz = sizeof(mysqlDispatchContext), .prologue = (prologueCallback) mysqlDispatchPrologue, .epilogue = (epilogueCallback) mysqlDispatchEpilogue, .dispose = (disposeCallback) mysqlDispatchContextDispose, CLII((struct att[]) { { STRI("host"), offsetof(mysqlDispatchContext, host), NULL, (readHandlerCallback) strHandler }, { STRI("login"), offsetof(mysqlDispatchContext, login), NULL, (readHandlerCallback) strHandler }, { STRI("password"), offsetof(mysqlDispatchContext, password), NULL, (readHandlerCallback) strHandler }, { STRI("port"), offsetof(mysqlDispatchContext, port), NULL, (readHandlerCallback) uint32Handler }, { STRI("schema"), offsetof(mysqlDispatchContext, schema), NULL, (readHandlerCallback) strHandler }, { STRI("temp.prefix"), offsetof(mysqlDispatchContext, temppr), NULL, (readHandlerCallback) strHandler }, }) } }); // All names on every sub-level should be sorted according to 'strncmp'!!! xmlNode xmlsch = { .name = STRI("RegionsMT"), .sz = sizeof(frameworkContext), .prologue = (prologueCallback) frameworkPrologue, .epilogue = (epilogueCallback) frameworkEpilogue, .dispose = (disposeCallback) frameworkContextDispose, CLII((struct att[]) { { STRI("log"), offsetof(frameworkContext, logFile), NULL, (readHandlerCallback) strHandler }, { STRI("threads"), offsetof(frameworkContext, threadCount), &(handlerContext) { offsetof(frameworkContext, bits) - offsetof(frameworkContext, threadCount), FRAMEWORKCONTEXT_BIT_POS_THREADCOUNT }, (readHandlerCallback) uint32Handler } }), CLII((xmlNode[]) { { .name = STRI("Data.Load"), .sz = sizeof(loadDataContext), .prologue = (prologueCallback) loadDataPrologue, .epilogue = (epilogueCallback) loadDataEpilogue, .dispose = (disposeCallback) loadDataContextDispose, CLII((struct att[]) { { STRI("header"), 0, &(handlerContext) { offsetof(loadDataContext, bits), LOADDATACONTEXT_BIT_POS_HEADER }, (readHandlerCallback) boolHandler }, { STRI("logarithm"), 0, &(handlerContext) { offsetof(loadDataContext, bits), LOADDATACONTEXT_BIT_POS_LOGARITHM }, (readHandlerCallback) boolHandler }, { STRI("no.ranks"), 0, &(handlerContext) { offsetof(loadDataContext, bits), LOADDATACONTEXT_BIT_POS_NORANKS }, (readHandlerCallback) boolHandler }, { STRI("path.chr"), offsetof(loadDataContext, pathchr), NULL, (readHandlerCallback) strHandler }, { STRI("path.row"), offsetof(loadDataContext, pathrow), NULL, (readHandlerCallback) strHandler }, { STRI("path.test"), offsetof(loadDataContext, pathtest), NULL, (readHandlerCallback) strHandler }, { STRI("path.val"), offsetof(loadDataContext, pathval), NULL, (readHandlerCallback) strHandler }, }), { dscsch.node, dscsch.cnt } }, { .name = STRI("Genotypes"), .sz = sizeof(genotypesContext), .prologue = (prologueCallback) genotypesPrologue, .epilogue = (epilogueCallback) genotypesEpilogue, .dispose = (disposeCallback) genotypesContextDispose, CLII((struct att[]) { { STRI("option0"), 0, &(handlerContext) { offsetof(genotypesContext, bits), GENOTYPESCONTEXT_BIT_POS_OPTION0 }, (readHandlerCallback) boolHandler }, { STRI("option1"), 0, &(handlerContext) { offsetof(genotypesContext, bits), GENOTYPESCONTEXT_BIT_POS_OPTION1 }, (readHandlerCallback) boolHandler }, { STRI("option2"), 0, &(handlerContext) { offsetof(genotypesContext, bits), GENOTYPESCONTEXT_BIT_POS_OPTION2 }, (readHandlerCallback) boolHandler }, { STRI("option3"), 0, &(handlerContext) { offsetof(genotypesContext, bits), GENOTYPESCONTEXT_BIT_POS_OPTION3 }, (readHandlerCallback) boolHandler }, { STRI("path.bed"), offsetof(genotypesContext, path_bed), NULL, (readHandlerCallback) strHandler }, { STRI("path.bim"), offsetof(genotypesContext, path_bim), NULL, (readHandlerCallback) strHandler }, { STRI("path.fam"), offsetof(genotypesContext, path_fam), NULL, (readHandlerCallback) strHandler } }), { dscsch.node, dscsch.cnt } }, { .name = STRI("MySQL.Fetch"), .sz = sizeof(mysqlFetchContext), .prologue = (prologueCallback) mysqlFetchPrologue, .epilogue = (epilogueCallback) mysqlFetchEpilogue, .dispose = (disposeCallback) mysqlFetchContextDispose, CLII((struct att[]) { { STRI("host"), offsetof(mysqlFetchContext, host), NULL, (readHandlerCallback) strHandler }, { STRI("login"), offsetof(mysqlFetchContext, login), NULL, (readHandlerCallback) strHandler }, { STRI("no.ranks"), 0, &(handlerContext) { offsetof(mysqlFetchContext, bits), MYSQLFETCHCONTEXT_BIT_POS_NORANKS }, (readHandlerCallback) boolHandler }, { STRI("password"), offsetof(mysqlFetchContext, password), NULL, (readHandlerCallback) strHandler }, { STRI("port"), offsetof(mysqlFetchContext, port), NULL, (readHandlerCallback) uint32Handler }, { STRI("schema"), offsetof(mysqlFetchContext, schema), NULL, (readHandlerCallback) strHandler } }), { dscsch.node, dscsch.cnt } } }) }; */ //FILE *f = stderr; // fopen("f:\\test\\h", "w"); //fputs("\xef\xbb\xbf", f); //for (size_t i = 0; i < (size_t) argc; i++) fprintf(stderr, "%s\n", argv[i]); //fclose(f); struct style style = { .ttl = { INIT_ENV_COL(FG_GREEN), INIT_ENV_COL(FG_RED), INIT_ENV_COL(FG_YELLOW), INIT_ENV_COL(FG_MAGENTA), INIT_ENV_COL(FG_CYAN) }, .ts = INIT_ENV_COL(FG_BR_BLACK), .src = INIT_ENV_COL(FG_BR_BLACK), .str = INIT_ENV_COL(FG_BR_MAGENTA), .num = INIT_ENV_COL(FG_BR_CYAN), .time = INIT_ENV_COL(FG_BR_YELLOW) }; struct log log; if (log_init(&log, NULL, 1, 0, style, NULL)) { size_t pos_cnt; char **pos_arr; struct main_args main_args = { 0 }; if (argv_parse(argv_par_selector, &argv_par_sch, &main_args, argv, argc, &pos_arr, &pos_cnt, &log)) { main_args = main_args_override(main_args, main_args_default()); if (uint8_bit_test(main_args.bits, MAIN_ARGS_BIT_POS_HELP)) { // Help mode log_message_generic(&log, CODE_METRIC, MESSAGE_INFO, "Help mode triggered!\n"); } else if (uint8_bit_test(main_args.bits, MAIN_ARGS_BIT_POS_TEST)) { test_main(&log); } else if (uint8_bit_test(main_args.bits, MAIN_ARGS_BIT_POS_CAT)) { if (pos_cnt >= 6) { size_t rpl = (size_t) strtoull(pos_arr[4], NULL, 10); uint64_t seed = (uint64_t) strtoull(pos_arr[5], NULL, 10); categorical_run(pos_arr[0], pos_arr[1], pos_arr[2], pos_arr[3], rpl, seed, &log); } } else if (uint8_bit_test(main_args.bits, MAIN_ARGS_BIT_POS_LDE)) { if (pos_cnt >= 2) lde_run(pos_arr[0], pos_arr[1], &log); } else { if (!pos_cnt) log_message_generic(&log, CODE_METRIC, MESSAGE_NOTE, "No input data specified.\n"); else { } } free(pos_arr); } log_close(&log); } /* if (bitTest(args.bits, CMDARGS_BIT_POS_HELP)) { logMsg(&loginfo, strings[STR_FR_IH], strings[STR_FN]); // Help message should be here } else { if (!inputcnt) logMsg(&loginfo, strings[STR_FR_ND], strings[STR_FN]); for (size_t i = 0; i < inputcnt; i++) // Processing input files { programObject *obj = programObjectFromXML(&xmlsch, input[i], &loginfo); if (obj) { if (!programObjectExecute(obj, &args.in)) logMsg(&loginfo, strings[STR_FR_WE], strings[STR_FN], input[i]); programObjectDispose(obj); } else logMsg(&loginfo, strings[STR_FR_WC], strings[STR_FN], input[i]); } } */ return EXIT_SUCCESS; } #if _WIN32 # include <windows.h> int wmain(int argc, wchar_t **wargv) { // Memory leaks will be reported at the program exit _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); // Making console output UTF-8 friendly if (!SetConsoleOutputCP(CP_UTF8)) return EXIT_FAILURE; int main_res = EXIT_FAILURE; // Translating UTF-16 command-line parameters to UTF-8 char **argv; if (array_init(&argv, NULL, argc, sizeof(*argv), 0, ARRAY_STRICT)) { size_t base_cnt = 0, i; for (i = 0; i < (size_t) argc; i++) // Determining total length and performing error checking { wchar_t *word = wargv[i]; uint32_t val; uint8_t context = 0; for (; *word; word++) { if (!utf16_decode((uint16_t) *word, &val, NULL, NULL, &context)) break; if (!context) base_cnt += utf8_len(val); } if (*word) break; else base_cnt++; } if (i == (size_t) argc) { char *base; if (array_init(&base, NULL, base_cnt, sizeof(*base), 0, ARRAY_STRICT)) { char *byte = base; for (i = 0; i < (size_t) argc; i++) // Performing translation { argv[i] = byte; wchar_t *word = wargv[i]; uint32_t val; uint8_t context = 0; for (; *word; word++) { if (!utf16_decode((uint16_t) *word, &val, NULL, NULL, &context)) break; if (!context) { uint8_t len; utf8_encode(val, (uint8_t *) byte, &len); byte += len; } } if (*word) break; else *(byte++) = '\0'; } if (i == (size_t) argc) main_res = Main(argc, argv); free(base); } } free(argv); } return main_res; } #else int main(int argc, char **argv) { return Main(argc, argv); } #endif
{ "alphanum_fraction": 0.5629772594, "avg_line_length": 45.2258064516, "ext": "c", "hexsha": "dab18b17bd170c69c60b00f8dcd75123f6919a49", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_forks_repo_path": "src/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_issues_repo_path": "src/main.c", "max_line_length": 259, "max_stars_count": null, "max_stars_repo_head_hexsha": "b416ed24df0178244061a9f2aa75c513b3d8df9c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "DobzhanskyCenterSPBU/RegionsMT.Update", "max_stars_repo_path": "src/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5399, "size": 23834 }
/* vector/gsl_vector_complex_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_COMPLEX_DOUBLE_H__ #define __GSL_VECTOR_COMPLEX_DOUBLE_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; double *data; gsl_block_complex *block; int owner; } gsl_vector_complex; typedef struct { gsl_vector_complex vector; } _gsl_vector_complex_view; typedef _gsl_vector_complex_view gsl_vector_complex_view; typedef struct { gsl_vector_complex vector; } _gsl_vector_complex_const_view; typedef const _gsl_vector_complex_const_view gsl_vector_complex_const_view; /* Allocation */ gsl_vector_complex *gsl_vector_complex_alloc (const size_t n); gsl_vector_complex *gsl_vector_complex_calloc (const size_t n); gsl_vector_complex * gsl_vector_complex_alloc_from_block (gsl_block_complex * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_complex * gsl_vector_complex_alloc_from_vector (gsl_vector_complex * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_complex_free (gsl_vector_complex * v); /* Views */ _gsl_vector_complex_view gsl_vector_complex_view_array (double *base, size_t n); _gsl_vector_complex_view gsl_vector_complex_view_array_with_stride (double *base, size_t stride, size_t n); _gsl_vector_complex_const_view gsl_vector_complex_const_view_array (const double *base, size_t n); _gsl_vector_complex_const_view gsl_vector_complex_const_view_array_with_stride (const double *base, size_t stride, size_t n); _gsl_vector_complex_view gsl_vector_complex_subvector (gsl_vector_complex *base, size_t i, size_t n); _gsl_vector_complex_view gsl_vector_complex_subvector_with_stride (gsl_vector_complex *v, size_t i, size_t stride, size_t n); _gsl_vector_complex_const_view gsl_vector_complex_const_subvector (const gsl_vector_complex *base, size_t i, size_t n); _gsl_vector_complex_const_view gsl_vector_complex_const_subvector_with_stride (const gsl_vector_complex *v, size_t i, size_t stride, size_t n); _gsl_vector_view gsl_vector_complex_real (gsl_vector_complex *v); _gsl_vector_view gsl_vector_complex_imag (gsl_vector_complex *v); _gsl_vector_const_view gsl_vector_complex_const_real (const gsl_vector_complex *v); _gsl_vector_const_view gsl_vector_complex_const_imag (const gsl_vector_complex *v); /* Operations */ gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i); void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z); gsl_complex *gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i); const gsl_complex *gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i); void gsl_vector_complex_set_zero (gsl_vector_complex * v); void gsl_vector_complex_set_all (gsl_vector_complex * v, gsl_complex z); int gsl_vector_complex_set_basis (gsl_vector_complex * v, size_t i); int gsl_vector_complex_fread (FILE * stream, gsl_vector_complex * v); int gsl_vector_complex_fwrite (FILE * stream, const gsl_vector_complex * v); int gsl_vector_complex_fscanf (FILE * stream, gsl_vector_complex * v); int gsl_vector_complex_fprintf (FILE * stream, const gsl_vector_complex * v, const char *format); int gsl_vector_complex_memcpy (gsl_vector_complex * dest, const gsl_vector_complex * src); int gsl_vector_complex_reverse (gsl_vector_complex * v); int gsl_vector_complex_swap (gsl_vector_complex * v, gsl_vector_complex * w); int gsl_vector_complex_swap_elements (gsl_vector_complex * v, const size_t i, const size_t j); int gsl_vector_complex_isnull (const gsl_vector_complex * v); int gsl_vector_complex_ispos (const gsl_vector_complex * v); int gsl_vector_complex_isneg (const gsl_vector_complex * v); #ifdef HAVE_INLINE extern inline gsl_complex gsl_vector_complex_get (const gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { gsl_complex zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_AT (v, i); } extern inline void gsl_vector_complex_set (gsl_vector_complex * v, const size_t i, gsl_complex z) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_AT (v, i) = z; } extern inline gsl_complex * gsl_vector_complex_ptr (gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_AT (v, i); } extern inline const gsl_complex * gsl_vector_complex_const_ptr (const gsl_vector_complex * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6366054802, "avg_line_length": 30.314516129, "ext": "h", "hexsha": "ec7cf731dea8b97e8c5c3df0de1052f8e4d8426b", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_line_length": 94, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_complex_double.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1594, "size": 7518 }
#ifndef __BLAS_H__ #define __BLAS_H__ #define sgemm sgemm_ #define dgemm dgemm_ #define ssteqr ssteqr_ #define dsteqr dsteqr_ #define dgemv dgemv_ #define ddot ddot_ #define daxpy daxpy_ #define dscal dscal_ #define dasum dasum_ #ifdef __cplusplus extern "C"{ #endif //#include <cblas.h> //#include <clapack.h> void sgemm_(const char* TRANSA, const char* TRANSB, const int* M, const int* N, const int* K, const float* ALPHA, const float* A, const int* LDA, const float* B, const int* LDB, const float* BETA, float* C, const int* LDC); void dgemm_(const char* TRANSA, const char* TRANSB, const int* M, const int* N, const int* K, const double* ALPHA, const double* A, const int* LDA, const double* B, const int* LDB, const double* BETA, double* C, const int* LDC); /* void ssteqr_(char *compz, const int *n, float *d, float *e, float *z, const int *ldz, float *work, const int *info); void dsteqr_(char *compz, const int *n, double *d, double *e, double *z, const int *ldz, double *work, const int *info); */ void dgemv_(const char *trans, const int *m, const int *n, const double *alpha, const double *a, const int *lda, const double *x, const int *incx, const double *beta, double *y, const int *incy); double ddot_(const int* n, const double* x, const int* incx, const double* y, const int* incy); void daxpy_(const int* n, const double *alpha, const double* x, const int* incx, double* y, const int* incy); void dscal_(const int*n, const double *alpha, const double* x, const int* incx); double dasum_(const int*n, const double *x, const int* incx); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.6391694725, "avg_line_length": 29.7, "ext": "h", "hexsha": "faa3bb887b93ba95902b4f5d29a9c93ccaa6b91e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z", "max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maumueller/rehashing", "max_forks_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "maumueller/rehashing", "max_issues_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_line_length": 82, "max_stars_count": 20, "max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maumueller/rehashing", "max_stars_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z", "num_tokens": 554, "size": 1782 }
/****************************************************************************/ /* */ /* File: typedefs.h */ /* */ /* Purpose: header file for all necessary inculdes and typedefs for files */ /* associated with the NeuroMorph or CellCount projects */ /* */ /* Author: Marcel Oberlaender */ /* Max-Planck-Institute for Neurobiologie */ /* Am Kolpferspitz 18 */ /* D-82152 Martinsried (Munich) */ /* */ /* Co-Author: Robert Egger */ /* Max-Planck-Institute for Medical Research */ /* Jahnstrasse 19 */ /* D-69120 Heidelberg */ /* */ /* EMail: regger@mpimf-heidelberg.mpg.de */ /* */ /* History: 17.01.2008 */ /* */ /* Remarks: All rights are reserved by the Max-Planck-Society */ /* */ /* Revised by: Daniel Udvary */ /* In Silico Brain Sciences */ /* Max Planck Institute for Neurobiology of Behavior – caesar */ /* Ludwig-Erhard-Allee 2 */ /* 53175 Bonn, Germany */ /* */ /* e-mail: daniel.udvary@mpinb.mpg.de */ /* */ /* Date: 21.11.2019 */ /* */ /****************************************************************************/ #ifndef TYPEDEF #define TYPEDEF //#define DEBUG #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef _OPENMP #include <omp.h> #endif #define PI 3.1415926 #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_WARNINGS //STL includes #include "string" #include <iostream> #include <cstdio> #include <fstream> #include <string> #include <list> #include <vector> #include <map> #include <cmath> #include <algorithm> #include <complex> #include <utility> #include <ctime> //GSL includes #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> //ITK includes #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkImageFileReader.h" #include "itkVTKImageImport.h" #include "itkVTKImageExport.h" #include "itkNeighborhoodIterator.h" #include "itkConstNeighborhoodIterator.h" #include "itkShapedNeighborhoodIterator.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkRescaleIntensityImageFilter.h" #include "itkSignedDanielssonDistanceMapImageFilter.h" #include "itkDanielssonDistanceMapImageFilter.h" #include "itkShrinkImageFilter.h" // // for Voronoi diagram creation & use // #include "itkPointSet.h" // #include "itkVoronoiDiagram2D.h" // #include "itkVoronoiDiagram2DGenerator.h" // #include "itkMeshSpatialObject.h" // #include "itkSpatialObjectToImageFilter.h" //VTK includes //basics #include "vtkSmartPointer.h" #include "vtkMath.h" #include "vtkPoints.h" #include "vtkImageData.h" #include "vtkPolyData.h" #include "vtkUnstructuredGrid.h" #include "vtkPointData.h" #include "vtkDataArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" #include "vtkIdTypeArray.h" #include "vtkTIFFWriter.h" #include "vtkPolyDataWriter.h" #include "vtkGenericCell.h" #include "vtkPolygon.h" #include "vtkTriangle.h" #include "vtkTetra.h" #include "vtkPlane.h" #include "vtkLine.h" #include "vtkCylinder.h" #include "vtkCutter.h" #include "vtkClipPolyData.h" #include "vtkTransform.h" #include "vtkParametricSpline.h" #include "vtkKochanekSpline.h" #include "vtkBoundingBox.h" #include "vtkImageImport.h" #include "vtkImageExport.h" #include "vtkBox.h" #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkActor.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> //algorithms #include "vtkContourFilter.h" #include "vtkMarchingCubes.h" #include "vtkSmoothPolyDataFilter.h" #include "vtkWindowedSincPolyDataFilter.h" #include "vtkSurfaceReconstructionFilter.h" #include "vtkCellLocator.h" #include "vtkSelectPolyData.h" #include "vtkExtractPolyDataGeometry.h" #include "vtkTransformPolyDataFilter.h" #include "vtkAppendFilter.h" #include "vtkAppendPolyData.h" #include "vtkPolyDataNormals.h" #include "vtkHull.h" #include "vtkPointsProjectedHull.h" #include "vtkDelaunay2D.h" #include "vtkDelaunay3D.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkButterflySubdivisionFilter.h" #include "vtkLoopSubdivisionFilter.h" #include "vtkSelectEnclosedPoints.h" typedef float CalcPixelType; typedef unsigned char PixelType; typedef itk::Image< PixelType, 3 > ImageType; typedef itk::Image< PixelType, 2 > Image2DType; typedef itk::Image< CalcPixelType, 3 > CalcImageType; typedef itk::Image< CalcPixelType, 2 > CalcImage2DType; typedef itk::NeighborhoodIterator< ImageType > SegNeighborhoodIteratorType; typedef itk::NeighborhoodIterator< CalcImageType > CalcNeighborhoodIteratorType; typedef itk::ShapedNeighborhoodIterator< ImageType > ShapedNeighborhoodIteratorType; typedef itk::ShapedNeighborhoodIterator< CalcImageType > ShapedCalcNeighborhoodIteratorType; typedef itk::ImageRegionIterator< ImageType > IteratorType2; typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; typedef itk::ImageRegionIterator< Image2DType > Iterator2DType; typedef itk::ImageRegionIterator< CalcImageType > CalcIteratorType; typedef itk::ImageRegionIterator< CalcImage2DType > Calc2DIteratorType; typedef itk::ImageRegionConstIterator< CalcImageType > ConstCalcIteratorType; typedef itk::ImageRegionIteratorWithIndex< ImageType > IndexIteratorType; typedef itk::RescaleIntensityImageFilter< CalcImage2DType, Image2DType > CalcImage2DToImage2DFilterType; typedef itk::SignedDanielssonDistanceMapImageFilter< ImageType, CalcImageType > DistanceMapImageFilterType; typedef itk::DanielssonDistanceMapImageFilter< ImageType, CalcImageType > DistanceMapImageFilterType2; typedef itk::ImageFileWriter< Image2DType > Image2DWriterType; typedef itk::ImageFileReader< Image2DType > Image2DReaderType; typedef itk::VTKImageImport< ImageType > VTK2ITKImageImportType; typedef itk::VTKImageExport< CalcImageType > ITK2VTKCalcImageExportType; typedef std::vector< SegNeighborhoodIteratorType::OffsetType > NeighborhoodOffsetVectorType; typedef std::vector< ShapedNeighborhoodIteratorType::OffsetType > ShapedNeighborhoodOffsetVectorType; typedef itk::ShrinkImageFilter<Image2DType, Image2DType> ShrinkImageFilterType; // typedef itk::PointSet< PixelType, 2 > itkPointSetType; // typedef itkPointSetType::PointType itkPointType; // typedef itk::VoronoiDiagram2D< float > VoronoiDiagramType; // typedef itk::VoronoiDiagram2DGenerator< float > VoronoiDiagramGeneratorType; // typedef itk::MeshSpatialObject< VoronoiDiagramType > VoronoiDiagramSpatialObjectType; // typedef itk::SpatialObjectToImageFilter< VoronoiDiagramSpatialObjectType, Image2DType > VoronoiDiagramToImageFilterType; typedef vtkSmartPointer< vtkPoints > PointsPointerType; typedef vtkSmartPointer< vtkDataArray > DataArrayPointerType; typedef vtkSmartPointer< vtkFloatArray > FloatArrayPointerType; typedef vtkSmartPointer< vtkDoubleArray > DoubleArrayPointerType; typedef vtkSmartPointer< vtkIdTypeArray > IdTypeArrayPointerType; typedef vtkSmartPointer< vtkPolygon > PolygonPointerType; typedef vtkSmartPointer< vtkTriangle > TrianglePointerType; typedef vtkSmartPointer< vtkTetra > TetraPointerType; typedef vtkSmartPointer< vtkIdList > IdListPointerType; typedef vtkSmartPointer< vtkPlane > PlanePointerType; typedef vtkSmartPointer< vtkLine > LinePointerType; typedef vtkSmartPointer< vtkCylinder > CylinderPointerType; typedef vtkSmartPointer< vtkCutter > CutterPointerType; typedef vtkSmartPointer< vtkClipPolyData > ClipPolyDataPointerType; typedef vtkSmartPointer< vtkTransform > TransformPointerType; typedef vtkSmartPointer< vtkMatrix4x4 > HomogeneousMatrixPointerType; typedef vtkSmartPointer< vtkParametricSpline > ParametricSplinePointerType; typedef vtkSmartPointer< vtkKochanekSpline > KochanekSplinePointerType; typedef vtkSmartPointer< vtkBoundingBox > BoundingBoxPointerType; typedef vtkSmartPointer< vtkImageData > ImageDataPointerType; typedef vtkSmartPointer< vtkPolyData > PolyDataPointerType; typedef vtkSmartPointer< vtkUnstructuredGrid > UnstructuredGridPointerType; typedef vtkSmartPointer< vtkTIFFWriter > TiffWriterPointerType; typedef vtkSmartPointer< vtkPolyDataWriter > PolyDataWriterPointerType; typedef vtkSmartPointer< vtkGenericCell > GenericCellPointerType; typedef vtkSmartPointer< vtkCell > CellPointerType; typedef vtkSmartPointer< vtkImageImport > ITK2VTKImageImportPointerType; typedef vtkSmartPointer< vtkImageExport > VTK2ITKImageExportPointerType; typedef vtkSmartPointer< vtkMarchingCubes > MarchingCubesPointerType; typedef vtkSmartPointer< vtkContourFilter > ContourFilterPointerType; typedef vtkSmartPointer< vtkSmoothPolyDataFilter > AveragePolyDataFilterType; typedef vtkSmartPointer< vtkWindowedSincPolyDataFilter > LowpassPolyDataFilterType; typedef vtkSmartPointer< vtkSurfaceReconstructionFilter > SurfaceReconstructionFilterType; typedef vtkSmartPointer< vtkCellLocator > CellLocatorPointerType; typedef vtkSmartPointer< vtkSelectPolyData > SelectPolyDataPointerType; typedef vtkSmartPointer< vtkExtractPolyDataGeometry > ExtractPolyDataGeometryPointerType; typedef vtkSmartPointer< vtkTransformPolyDataFilter > TransformFilterType; typedef vtkSmartPointer< vtkAppendFilter > AppendFilterPointerType; typedef vtkSmartPointer< vtkAppendPolyData > AppendPolyDataPointerType; typedef vtkSmartPointer< vtkPolyDataNormals > PolyDataNormalsPointerType; typedef vtkSmartPointer< vtkHull > ConvexHullFilterPointerType; typedef vtkSmartPointer< vtkPointsProjectedHull > ConvexHull2DFilterPointerType; typedef vtkSmartPointer< vtkDelaunay2D > Delaunay2DFilterPointerType; typedef vtkSmartPointer< vtkDelaunay3D > Delaunay3DFilterPointerType; typedef vtkSmartPointer< vtkDataSetSurfaceFilter > DataSetSurfaceFilterPointerType; typedef vtkSmartPointer< vtkButterflySubdivisionFilter > MeshRefinementFilterPointerType; typedef vtkSmartPointer< vtkLoopSubdivisionFilter > MeshRefinementFilter2PointerType; typedef vtkSmartPointer< vtkSelectEnclosedPoints > SelectEnclosedPointsFilterType; typedef std::pair< unsigned int, unsigned int > ColumnCellTypePair; typedef std::pair< unsigned int, unsigned int > MatrixIndexType; typedef std::vector< unsigned int > SelectionType; extern float XYSAMPLING; extern float ZSAMPLING; extern float averageSomaRadius; extern float zScale; extern unsigned long BINSIZE; extern unsigned long BOXSIZE; //VoxelFeatures of the Measurement Vector Type #define X_COORD 0 #define Y_COORD 1 #define Z_COORD 2 //celltypes for automatic dendrite detection #define SUPRA 1 #define GRAN 2 #define INFRA 3 //Label IDs for Amira Spatial Graphs #define Neuron 2 #define Dendrite 3 #define ApicalDendrite 4 #define BasalDendrite 5 #define Axon 6 #define Soma 7 #define Landmark 8 #define Pia 9 #define WhiteMatter 48 #define Vessel 10 #define Barrel 11 #define ZAxis 50 #define aRow 12 #define A1 13 #define A2 14 #define A3 15 #define A4 16 #define bRow 17 #define B1 18 #define B2 19 #define B3 20 #define B4 21 #define cRow 22 #define C1 23 #define C2 24 #define C3 25 #define C4 26 #define C5 27 #define C6 28 #define dRow 29 #define D1 30 #define D2 31 #define D3 32 #define D4 33 #define D5 34 #define D6 35 #define eRow 36 #define E1 37 #define E2 38 #define E3 39 #define E4 40 #define E5 41 #define E6 42 #define greekRow 43 #define Alpha 44 #define Beta 45 #define Gamma 46 #define Delta 47 #define Septum 0 // cell types for NeuroNet Connectome analysis #define L2 1 #define L34 2 #define L4py 3 #define L4sp 4 #define L4ss 5 #define L5st 6 #define L5tt 7 #define L6cc 8 #define L6ccinv 9 #define L6ct 10 #define VPM 11 #define L2axon 12 #define L34axon 13 #define L4pyaxon 14 #define L4spaxon 15 #define L4ssaxon 16 #define L5staxon 17 #define L5ttaxon 18 #define L6ccaxon 19 #define L6ccinvaxon 20 #define L6ctaxon 21 #define SymLocal 22 #define SymLocal1 23 #define SymLocal2 24 #define SymLocal3 25 #define SymLocal4 26 #define SymLocal5 27 #define SymLocal6 28 #define L1 29 #define L23Trans 30 #define L45Sym 31 #define L45Peak 32 #define L56Trans 33 #define SymLocalaxon 34 #define SymLocal1axon 35 #define SymLocal2axon 36 #define SymLocal3axon 37 #define SymLocal4axon 38 #define SymLocal5axon 39 #define SymLocal6axon 40 #define L1axon 41 #define L23Transaxon 42 #define L45Symaxon 43 #define L45Peakaxon 44 #define L56Transaxon 45 //168fines #endif
{ "alphanum_fraction": 0.6835102716, "avg_line_length": 39.0997304582, "ext": "h", "hexsha": "85d73da2c5a8832d7dd401d6da07bea6174e92d0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8b456c41e72958677cb6035028d9c23013cb7c7e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zibneuro/udvary-et-al-2022", "max_forks_repo_path": "analysis/preprocessing/cpp/truncateCell/src/typedefs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8b456c41e72958677cb6035028d9c23013cb7c7e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zibneuro/udvary-et-al-2022", "max_issues_repo_path": "analysis/preprocessing/cpp/truncateCell/src/typedefs.h", "max_line_length": 125, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8b456c41e72958677cb6035028d9c23013cb7c7e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zibneuro/udvary-et-al-2022", "max_stars_repo_path": "analysis/preprocessing/cpp/truncateCell/src/typedefs.h", "max_stars_repo_stars_event_max_datetime": "2022-03-11T13:43:50.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-11T13:43:50.000Z", "num_tokens": 3779, "size": 14506 }
#include <stdlib.h> #include <gsl/gsl_vector.h> #include "../include/type.h" #include "../include/global.h" #include "../include/cthreadpool.h" void *pool_thread(void *arg) { threadpool_t *pool = (threadpool_t*)arg; task_t task; int head; while(1) { pthread_mutex_lock(&(pool->pool_lock)); while(pool->task_count == 0 && pool->flag != POOL_RECLAIM) { pthread_cond_wait(&(pool->notify), &(pool->pool_lock)); } if (pool->task_count == 0 && pool->flag == POOL_RECLAIM) { break; } head = pool->task_head; task.func = pool->tasks[head].func; task.arg = pool->tasks[head].arg; pool->task_head++; pool->task_count--; pthread_mutex_unlock(&(pool->pool_lock)); *(pool->tasks[head].ret) = (task.func)(task.arg); } pthread_mutex_unlock(&(pool->pool_lock)); return NULL; } threadpool_t* threadpool_create(const int nthread, const int queue_size) { int i = 0; threadpool_t *pool = NULL; if ((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) { return NULL; } pool->nthread = nthread; pool->queue_size = queue_size; pool->task_head = 0; pool->task_tail = -1; pool->task_count = 0; pthread_mutex_init(&pool->pool_lock, NULL); pthread_cond_init(&pool->notify, NULL); pool->working = (int*)malloc(sizeof(int)*nthread); pool->threads = (pthread_t*)malloc(sizeof(pthread_t)*nthread); pool->tasks = (task_t*)malloc(sizeof(task_t)*queue_size); for (i = 0; i < nthread; ++i) { pool->working[i] = IDLE; } for(i = 0; i < nthread; i++) { if(pthread_create(&(pool->threads[i]), NULL, pool_thread, (void*)pool) != 0) { threadpool_reclaim(pool); return NULL; } pool->working[i] = INCOMPLETED; } return pool; } int threadpool_add(threadpool_t *pool, void* (*func)(void *), void *arg, void **ret) { int tail; if (pool == NULL || func == NULL) { return POOL_ADD_ERR; } if(pthread_mutex_lock(&(pool->pool_lock)) != 0) { return POOL_LOCK_FAILURE; } tail = pool->task_tail + 1; tail = tail == pool->queue_size? 0:tail; if (pool->task_count == pool->queue_size) { // TODO erroneous. if ((realloc(pool->tasks, 2 * pool->queue_size)) != 0) { return POOL_ADD_ERR; } tail = pool->queue_size; pool->queue_size *= 2; } pool->tasks[tail].func = func; pool->tasks[tail].arg = arg; pool->tasks[tail].ret = ret; pool->task_tail = tail; pool->task_count++; if(pthread_cond_signal(&(pool->notify)) != 0 || pthread_mutex_unlock(&pool->pool_lock) != 0) { return POOL_LOCK_FAILURE; } return 0; } int threadpool_reclaim(threadpool_t *pool) { int i = 0; if(pthread_mutex_lock(&(pool->pool_lock)) != 0) { return POOL_LOCK_FAILURE; } pool->flag = POOL_RECLAIM; pthread_mutex_unlock(&(pool->pool_lock)); for (i = 0; i < pool->nthread; ++i) { if (pool->working[i] != IDLE) { pthread_join(pool->threads[i], NULL); } } free(pool->threads); free(pool->tasks); free(pool); return 0; }
{ "alphanum_fraction": 0.574034661, "avg_line_length": 24.1838235294, "ext": "c", "hexsha": "a353e244066136bc1c4eae91d66645d6e9b38e26", "lang": "C", "max_forks_count": 39, "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z", "max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "chunjie-sam-liu/rmats-turbo", "max_forks_repo_path": "rMATS_C/src/cthreadpool.c", "max_issues_count": 163, "max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "chunjie-sam-liu/rmats-turbo", "max_issues_repo_path": "rMATS_C/src/cthreadpool.c", "max_line_length": 86, "max_stars_count": 88, "max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "chunjie-sam-liu/rmats-turbo", "max_stars_repo_path": "rMATS_C/src/cthreadpool.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z", "num_tokens": 906, "size": 3289 }
/*************************************************************************** Copyright (c) 2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ // #include "bench.h" #include <cblas.h> #include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> // mlir-clang gemm.c -I .. -I /home/lchelini/scratch/polygeist/llvm-project/llvm/../clang/lib/Headers -o gemm --emit-llvm int main(int argc, char *argv[]) { float *a, *b; float *c; float alpha = 1.0; float beta = 1.0; char transa = 'N'; char transb = 'N'; int m, n, k, i, j, lda, ldb, ldc; m = 500; k = 500; n = 500; a = (float *)malloc(sizeof(float) * m * k); b = (float *)malloc(sizeof(float) * k * n); c = (float *)malloc(sizeof(float) * m * n); for (i = 0; i < m * k; i++) { a[i] = ((float)rand() / (float)RAND_MAX) - 0.5; } for (i = 0; i < k * n; i++) { b[i] = ((float)rand() / (float)RAND_MAX) - 0.5; } for (i = 0; i < m * n; i++) { c[i] = ((float)rand() / (float)RAND_MAX) - 0.5; } if (transa == 'N') { lda = m; } else { lda = k; } if (transb == 'N') { ldb = k; } else { ldb = n; } ldc = m; sgemm_(&transa, &transb, &m, &n, &k, &alpha, &(a[5]), &lda, b, &ldb, &beta, c, &ldc); fprintf(stderr, "%.6f\n", c[100]); return 0; }
{ "alphanum_fraction": 0.6420373027, "avg_line_length": 33.5903614458, "ext": "c", "hexsha": "8586bb1d5df023e8c26cfd1b538606482fd1f41f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "chelini/openBlas", "max_forks_repo_path": "benchmark/gemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "chelini/openBlas", "max_issues_repo_path": "benchmark/gemm.c", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "chelini/openBlas", "max_stars_repo_path": "benchmark/gemm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 762, "size": 2788 }
//-*-C++-*- /*************************************************************************** * * Copyright (C) 2008 by Willem van Straten * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ #ifndef __Pulsar_Interpolation_h #define __Pulsar_Interpolation_h #include "Reference.h" #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <vector> //! Interface to GSL interpolation routines class Interpolation : public Reference::Able { public: //! Default constructor Interpolation (); //! Destructor virtual ~Interpolation (); //! Initialize interpolation object void init (const std::vector<double>& x, const std::vector<double>& y); //! Evaluate at the given abscissa double eval (double x); protected: const double* xa; const double* ya; size_t size; gsl_interp* interp; gsl_interp_accel* acc; void destroy (); }; #endif
{ "alphanum_fraction": 0.5877466251, "avg_line_length": 19.26, "ext": "h", "hexsha": "f64c1f3a9401871f235dd7b1294c904ee2c22468", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_forks_repo_licenses": [ "AFL-2.1" ], "max_forks_repo_name": "rwharton/psrchive_dsn", "max_forks_repo_path": "Util/genutil/Interpolation.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AFL-2.1" ], "max_issues_repo_name": "rwharton/psrchive_dsn", "max_issues_repo_path": "Util/genutil/Interpolation.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_stars_repo_licenses": [ "AFL-2.1" ], "max_stars_repo_name": "rwharton/psrchive_dsn", "max_stars_repo_path": "Util/genutil/Interpolation.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 208, "size": 963 }
static char help[] = "ODE system solver example using TS, but with Jacobian. Sets TS type to\n" "implicit Crank-Nicolson. Compare ode.c.\n\n"; #include <petsc.h> extern PetscErrorCode ExactSolution(PetscReal, Vec); extern PetscErrorCode FormRHSFunction(TS, PetscReal, Vec, Vec, void*); extern PetscErrorCode FormRHSJacobian(TS, PetscReal, Vec, Mat, Mat, void*); int main(int argc,char **argv) { PetscErrorCode ierr; PetscInt steps; PetscReal t0 = 0.0, tf = 20.0, dt = 0.1, err; Vec y, yexact; Mat J; TS ts; ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr; ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr); ierr = VecSetSizes(y,PETSC_DECIDE,2); CHKERRQ(ierr); ierr = VecSetFromOptions(y); CHKERRQ(ierr); ierr = VecDuplicate(y,&yexact); CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr); //STARTMATJ ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr); ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr); ierr = MatSetFromOptions(J); CHKERRQ(ierr); ierr = MatSetUp(J); CHKERRQ(ierr); ierr = TSSetRHSJacobian(ts,J,J,FormRHSJacobian,NULL); CHKERRQ(ierr); ierr = TSSetType(ts,TSCN); CHKERRQ(ierr); //ENDMATJ // set time axis ierr = TSSetTime(ts,t0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetFromOptions(ts); CHKERRQ(ierr); // set initial values and solve ierr = TSGetTime(ts,&t0); CHKERRQ(ierr); ierr = ExactSolution(t0,y); CHKERRQ(ierr); ierr = TSSolve(ts,y); CHKERRQ(ierr); // compute error and report ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); ierr = TSGetTime(ts,&tf); CHKERRQ(ierr); ierr = ExactSolution(tf,yexact); CHKERRQ(ierr); ierr = VecAXPY(y,-1.0,yexact); CHKERRQ(ierr); // y <- y - yexact ierr = VecNorm(y,NORM_INFINITY,&err); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "error at tf = %.3f with %d steps: |y-y_exact|_inf = %g\n", tf,steps,err); CHKERRQ(ierr); MatDestroy(&J); VecDestroy(&y); VecDestroy(&yexact); TSDestroy(&ts); return PetscFinalize(); } PetscErrorCode ExactSolution(PetscReal t, Vec y) { PetscReal *ay; VecGetArray(y,&ay); ay[0] = t - PetscSinReal(t); ay[1] = 1.0 - PetscCosReal(t); VecRestoreArray(y,&ay); return 0; } PetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec y, Vec g, void *ptr) { const PetscReal *ay; PetscReal *ag; VecGetArrayRead(y,&ay); VecGetArray(g,&ag); ag[0] = ay[1]; // = g_1(t,y) ag[1] = - ay[0] + t; // = g_2(t,y) VecRestoreArrayRead(y,&ay); VecRestoreArray(g,&ag); return 0; } //STARTJACOBIAN PetscErrorCode FormRHSJacobian(TS ts, PetscReal t, Vec y, Mat J, Mat P, void *ptr) { PetscErrorCode ierr; PetscInt row[2] = {0, 1}, col[2] = {0, 1}; PetscReal v[4] = { 0.0, 1.0, -1.0, 0.0}; ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; } //ENDJACOBIAN
{ "alphanum_fraction": 0.6465874551, "avg_line_length": 34.141509434, "ext": "c", "hexsha": "319c5ccf9d7f5711ba64adb7131adb4c1f86d23f", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch5/odejac.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch5/odejac.c", "max_line_length": 76, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch5/odejac.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 1154, "size": 3619 }
#ifndef INCLUDED_TELEPATH_MATRIX_H #define INCLUDED_TELEPATH_MATRIX_H #include <cblas.h> #include "telepath/blas/traits.h" namespace telepath{ enum ORDER { ROW_MAJOR = CblasRowMajor, COL_MAJOR = CblasColMajor }; enum TRANSPOSE { NONE = CblasNoTrans, TRANS = CblasTrans, CONJ_TRANS = CblasConjTrans }; enum UPLO{ UPPER = CblasUpper, LOWER = CblasLower, }; /* Struct for storing BLAS matrix data */ template< typename T > struct matrix{ ORDER layout; TRANSPOSE trans; T* array; std::size_t rows; std::size_t cols; std::size_t ld; }; template< typename T > struct sym_matrix{ ORDER layout; TRANSPOSE trans; UPLO uplo; T* array; std::size_t rows; std::size_t cols; std::size_t ld; }; } //namespace telepath namespace blas{ template< typename T > struct Traits< const telepath::matrix<T> >{ using mat_t = typename telepath::matrix<T>; const mat_t& mat; constexpr Traits( const mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< telepath::matrix<T> >{ using mat_t = typename telepath::matrix<T>; mat_t& mat; constexpr Traits( mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } inline T* array() { return mat.array; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< const telepath::sym_matrix<T> >{ using mat_t = telepath::sym_matrix<T>; const mat_t& mat; constexpr Traits( const mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr telepath::UPLO uplo() const{ return mat.uplo; } constexpr const T* array() const{ return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct Traits< telepath::sym_matrix<T> >{ using mat_t = typename telepath::sym_matrix<T>; mat_t& mat; constexpr Traits( mat_t& m ) : mat( m ) { } constexpr telepath::ORDER layout() const{ return mat.layout; } constexpr telepath::TRANSPOSE trans() const{ return mat.trans; } constexpr telepath::UPLO uplo() const{ return mat.uplo; } constexpr const T* array() const{ return mat.array; } inline T* array() { return mat.array; } constexpr auto nrows() const{ return mat.rows; } constexpr auto ncols() const{ return mat.cols; } constexpr auto ld() const{ return mat.ld; } }; template< typename T > struct MatrixTraits< telepath::matrix<T> >{ using mat = typename telepath::matrix<T>; using scalar_t = T; constexpr static CBLAS_ORDER layout( const mat& m ){ return (CBLAS_ORDER) m.layout; } constexpr static CBLAS_TRANSPOSE trans( const mat& m ){ return (CBLAS_TRANSPOSE) m.trans; } constexpr static auto nrows( const mat& m ){ return m.rows; } constexpr static auto ncols( const mat& m ){ return m.cols; } constexpr static T* array( mat& m ){ return m.array; } constexpr static const T* array( const mat& m ){ return m.array; } constexpr static auto ld( const mat& m ){ return m.ld; } }; template< typename T > struct MatrixTraits< telepath::sym_matrix<T> >{ using mat = typename telepath::sym_matrix<T>; using scalar_t = T; constexpr static CBLAS_ORDER layout( const mat& m ){ return (CBLAS_ORDER) m.layout; } constexpr static CBLAS_TRANSPOSE trans( const mat& m ){ return (CBLAS_TRANSPOSE) m.trans; } constexpr static CBLAS_UPLO uplo( const mat& m ){ return (CBLAS_UPLO) m.uplo; } constexpr static auto nrows( const mat& m ){ return m.rows; } constexpr static auto ncols( const mat& m ){ return m.cols; } constexpr static T* array( mat& m ){ return m.array; } constexpr static const T* array( const mat& m ){ return m.array; } constexpr static auto ld( const mat& m ){ return m.ld; } }; } //namespace blas #endif
{ "alphanum_fraction": 0.6005830904, "avg_line_length": 35, "ext": "h", "hexsha": "7ce46eb16e74d6841b3cb0f8fe9a08aa9f2156fd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tbepler/telepath", "max_forks_repo_path": "include/telepath/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tbepler/telepath", "max_issues_repo_path": "include/telepath/matrix.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tbepler/telepath", "max_stars_repo_path": "include/telepath/matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1244, "size": 5145 }
#include <stdio.h> #include <gsl/gsl_fit.h> int main (void) { int n = 11; double x[11] = {10.0, 8.0, 13.0, 9.0, 11.0, 14.0 ,6.0, 4.0 , 12.0,7.0,5.0}; double y[11] = {8.04, 6.95,7.68, 8.81, 8.33, 9.96, 7.24,4.26,10.84, 4.82,5.68 }; double c0, c1, cov00, cov01, cov11, sumsq; gsl_fit_linear(x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); printf ("best fit: Y = %g + %g X\n", c0, c1); printf ("covariance matrix:\n"); printf ("[ %g, %g\n %g, %g]\n", cov00, cov01, cov01, cov11); printf ("sumsq = %g\n", sumsq); printf ("\n"); // plot FILE *pipe = popen("gnuplot -persist", "w"); // Open a pipe to gnuplot if (pipe) // If gnuplot is found { fprintf(pipe, "set term wx\n"); // set the terminal fprintf(pipe, "set xlabel 'X'\n"); fprintf(pipe, "set ylabel 'Y'\n"); fprintf(pipe, "set xrange [0:20]\n"); fprintf(pipe, "set yrange [2:14]\n"); fprintf(pipe, "set title '<X,Y> and Linear fit:y=%.4f*x+%.4f'\n",c1,c0); /* In this case, the datafile is written directly to the gnuplot pipe with no need for a temporary file. The special filename '-' specifies that the data are inline; i.e., they follow the command. 1 sending gnuplot the plot '-' command 2 followed by data points 3 followed by the letter "e" */ // 1 sending gnuplot the plot '-' command fprintf(pipe, "plot '-' title '<x,y>' with points pt 7 lc rgb 'blue',\ '-' title 'Line' with linespoints pt 6 lc rgb 'red'\n"); // 2 followed by data points: <x,y> for (int i = 0; i < n; i++) { fprintf(pipe, "%lf %lf\n", x[i], y[i]); } // 3 followed by the letter "e" fprintf(pipe, "e"); // linear fit fprintf(pipe,"\n"); // start a new draw item fprintf(pipe, "%lf %lf\n", 0.0, c0+c1*0,0); for (int i = 0; i < n; i++) { fprintf(pipe, "%lf %lf\n", x[i], c0+c1*x[i]); } fprintf(pipe, "%lf %lf\n", 20.0,c0+c1*20,0); fprintf(pipe, "e"); fflush(pipe); fprintf(pipe, "exit \n"); // exit gnuplot pclose(pipe); //close pipe } return 0; }
{ "alphanum_fraction": 0.4950917627, "avg_line_length": 32.5416666667, "ext": "c", "hexsha": "a0caf8402ed5b8f30fa064403a2db861ffd5873b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_path": "notebook/demo/src/gnuplot_pipe_array.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 795, "size": 2343 }
#include <stdlib.h> #include <stdio.h> //#define VERY_VERBOSE #define MSG(x) { printf(x); fflush(stdout); } #define MSGF(x) { printf x ; fflush(stdout); } #include "buffer.h" static void test_buffer() { } #include "array.h" static void test_array() { int k; const int * p; const int * q; OLIO_ARRAY_STACK(st, int, 64); olio_array * hp; OLIO_ARRAY_ALLOC(hp, int, 0); printf("[testing array...]\n"); fflush(stdout); MSGF(("st %u\n", st->base.allocated)); MSGF(("hp %u\n", hp->base.allocated)); #define ARRAY_COUNT 1000 MSG("appending to arrays...\n"); for (k = 0; k < ARRAY_COUNT; k++) { olio_array_append(st, &k, 1); olio_array_append(hp, &k, 1); } MSG("prepending to arrays...\n"); for (k = 0; k < ARRAY_COUNT; k++) { olio_array_prepend(st, &k, 1); olio_array_prepend(hp, &k, 1); } MSG("inserting to arrays...\n"); for (k = 0; k <= ARRAY_COUNT * 2; k++) { olio_array_insert(st, k * 2, &k, 1); olio_array_insert(hp, k * 2, &k, 1); } MSG("checking array contents...\n"); p = olio_array_contents(st); q = olio_array_contents(hp); for (k = 0; k < ARRAY_COUNT; k++) { if (p[k * 2 + 1] != ARRAY_COUNT - 1 - k || p[k * 2 + 1 + ARRAY_COUNT * 2] != k) MSG("ERROR: odd numbered stack item not as expected\n"); if (p[k * 2] != k || p[k * 2 + ARRAY_COUNT * 2] != k + ARRAY_COUNT) MSG("ERROR: even numbered stack item not as expected\n"); if (q[k * 2 + 1] != ARRAY_COUNT - 1 - k || q[k * 2 + 1 + ARRAY_COUNT * 2] != k) MSG("ERROR: odd numbered heap item not as expected\n"); if (q[k * 2] != k || q[k * 2 + ARRAY_COUNT * 2] != k + ARRAY_COUNT) MSG("ERROR: even numbered heap item not as expected\n"); } if (p[ARRAY_COUNT * 4] != ARRAY_COUNT * 2) MSG("ERROR: last item in stack array not as expected\n"); if (q[ARRAY_COUNT * 4] != ARRAY_COUNT * 2) MSG("ERROR: last item in heap array not as expected\n"); #ifdef VERY_VERBOSE for (k = 0; k < olio_array_length(st) || k < olio_array_length(hp); k++) { MSGF(("%i: st % 4i hp % 4i\n", k, (k < olio_array_length(st)) ? p[k] : -1, (k < olio_array_length(hp)) ? q[k] : -1)); } #endif MSGF(("st %p = %p\n", st->base.data, st->stack)); MSGF(("hp %p = %p\n", hp->base.data, hp->stack)); MSG("freeing arrays...\n"); olio_array_free(st); olio_array_free(hp); } #include "string.h" static void test_string() { } #include "graph.h" static void test_graph() { int rc; olio_graph g; printf("[testing graph...]\n"); fflush(stdout); printf("graph initialization...\n"); fflush(stdout); olio_graph_init(&g, 10); printf("graph setting edges...\n"); fflush(stdout); olio_graph_set_edge(&g, 0, 1, 10); olio_graph_set_edge(&g, 1, 2, 10); printf("graph testing cyclic...\n"); fflush(stdout); rc = olio_graph_acyclic(&g); if (rc == 0) { printf("ERROR: graph NOT acyclic\n"); fflush(stdout); } printf("graph setting edges...\n"); fflush(stdout); olio_graph_set_edge(&g, 2, 0, 10); MSG("graph testing cyclic...\n"); rc = olio_graph_acyclic(&g); if (rc != 0) MSG("ERROR: graph NOT cyclic\n"); MSG("freeing graph...\n"); olio_graph_free(&g); } #include "skiplist.h" static void test_skiplist() { uint32_t test_data[] = {0xf, 0x436, 0x53547, 0x65, 0x54, 0x5654, 0x8756, 0x8767}; olio_skiplist sk; int i; printf("sizeof(entry) = %li\n", sizeof(olio_skiplist_entry)); printf("sizeof(block) = %li\n", sizeof(olio_skiplist_block)); printf("sizeof(skiplist) = %li\n", sizeof(olio_skiplist)); olio_skiplist_init(&sk); printf("adding...\n"); for (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) { int rv = olio_skiplist_add(&sk, test_data[i], (void*) test_data[i]); printf("k: 0x%x, rv: %i\n", test_data[i], rv); } printf("searching...\n"); for (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) { void * d = olio_skiplist_find(&sk, test_data[i]); printf("k: 0x%x, data: %p\n", test_data[i], d); } olio_skiplist_display(&sk); printf("freeing...\n"); olio_skiplist_free(&sk); olio_skiplist_display(&sk); olio_skiplist_init(&sk); printf("adding...\n"); for (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) { int rv = olio_skiplist_add(&sk, test_data[i], (void*) test_data[i]); printf("k: 0x%x, rv: %i\n", test_data[i], rv); } printf("deleting...\n"); for (i = 0; i < sizeof(test_data) / sizeof(uint32_t); i++) { void * d; int rv = olio_skiplist_remove(&sk, test_data[i], &d); printf("k: 0x%x, rv: %i, data: %p\n", test_data[i], rv, d); olio_skiplist_display(&sk); } printf("freeing...\n"); olio_skiplist_free(&sk); olio_skiplist_display(&sk); } #include "error.h" static void test_error() { } #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include "random.h" gsl_rng * gsl; olio_random olio; static void test_random() { uint32_t seed; uint32_t a, b; long i; printf("[testing random...]\n"); fflush(stdout); gsl = gsl_rng_alloc(gsl_rng_mt19937); //for (seed = 0; seed < 1000; seed++) { seed = 0; gsl_rng_set(gsl, 0); olio_random_set_seed(&olio, 4357); for (i = 0; i < 10000; i++) { a = gsl_rng_uniform_int(gsl, 0xffffffff); b = olio_random_integer(&olio); if (a != b) { printf("mismatch\n"); } } } gsl_rng_free(gsl); } #else static void test_random() {} #endif #include "phash.h" #include "hash.h" static void test_hashes() { unsigned long i; const char * s[] = { "alpha", "beta", "gamma", "delta", "epsilon", "lamda", "mu", "nu", "omicron", "pi", "phi", "psi", "tau", "theta", "zeta", NULL }; olio_phash_build m; int rc; printf("[testing hashes...]\n"); fflush(stdout); rc = olio_phash_init(&m, NULL); if (rc == -1) { printf("error, aborting\n"); exit(1); } for (i = 0; s[i] != NULL; i++) { rc = olio_phash_add_entry(&m, s[i], strlen(s[i]), i * 1000); if (rc == -1) { printf("error, aborting\n"); exit(1); } } rc = olio_phash_generate(&m, 1000, 1); if (rc < 0) { printf("error, aborting\n"); exit(1); } if (rc > 0) { printf("failed to generate with attempt/extra limits\n"); exit(1); } printf("phash generated:\n"); printf("A hash: %08x\nB hash: %08x\nG size: %u\n", m.phash->a_hash_seed, m.phash->b_hash_seed, m.phash->g_table_size); printf("{ "); for (i = 0; i < m.phash->g_table_size; i++) { int16_t * gv = (int16_t *) m.phash->data; printf("%i, ", gv[i]); } printf("}\n"); for (i = 0; s[i] != NULL; i++) { int32_t v = olio_phash_value(m.phash, s[i], strlen(s[i])); printf(" %s -> %li\n", s[i], v); } olio_phash_free(&m); } #include "varint.h" static void test_varint_sub(uint32_t x, uint8_t bytes_expected) { uint32_t a; uint8_t storage[5]; uint8_t bytes_set, bytes_get; uint8_t i; bytes_set = olio_varint_set(x, storage); a = olio_varint_get(storage, &bytes_get); if (a != x || bytes_set != bytes_get || bytes_set != bytes_expected) { printf("x = %lu\n(%u) 0x", x, bytes_set); for (i = 0; i < bytes_set; i++) printf("%02x", storage[i]); printf("\na = %lu\n(%u)\n\n", a, bytes_get); } } static void test_varint() { printf("[testing varint...]\n"); fflush(stdout); test_varint_sub(0, 1); test_varint_sub(1,1); test_varint_sub(127, 1); test_varint_sub(200, 2); test_varint_sub(32000, 3); test_varint_sub(32000000, 3); test_varint_sub(100000000, 4); test_varint_sub(400000000, 5); test_varint_sub(0, 1); test_varint_sub(1, 1); } int main(int argv, char ** argc) { test_buffer(); test_array(); test_string(); test_graph(); test_skiplist(); test_error(); test_random(); test_hashes(); test_varint(); }
{ "alphanum_fraction": 0.598961039, "avg_line_length": 22.514619883, "ext": "c", "hexsha": "69cc9847e81a8be46bd9fcbdfc7b61508169f93e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jabr/olio", "max_forks_repo_path": "test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jabr/olio", "max_issues_repo_path": "test.c", "max_line_length": 82, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e237053d4026e9e78564f1ad354143c8dd6b4b69", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jabr/olio", "max_stars_repo_path": "test.c", "max_stars_repo_stars_event_max_datetime": "2018-11-25T05:53:52.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-25T05:53:52.000Z", "num_tokens": 2610, "size": 7700 }
#pragma once #include "AsyncSystem.h" #include "IAssetRequest.h" #include "Library.h" #include <gsl/span> #include <cstddef> #include <memory> #include <string> #include <vector> namespace CesiumAsync { class AsyncSystem; /** * @brief Provides asynchronous access to assets, usually files downloaded via * HTTP. */ class CESIUMASYNC_API IAssetAccessor { public: /** * @brief An HTTP header represented as a key/value pair. */ typedef std::pair<std::string, std::string> THeader; virtual ~IAssetAccessor() = default; /** * @brief Starts a new request for the asset with the given URL. * The request proceeds asynchronously without blocking the calling thread. * * @param asyncSystem The async system used to do work in threads. * @param url The URL of the asset. * @param headers The headers to include in the request. * @return The in-progress asset request. */ virtual CesiumAsync::Future<std::shared_ptr<IAssetRequest>> requestAsset( const AsyncSystem& asyncSystem, const std::string& url, const std::vector<THeader>& headers = {}) = 0; /** * @brief Starts a new POST request to the given URL. * * The request proceeds asynchronously without blocking the calling thread. * * @param asyncSystem The async system used to do work in threads. * @param url The URL of the asset. * @param headers The headers to include in the request. * @param contentPayload The payload data of the POST. * @return The in-progress asset request. */ virtual CesiumAsync::Future<std::shared_ptr<IAssetRequest>> post( const AsyncSystem& asyncSystem, const std::string& url, const std::vector<THeader>& headers = std::vector<THeader>(), const gsl::span<const std::byte>& contentPayload = {}) = 0; /** * @brief Ticks the asset accessor system while the main thread is blocked. * * If the asset accessor is not dependent on the main thread to * dispatch requests, this method does not need to do anything. */ virtual void tick() noexcept = 0; }; } // namespace CesiumAsync
{ "alphanum_fraction": 0.6946564885, "avg_line_length": 29.5211267606, "ext": "h", "hexsha": "e13f4b68b7d55bd046db3a102864cd6ef8194733", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JiangMuWen/cesium-native", "max_forks_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "JiangMuWen/cesium-native", "max_issues_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_line_length": 78, "max_stars_count": 154, "max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JiangMuWen/cesium-native", "max_stars_repo_path": "CesiumAsync/include/CesiumAsync/IAssetAccessor.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 496, "size": 2096 }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 The Boeing Company * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Gary Pei <guangyu.pei@boeing.com> */ /* * This program is used to generate plots found in the paper * G. Pei and Tom Henderson, "Validation of ns-3 802.11b PHY model", * available online at http://www.nsnam.org/~pei/80211b.pdf * * It can be compiled as a C program and relies on a library installation of * the GNU Scientific Library (gsl). To compile: * gcc 80211b.c -o 80211b -lm -lgsl -lgslcblas * * The executable output should be redirected into a text file 80211b.txt * ./80211b > 80211b.txt * * Then gnuplot can load the associated plot file which references 80211b.txt: * gnuplot 80211b.plt */ #include "math.h" #include "stdlib.h" #include "stdio.h" #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_sf_bessel.h> #define min(a,b) ((a) < (b) ? (a) : (b)) #define max(a,b) ((a) > (b) ? (a) : (b)) #define WLAN_SIR_perfect 10.0 // if SIR > 10dB, perfect reception #define WLAN_SIR_impossible 0.1 // if SIR < -10dB, impossible to receive /** * \ingroup wifi * \defgroup wifi-test wifi module tests */ /** * \ingroup wifi-test * \ingroup tests * * \brief fn_parameter_t structure */ typedef struct fn_parameter_t { double beta; ///< beta double n; ///< n } fn_parameters; double QFunction (double x) { return 0.5 * erfc (x / sqrt (2.0)); } double f (double x, void * params) { double beta = ((fn_parameters *) params)->beta; double n = ((fn_parameters *) params)->n; double f = pow ( 2 * gsl_cdf_ugaussian_P (x + beta) - 1, n - 1) * exp (-x * x / 2.0) / sqrt (2.0 * M_PI); return f; } double p_e2 (double e2) { double sep; double error; fn_parameters params; params.beta = sqrt (2.0 * e2); params.n = 8.0; gsl_integration_workspace* w = gsl_integration_workspace_alloc (1000); gsl_function F; F.function = &f; F.params = &params; gsl_integration_qagiu (&F, -params.beta, 0, 1e-7, 1000, w, &sep, &error); gsl_integration_workspace_free (w); if (error == 0.0) { sep = 1.0; } return 1.0 - sep; } double p_e1 (double e1) { return 1.0 - pow ( 1.0 - p_e2 (e1 / 2.0), 2.0); } double DbToNoneDb (double x) { return pow (10.0, x / 10.0); } double NoneDbToDb (double x) { return 10.0 * log10 (x); } double DQPSKFunction (double x) { double pi = acos (-1.0); return ( (sqrt (2.0) + 1.0) / sqrt (8.0 * pi * sqrt (2.0))) * (1.0 / sqrt (x)) * exp ( -(2.0 - sqrt (2.0)) * x); } double Get80211bDsssDbpskBerIeee (double EcNc) { double ber; if (EcNc > WLAN_SIR_perfect) { ber = 0; } else if (EcNc < WLAN_SIR_impossible) { ber = 0.5; } else { ber = min (QFunction (sqrt (11.0 * EcNc)),0.5); } return ber; } double Get80211bDsssDbpskBer (double sinr) { double EbN0 = sinr * 22000000.0 / 1000000.0; double ber = 0.5 * exp (-EbN0); return ber; } double Get80211bDsssDqpskBerIeee (double EcNc) { double ber; if (EcNc > WLAN_SIR_perfect) { ber = 0; } else if (EcNc < WLAN_SIR_impossible) { ber = 0.5; } else { ber = min (QFunction (sqrt (5.5 * EcNc)),0.5); } return ber; } double Get80211bDsssDqpskBer (double sinr) { // 2 bits per symbol, 1 MSPS double EbN0 = sinr * 22000000.0 / 1000000.0 / 2.0; double ber = DQPSKFunction (EbN0); return ber; } double Get80211bDsssDqpskCCK5_5BerIeee (double EcNc) { double ber; if (EcNc > WLAN_SIR_perfect) { ber = 0.0; } else if (EcNc < WLAN_SIR_impossible) { ber = 0.5; } else { double pew = 14.0 * QFunction (sqrt (EcNc * 8.0)) + QFunction (sqrt (EcNc * 16.0)); pew = min (pew, 0.99999); ber = 8.0 / 15.0 * pew; } return ber; } double Get80211bDsssDqpskCCK11BerIeee (double EcNc) { double ber; if (EcNc > WLAN_SIR_perfect) { ber = 0.0; } else if (EcNc < WLAN_SIR_impossible) { ber = 0.5; } else { double pew = 24.0 * QFunction (sqrt (EcNc * 4.0)) + 16.0 * QFunction (sqrt (EcNc * 6.0)) + 174.0 * QFunction (sqrt (EcNc * 8.0)) + 16.0 * QFunction (sqrt (EcNc * 10.0)) + 24.0 * QFunction (sqrt (EcNc * 12.0)) + QFunction (sqrt (EcNc * 16.0)); pew = min (pew, 0.99999); ber = 128.0 / 255.0 * pew; } return ber; } int main (int argc, char * argv[]) { double rss, sinr; double totalPkt = 200.0; //double noise = 1.552058; // (dB) this noise figure value corresponds to // -99 dBm noise floor reported in CMU paper double noise = 7; // (dB) this noise figure value corresponds to the // default in YansWifiPhy, and matches CMU testbed results double EcNc, EbN01, EbN02, EbN05, EbN011; double ieee1,ieee2,ieee5,ieee11; double numBits = (1024. + 40. + 14.) * 8.; double dbpsk,dqpsk,cck16,cck256,sepcck16,sepcck256; noise = DbToNoneDb (noise) * 1.3803e-23 * 290.0 * 22000000; for (rss = -102.0; rss <= -80.0; rss += 0.1) { sinr = DbToNoneDb (rss) / 1000.0 / noise; EcNc = sinr * 22000000.0 / 11000000.0; // IEEE sir EbN01 = sinr * 22000000.0 / 1000000.0; // 2 bits per symbol, 1 MSPS EbN02 = sinr * 22000000.0 / 1000000.0 / 2.0; EbN05 = sinr * 22000000.0 / 1375000.0 / 4.0; EbN011 = sinr * 22000000.0 / 1375000.0 / 8.0; // 1=rss, 2=EcNc, 3=EbN01, 4=EbN02, 5=EBN05, 6=EbN011 printf ("%g %g %g %g %g %g ", rss, NoneDbToDb (EcNc), NoneDbToDb (EbN01),NoneDbToDb (EbN02), NoneDbToDb (EbN05),NoneDbToDb (EbN011)); ieee1 = Get80211bDsssDbpskBerIeee (EcNc); ieee2 = Get80211bDsssDqpskBerIeee (EcNc); ieee5 = Get80211bDsssDqpskCCK5_5BerIeee (EcNc); ieee11 = Get80211bDsssDqpskCCK11BerIeee (EcNc); // 7=ber_ieee1, 8=ber_ieee2, 9=ber_ieee5, 10=ber_ieee11 printf (" %g %g %g %g ", ieee1, ieee2,ieee5,ieee11); ieee1 = totalPkt * pow (1 - ieee1, numBits); ieee2 = totalPkt * pow (1 - ieee2, numBits); ieee5 = totalPkt * pow (1 - ieee5, numBits); ieee11 = totalPkt * pow (1 - ieee11, numBits); // 11=pkt_ieee1, 12=pkt_ieee2, 13=pkt_ieee5, 14=pkt_ieee11 printf (" %g %g %g %g ", ieee1, ieee2,ieee5,ieee11); dbpsk = Get80211bDsssDbpskBer (sinr); dqpsk = Get80211bDsssDqpskBer (sinr); cck16 = max (0, 8.0 / 15.0 * p_e2 (4.0 * EbN05 / 2.0)); cck256 = max (0, 128.0 / 255.0 * p_e1 (8.0 * EbN011 / 2.0)); // 15=ber_dbpsk, 16=ber_dqpsk, 17=ber_cck16, 18=ber_cck256 printf (" %g %g %g %g ", dbpsk, dqpsk,cck16,cck256); dbpsk = totalPkt * pow (1 - dbpsk,numBits); dqpsk = totalPkt * pow (1 - dqpsk,numBits); sepcck16 = p_e2 (4.0 * EbN05 / 2.0); sepcck256 = p_e1 (8.0 * EbN011 / 2.0); cck16 = totalPkt * pow (1.0 - sepcck16,numBits / 4.0); cck256 = totalPkt * pow (1.0 - sepcck256,numBits / 8.0); // 19=pkt_dbpsk, 20=pkt_dqpsk, 21=pkt_cck16, 22=pkt_cck256 printf (" %g %g %g %g ", dbpsk, dqpsk,cck16,cck256); // 23=sinr printf (" %g \n",NoneDbToDb (sinr)); } return 0; }
{ "alphanum_fraction": 0.6118750803, "avg_line_length": 28.9256505576, "ext": "c", "hexsha": "115fa8b5c1ffa5b48ee498f5582da57cb58f2f94", "lang": "C", "max_forks_count": 21, "max_forks_repo_forks_event_max_datetime": "2021-07-26T02:37:41.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-27T19:36:12.000Z", "max_forks_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zack-braun/4607_NS", "max_forks_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_issues_repo_issues_event_max_datetime": "2021-06-22T13:18:32.000Z", "max_issues_repo_issues_event_min_datetime": "2019-04-19T16:39:58.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zack-braun/4607_NS", "max_issues_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_line_length": 250, "max_stars_count": 93, "max_stars_repo_head_hexsha": "43c8fb772e5552fb44bd7cd34173e73e3fb66537", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zack-braun/4607_NS", "max_stars_repo_path": "ns-allinone-3.27/ns-3.27/src/wifi/test/80211b.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:26:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-21T08:22:26.000Z", "num_tokens": 2989, "size": 7781 }
/* * This file is part of the Visual Computing Library (VCL) release under the * license. * * Copyright (c) 2017 Basil Fierz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once // VCL configuration #include <vcl/config/global.h> // C++ Standard library #include <memory> #include <string> #include <tuple> #include <vector> // GSL #include <gsl/gsl> // Windows API #define WIN32_LEAN_AND_MEAN #include <Windows.h> extern "C" { # include <hidsdi.h> } // VCL #include <vcl/hid/device.h> namespace Vcl { namespace HID { namespace Windows { //! \note Structure definition taken from //! https://zfx.info/viewtopic.php?f=11&t=2977 //! https://www.codeproject.com/Articles/297312/Minimal-Key-Logger-using-RAWINPUT //! https://www.codeproject.com/Articles/185522/Using-the-Raw-Input-API-to-Process-Joystick-Input struct Axis { //! Usage page as defined in the standard (e.g. "generic (0001)") USAGE usagePage; //! Usage of the axis as defined in the standard (e.g. "slider (0036)") USAGE usage; //! Index as defined through Hidp_GetData() USHORT index; //! Minimum value defined by the HID device int32_t logicalMinimum; //! Maximum value defined by the HID device int32_t logicalMaximum; //! Indicate wheter DirectInput calibration data was applied bool isCalibrated; //! Minimum value after calibration int32_t logicalCalibratedMinimum; //! Maximum value after calibration int32_t logicalCalibratedMaximum; //! Through calibration defined center value of the axis int32_t logicalCalibratedCenter; //! Physical minimum value int32_t physicalMinimum; //! Physical maxiumum value int32_t physicalMaximum; //! Name as given by the driver std::wstring name; }; struct Button { //! Usage page as defined in the standard (e.g. "buttons (0009)") USAGE usagePage; //! Usage of the axis as defined in the standard (e.g. "secondary (0002)") USAGE usage; //! Index as defined through Hidp_GetData() USHORT index; //! Name as given by the driver std::wstring name; }; //! Normalize the axix value using the device configuration data inline float normalizeAxis(ULONG value, const Axis& axis) { if (static_cast<LONG>(value) < axis.logicalCalibratedCenter) { float range = static_cast<float>(axis.logicalCalibratedCenter - axis.logicalCalibratedMinimum); return (static_cast<LONG>(value) - axis.logicalCalibratedCenter) / range; } else { float range = static_cast<float>(axis.logicalCalibratedMaximum - axis.logicalCalibratedCenter); return (static_cast<LONG>(value) - axis.logicalCalibratedCenter) / range; } } class GenericHID { public: GenericHID(HANDLE raw_handle); //! Access the raw-input API handle //! \returns The input device handle HANDLE rawHandle() const { return _rawInputHandle; } //! Access the windows internal handle //! \returns The file handle to the device HANDLE fileHandle() const { return _fileHandle; } //! Access the vendor ID //! \returns The vendor ID DWORD vendorId() const { return _vendorId; } //! Access the product ID //! \returns The product ID DWORD productId() const { return _productId; } //! Read the device name from the hardware //! \returns The vendor defined names (vendor, product) auto readDeviceName() const -> std::pair<std::wstring, std::wstring>; const std::vector<Axis>& axes() const { return _axes; } const std::vector<Button>& buttons() const { return _buttons; } const std::vector<HIDP_VALUE_CAPS>& axisCaps() const { return _axesCaps; } const std::vector<HIDP_BUTTON_CAPS>& buttonCaps() const { return _buttonCaps; } private: //! Read the device capabilities auto readDeviceCaps() const -> std::tuple<std::vector<HIDP_BUTTON_CAPS>, std::vector<HIDP_VALUE_CAPS>>; //! Map buttons and fetch calibration data //! \param mapping Direct Input related remapping of buttons void readButtonCalibration(gsl::span<struct DirectInputButtonMapping> mapping) const; //! Map axes and fetch calibration data //! \param axes_caps void readAxisCalibration(const std::vector<HIDP_VALUE_CAPS>& axes_caps, gsl::span<struct DirectInputAxisMapping> mapping) const; //! Convert and store the button caps //! \param button_caps //! \param mapping Direct Input related remapping of buttons void storeButtons(std::vector<HIDP_BUTTON_CAPS>&& button_caps, gsl::span<struct DirectInputButtonMapping> mapping); //! Convert and store the axes caps //! \param axes_caps void storeAxes(std::vector<HIDP_VALUE_CAPS>&& axes_caps, gsl::span<struct DirectInputAxisMapping> mapping); private: //! Handle provided by the raw input API HANDLE _rawInputHandle{ nullptr }; //! Handle from the file API HANDLE _fileHandle{ nullptr }; //! Vendor ID DWORD _vendorId; //! Product ID DWORD _productId; //! Buttons associated with the device std::vector<Button> _buttons; //! Axes associated with the device std::vector<Axis> _axes; //! HID button representation std::vector<HIDP_BUTTON_CAPS> _buttonCaps; //! HID axis representation std::vector<HIDP_VALUE_CAPS> _axesCaps; }; class AbstractHID { public: AbstractHID(std::unique_ptr<GenericHID> device) : _device{ std::move(device) } {} const GenericHID* device() const { return _device.get(); } virtual bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) = 0; private: //! Actual hardware device implementation std::unique_ptr<GenericHID> _device; }; template<typename JoystickType> class JoystickHID : public AbstractHID, public JoystickType { public: JoystickHID(std::unique_ptr<GenericHID> device); bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override; }; template<typename GamepadType> class GamepadHID : public AbstractHID, public GamepadType { public: GamepadHID(std::unique_ptr<GenericHID> device); bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override; }; template<typename ControllerType> class MultiAxisControllerHID : public AbstractHID, public ControllerType { public: MultiAxisControllerHID(std::unique_ptr<GenericHID> device); bool processInput(HWND window_handle, UINT input_code, PRAWINPUT raw_input) override; }; class DeviceManager { public: DeviceManager(); gsl::span<Device const* const> devices() const; //! Register devices with a specific window //! \param device_types Types of devices for which input should //! be processed. //! \param window_handle Handle to the window to which devices should be //! registered. void registerDevices(Flags<DeviceType> device_types, HWND window_handle); //! Polls all the devices instead of processing only a single device //! \param window_handle Handle of the window calling this method //! \returns True, if any device was successfully polled. //! \note This method is implemented according to the documenation //! on MSDN. However, it seems not possible to call it. bool poll(HWND window_handle, UINT input_code); //! Process the input of a specific device bool processInput(HWND window_handle, UINT message, WPARAM wide_param, LPARAM low_param); private: //! List of Windows HID std::vector<std::unique_ptr<AbstractHID>> _devices; //! List of device pointers (links to `_devices`) std::vector<Device*> _deviceLinks; }; }}}
{ "alphanum_fraction": 0.7212121212, "avg_line_length": 31.2, "ext": "h", "hexsha": "64aa8d92126a8301f130eba6271f238432826b00", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bfierz/vcl.hid", "max_forks_repo_path": "src/vcl/hid/windows/hid.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "bfierz/vcl.hid", "max_issues_repo_path": "src/vcl/hid/windows/hid.h", "max_line_length": 130, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4193fe488d6759306e297b225e3a3c4da58716b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bfierz/vcl.hid", "max_stars_repo_path": "src/vcl/hid/windows/hid.h", "max_stars_repo_stars_event_max_datetime": "2020-03-26T20:39:34.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-26T20:39:34.000Z", "num_tokens": 2165, "size": 8580 }
/* # This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE */ #ifndef AN_GSL_UTILS_H #define AN_GSL_UTILS_H #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_vector_double.h> void gslutils_use_error_system(); /** Solves a least-squares matrix equation A X_i = B_i For NB pairs of X_i, B_i. NOTE: THIS DESTROYS A! A: MxN matrix B: array of NB x length-M vectors X: must be an array big enough to hold NB vectors. (they will be length-N). resids: if non-NULL, must be an array big enough to hold NB vectors (they will be length-M). The result vectors are freshly allocated and should be freed with gsl_vector_free(). */ int gslutils_solve_leastsquares(gsl_matrix* A, gsl_vector** B, gsl_vector** X, gsl_vector** resids, int NB); /** Same as above, but using varargs. There must be exactly 3 * NB additional arguments, in the order: B0, &X0, &resid0, B1, &X1, &resid1, ... ie, the types must be repeating triples of: gsl_vector* b, gsl_vector** x, gsl_vector** resid */ int gslutils_solve_leastsquares_v(gsl_matrix* A, int NB, ...); // C = A B void gslutils_matrix_multiply(gsl_matrix* C, const gsl_matrix* A, const gsl_matrix* B); int gslutils_invert_3x3(const double* A, double* B); #endif
{ "alphanum_fraction": 0.6901408451, "avg_line_length": 24.9814814815, "ext": "h", "hexsha": "81996f71cade9ee3f808850a6e6f1a1b2e594c4d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-02-11T06:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-11T06:56:30.000Z", "max_forks_repo_head_hexsha": "38d14d490f33fc933c3d90226691dd1e685ced08", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zfedoran/astrometry.js", "max_forks_repo_path": "src/astrometry/include/astrometry/gslutils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "38d14d490f33fc933c3d90226691dd1e685ced08", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zfedoran/astrometry.js", "max_issues_repo_path": "src/astrometry/include/astrometry/gslutils.h", "max_line_length": 87, "max_stars_count": 4, "max_stars_repo_head_hexsha": "38d14d490f33fc933c3d90226691dd1e685ced08", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zfedoran/astrometry.js", "max_stars_repo_path": "src/astrometry/include/astrometry/gslutils.h", "max_stars_repo_stars_event_max_datetime": "2021-09-30T16:02:22.000Z", "max_stars_repo_stars_event_min_datetime": "2018-02-13T23:11:40.000Z", "num_tokens": 368, "size": 1349 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "Data\Intrinsics.h" #include "Data\Pose.h" #include "Device/CameraCalibration.h" #include "MageSettings.h" #include "Device\IMUCharacterization.h" #include "Map\Map.h" #include "Map\ThreadSafeMap.h" #include "Bow\BaseBow.h" #include "Image\AnalyzedImage.h" #include "Proxies\MapPointProxy.h" #include <opencv2\core\core.hpp> #include <opencv2\features2d\features2d.hpp> #include <memory> #include <gsl\gsl> namespace UnitTests { class MapInitializationUnitTest; } namespace mage { class KeyframeBuilder; class MapInitialization { public: enum InitializationAttemptState { NoPose, ResetInit, FinishInit, Skipped }; MapInitialization(const MonoMapInitializationSettings& settings, const PerCameraSettings& cameraSettings, const device::IMUCharacterization& imuCharacterization, mira::determinator& determinator); InitializationAttemptState TryInitializeMap(const std::shared_ptr<const AnalyzedImage>& frame, thread_memory memory, InitializationData& initializationData, BaseBow& bagOfWords); bool InitializeWithFrames(gsl::span<const cv::DMatch> matches, const std::shared_ptr<const AnalyzedImage>& frame0, const std::shared_ptr<const AnalyzedImage>& frame1, InitializationData& initializationData, thread_memory memory); struct BundlerSettings { float HuberWidth; float MaxOutlierError; float MaxOutlierErrorScaleFactor; float MinMeanSquareError; bool FixMapPoints; uint32_t NumStepsPerRun; uint32_t NumSteps; uint32_t MinSteps; }; static void BundleAdjustInitializationData(InitializationData& initializationData, mira::determinator& determinator, bool cullOutliers, const BundlerSettings& bundlerSettings, thread_memory memory); static bool ValidateInitializationData(const InitializationData& initializationData, float maxZContribution, float amountBACanChangePose, size_t minFeatureCount); // Frame1Points and Frame2Points are indexed to match each other static void CollectMatchPoints(const std::shared_ptr<const AnalyzedImage>& referenceFrame, const std::shared_ptr<const AnalyzedImage>& currentFrame, gsl::span<const cv::DMatch> matches, std::vector<cv::Point2f>& frame1Points, std::vector<cv::Point2f>& frame2Points); static void TriangulatePoints(const std::shared_ptr<const AnalyzedImage>& referenceFrame, const std::shared_ptr<const AnalyzedImage>& currentFrame, const Pose & referencePose, const Pose & currentPose, gsl::span<const cv::DMatch> matches, gsl::span<const cv::Point2f> frame1_points, gsl::span<const cv::Point2f> frame2_points, float pixelMaxEpipolarDistance, float minAcceptanceDistanceRatio, std::vector<std::pair<cv::DMatch, cv::Point3f>>& initial3DPoints); private: struct MatchedImage { std::shared_ptr<const AnalyzedImage> Image; std::vector<cv::DMatch> Matches; MatchedImage(std::shared_ptr<const AnalyzedImage> image, std::vector<cv::DMatch> matches) : Image{ image }, Matches( std::move(matches) ) {}; MatchedImage(std::shared_ptr<const AnalyzedImage> image) : Image{ image } {}; }; struct PointAssociation { size_t PointIndex2d; size_t PointIndex3d; PointAssociation(size_t twoD, size_t threeD) : PointIndex2d { twoD }, PointIndex3d { threeD } {}; }; struct InitializationPose { std::shared_ptr<const AnalyzedImage> Image; mage::Pose Pose; std::vector<PointAssociation> Associations; InitializationPose(std::shared_ptr<const AnalyzedImage> image, mage::Pose pose, std::vector<PointAssociation> associations) : Image( image ), Pose( pose ), Associations(std::move(associations)) {}; }; void ResetMapInitialization(); bool TryIntializeMapWithProvidedFrames( const MatchedImage& referenceFrame, MatchedImage& currentFrame, thread_memory memory, InitializationData& initializationData, BaseBow& bagOfWords); std::vector<Pose> FindEssentialPotientialPoses( const cv::Matx33f& essentialMat); //Frame1Points and Frame2Points are indexed to match each other float ScoreFundamentalMatrix(gsl::span<const cv::Point2f> frame1Points, gsl::span<const cv::Point2f> frame2Points, const cv::Matx33f& fundamentalMat1To2, const cv::Matx33f& fundamentalMat2To1); //Frame1Points and Frame2Points are indexed to match each other std::vector<Pose> FindPossiblePoses(gsl::span<const cv::Point2f> frame1Points, gsl::span<const cv::Point2f> frame2Points, const CameraCalibration& frame1Calibration, const CameraCalibration& frame2Calibration); //Frame1Points and Frame2Points are indexed to match each other bool FindCorrectPose(gsl::span<const cv::Point2f> frame1Points, gsl::span<const cv::Point2f> frame2Points, gsl::span<const cv::DMatch> matches, const CameraCalibration& frame1Calibration, const CameraCalibration& frame2Calibration, const Pose& referencePose, const std::vector<Pose>& poses, Pose& correctPose, std::vector<std::pair<cv::DMatch, cv::Point3f>>& correct3DPoints); const MonoMapInitializationSettings m_settings; const PerCameraSettings m_cameraSettings; const device::IMUCharacterization& m_imuCharacterization; mira::determinator& m_determinator; std::vector<MatchedImage> m_initializationFrames; std::vector<uint8_t> m_initializationDescriptorsCounters; //For Test friend class ::UnitTests::MapInitializationUnitTest; }; }
{ "alphanum_fraction": 0.6440729949, "avg_line_length": 37.2628571429, "ext": "h", "hexsha": "90df93cd20b2367256fc21eb591f9d5c2fa9ace0", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_line_length": 206, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 1406, "size": 6521 }
/*! /file global.h * /brief Declarations of global variables and functions. */ #ifndef GLOBAL_H #define GLOBAL_H #ifdef COOLING_CPU #include <gsl/gsl_spline.h> #include <gsl/gsl_spline2d.h> #endif #if PRECISION == 1 #ifndef FLOAT_TYPEDEF_DEFINED typedef float Real; #endif //FLOAT_TYPEDEF_DEFINED #endif //PRECISION == 1 #if PRECISION == 2 #ifndef FLOAT_TYPEDEF_DEFINED typedef double Real; #endif //FLOAT_TYPEDEF_DEFINED #endif //PRECISION == 2 #define MAXLEN 100 #define TINY_NUMBER 1.0e-20 #define PI 3.141592653589793 #define MP 1.672622e-24 // mass of proton, grams #define KB 1.380658e-16 // boltzmann constant, cgs //#define GN 6.67259e-8 // gravitational constant, cgs #define GN 4.49451e-18 // gravitational constant, kpc^3 / M_sun / kyr^2 //#define TIME_UNIT 3.15569e10 // 1 kyr in s //#define LENGTH_UNIT 3.08567758e21 // 1 kpc in cm //#define MASS_UNIT 1.98855e33 // 1 solar mass in grams #define TIME_UNIT 60300.114856343294 #define LENGTH_UNIT 310994529228.64191 #define MASS_UNIT 2.6020994527238984e+18 #define DENSITY_UNIT (MASS_UNIT/(LENGTH_UNIT*LENGTH_UNIT*LENGTH_UNIT)) #define VELOCITY_UNIT (LENGTH_UNIT/TIME_UNIT) #define ENERGY_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT) #define PRESSURE_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT) #define SP_ENERGY_UNIT (VELOCITY_UNIT*VELOCITY_UNIT) #ifdef SCALAR #define NSCALARS 1 #endif #define SIGN(a) ( ((a) < 0.) ? -1. : 1. ) /* Global variables */ extern Real gama; // Ratio of specific heats extern Real C_cfl; // CFL number (0 - 0.5) extern Real t_comm; extern Real t_other; #ifdef COOLING_CPU extern gsl_interp_accel *acc; extern gsl_interp_accel *xacc; extern gsl_interp_accel *yacc; extern gsl_spline *highT_C_spline; extern gsl_spline2d *lowT_C_spline; extern gsl_spline2d *lowT_H_spline; #endif #ifdef COOLING_GPU extern float *cooling_table; extern float *heating_table; #endif /*! \fn void Set_Gammas(Real gamma_in) * \brief Set gamma values for Riemann solver. */ extern void Set_Gammas(Real gamma_in); /*! \fn double get_time(void) * \brief Returns the current clock time. */ extern double get_time(void); /*! \fn int sgn * \brief Mathematical sign function. Returns sign of x. */ extern int sgn(Real x); #ifndef CUDA /*! \fn Real calc_eta(Real cW[], Real gamma) * \brief Calculate the eta value for the H correction. */ extern Real calc_eta(Real cW[], Real gamma); #endif struct parameters { int nx; int ny; int nz; double tout; double outstep; Real gamma; char init[MAXLEN]; int nfile; int nfull; Real xmin; Real ymin; Real zmin; Real xlen; Real ylen; Real zlen; int xl_bcnd; int xu_bcnd; int yl_bcnd; int yu_bcnd; int zl_bcnd; int zu_bcnd; #ifdef MPI_CHOLLA int xlg_bcnd; int xug_bcnd; int ylg_bcnd; int yug_bcnd; int zlg_bcnd; int zug_bcnd; #endif /*MPI_CHOLLA*/ char custom_bcnd[MAXLEN]; char outdir[MAXLEN]; Real rho; Real vx; Real vy; Real vz; Real P; Real A; Real rho_l; Real v_l; Real P_l; Real rho_r; Real v_r; Real P_r; Real diaph; #ifdef ROTATED_PROJECTION int nxr; int nzr; Real delta; Real theta; Real phi; Real Lx; Real Lz; int n_delta; Real ddelta_dt; int flag_delta; #endif /*ROTATED_PROJECTION*/ // added by TRW int ncycle_out; // controls freq of output to screen Real my_reals[99]; // an array to hold an additional 99 parameters }; /*! \fn void parse_params(char *param_file, struct parameters * parms); * \brief Reads the parameters in the given file into a structure. */ extern void parse_params (char *param_file, struct parameters * parms); #endif //GLOBAL_H
{ "alphanum_fraction": 0.7284530387, "avg_line_length": 22.3456790123, "ext": "h", "hexsha": "37b546016a23f9bc66cafea5ea397c5a9b2073c5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "twaters/cholla", "max_forks_repo_path": "src/global.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "twaters/cholla", "max_issues_repo_path": "src/global.h", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "twaters/cholla", "max_stars_repo_path": "src/global.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1101, "size": 3620 }
/** * * \file gpsins.c - Implements an integrated GPS-Inertial navigation system. * * This program implements an integrated GPS-Inertial navigation system. Data is * retrieved from shared memory and processed in two threads. The high speed thread * implements the inertial navigation mechanisation. The low speed thread combines * the inertial navigation solution with GPS measurements in a tightly coupled * architecture. The output is stored back into shared memory. * * This program implements a 17 state tightly coupled EKF. Note * that the filter states are organised such that the first 15 states * are identical to those used by a 15 state loosely coupled EKF. * * The filter uses an error state formulation. The EKF_x_hat vector contains the state * error rather than the full state. The full state is stored in regular arrays of * Pos_LLH, Vel_NED and C_BN representing the Latitude, Longitude, Height, North, East * and Down Velocity, and attitude direction cosine matrix (DCM). * * \code * Filter States * ============= * x1 - Latitude Error (radians) * x2 - Longitude Error (radians) * x3 - Height Error (metres) * x4 - North Velocity Error (m/s) * x5 - East Velocity Error (m/s) * x6 - Down Velocity Error (m/s) * x7 - North Tilt Error (radians) * x8 - East Tilt Error (radians) * x9 - Down Tilt Error (radians) * x10 - X Accelerometer Bias Error (m/s/s) * x11 - Y Accelerometer Bias Error (m/s/s) * x12 - Z Accelerometer Bias Error (m/s/s) * x13 - X Gyroscope Bias Error (rad/s) * x14 - Y Gyroscope Bias Error (rad/s) * x15 - Z Gyroscope Bias Error (rad/s) * x16 - Receiver Clock Bias Error (metres) * x17 - Receiver Clock Frequency Error (metres/sec) * * Measurement States - assuming 'n' satellite measurements available * ================== * z1 - zn - GPS Pseudorange Measurements * zn+1 - 2zn - GPS Pseudorange Rate (doppler) measurements * * These states are not yet implemented... * 2nz+1 - Barometric Altitude Error (metres) * 2zn+2 - Compass Heading Error (radians) * \endcode * * \author Duncan Greer * \version "$Id: gpsins.c 955 2007-12-06 06:38:04Z greerd $" */ /* this is an additonal comment */ /* if we are using rtai, declare it here */ /* #define USE_RTAI */ #undef USE_RTAI #include <stdio.h> #include <termios.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <strings.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <stdlib.h> #include <signal.h> #ifndef _SVID_SOURCE #define _SVID_SOURCE #endif #include <sys/shm.h> #include <sys/ipc.h> #include <mqueue.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <spawn.h> #include <sys/mman.h> #ifdef USE_RTAI #include <rtai_lxrt.h> #include <rtai_bits.h> #else #include <sys/ioctl.h> #include <linux/rtc.h> #endif #include <math.h> #include "gpsins.h" #include "gps.h" #include "../../novatelstore/src/shmdef.h" #include "matrix.h" #define MODULE_NAME "[GPSINS]" #define log(string) fprintf(stdout,"%s %s\n", MODULE_NAME, string) #define err(string) fprintf(stderr,"%s ERROR: %s\n",MODULE_NAME, string) #define CONTROL_MQUEUE_NAME "/control-queue" #define GPSINS_MQUEUE_NAME "/gpsins-queue" #define INS_MQUEUE_NAME "/ins-queue" #define CMD_SHUTDOWN 1 #define CMD_RUNLOOP 2 #define MAX_DIR_LENGTH 1024 //int Shutdown = 0; /** thread to control execution of the program */ void *ControlThread(void *ThreadArgs); /** thread to perform INS solution - 100Hz */ void *INSThread(void *ThreadArgs); /** thread to perform GPS-INS solution - 1 Hz */ void *GPSINSThread(void *ThreadArgs); /* INS globals */ double C_BN[3][3]; double Pos_LLH[3]; double Vel_NED[3]; double Acc_NED[3]; double UserClock[2]; double GyroBias[3]; double AccBias[3]; int iShutdown = 0; /* state variables */ gsl_matrix *EKF_P; gsl_vector *EKF_x_hat; /** * \fn HandleSignal * \brief Handle caught signals * * This function sets a flag (iShutdown) to shut the program down. */ void HandleSignal(int signal) { fprintf(stdout,"Got Signal: %d\n",signal); iShutdown = 1; } /** * main */ int main(int argc, char *argv[]) { /* generic return value */ int iReturnValue; #ifndef USE_RTAI int iRTCDevice; long lRTCBuffer; #endif /* int iMessage = 0; char cMessage = 0; */ message mMessage; /* thread paramter/control objects */ pthread_t ptControlThread; pthread_t ptINSThread; pthread_t ptGPSINSThread; /* pointers to GPS and IMU data respectively */ // GPSData *ptGPSData; // IMUData *ptIMUData; /* shared memory objects */ // int shmGPSId, shmIMUId; // key_t shmGPSKey, shmIMUKey; /* message queue */ mqd_t mqdControl; struct mq_attr mqdControlAttr; /** GPS INS Thread Message Queue (POSIX) */ mqd_t mqdGPSINS; /** INS Thread Message Queue (POSIX) */ mqd_t mqdINS; /** storage for gps store pid */ // pid_t pidGPSStore; /* storage for current working directory */ // char azcCurrentWorkingDirectory[MAX_DIR_LENGTH]; // char azcLaunchPath[MAX_DIR_LENGTH+20]; // char *ptr; /* storage for GPSStore Arguments */ // char *azcGPSStoreArgs[4] = {"gpsstore","/dev/ttyUSB0","230400",NULL}; sigset_t ssSigSet; log("Initialising Program"); /* setup signal handlers */ signal(SIGHUP, HandleSignal); signal(SIGTERM, HandleSignal); signal(SIGKILL, HandleSignal); signal(SIGALRM, HandleSignal); signal(SIGINT, HandleSignal); sigemptyset(&ssSigSet); sigaddset(&ssSigSet,SIGRTMIN); pthread_sigmask(SIG_BLOCK, &ssSigSet, NULL); mqdControlAttr.mq_maxmsg = 10; mqdControlAttr.mq_msgsize = sizeof(message); mqdControlAttr.mq_flags = 0; /* initialise message */ memset(&mMessage,0,sizeof(message)); /* create a control message queue */ mqdControl = mq_open(CONTROL_MQUEUE_NAME,O_CREAT|O_RDWR|O_EXCL|O_NONBLOCK, (mode_t)0666, &mqdControlAttr); if(mqdControl == -1) { perror("mq_open(): CONTROL_MQUEUE_NAME"); exit(-1); } /* setup gps ins message queue */ #ifdef USE_RTAI mqdGPSINS = mq_open(GPSINS_MQUEUE_NAME,O_CREAT|O_RDWR|O_EXCL|O_NONBLOCK, (mode_t)0666, &mqdControlAttr); #else mqdGPSINS = mq_open(GPSINS_MQUEUE_NAME,O_CREAT|O_RDWR|O_EXCL, (mode_t)0666, &mqdControlAttr); #endif if(mqdGPSINS == -1) { perror("mq_open(): GPSINS_MQUEUE_NAME"); exit(-1); } /* setup ins message queue */ mqdINS = mq_open(INS_MQUEUE_NAME,O_CREAT|O_RDWR|O_EXCL|O_NONBLOCK, (mode_t)0666, &mqdControlAttr); if(mqdINS == -1) { perror("mq_open(): INS_MQUEUE_NAME"); exit(-1); } /* ptmqdControl = (mqd_t *)malloc(sizeof(mqd_t)); *ptmqdControl = mqdControl; */ /* start control thread */ iReturnValue = pthread_create(&ptControlThread,NULL,ControlThread,(void *)&mqdControl); if(iReturnValue < 0) { perror("pthread_create():"); } /* debug message */ /* fprintf(stdout,"%s GPS Data: %d bytes, IMU Data: %d bytes\n",MODULE_NAME, sizeof(GPSData), sizeof(IMUData)); */ // shmGPSKey = GPSDATA_KEY; // shmIMUKey = IMUDATA_KEY; /*. create shared memory space for storing the data */ // if((shmGPSId = shmget(shmGPSKey, sizeof(GPSData), IPC_CREAT | 0666)) < 0) // { // perror("shmget(): allocating GPS data storage"); // exit(-1); // } /* attach */ // if((ptGPSData = shmat(shmGPSId, NULL, 0)) == (GPSData *) -1) // { // perror("shmat(): attaching GPS Data Storage"); // exit(-1); // } // if((shmIMUId = shmget(shmIMUKey,sizeof(GPSData), IPC_CREAT | 0666)) < 0) // { // perror("shmget(): allocating IMU data storage"); // exit(-1); // } // if((ptIMUData = shmat(shmIMUId, NULL, 0)) == (IMUData *)-1) // { // perror("shmat(): attaching IMU data storage"); // exit(-1); // } /* intialise shared memory */ // memset(ptGPSData,0,sizeof(GPSData)); // memset(ptIMUData,0,sizeof(IMUData)); /* get current working directory - used for spawn call */ // ptr = getcwd(azcCurrentWorkingDirectory,(size_t) MAX_DIR_LENGTH); // strcat(azcLaunchPath,azcCurrentWorkingDirectory); // strcat(azcLaunchPath,"/"); // strcat(azcLaunchPath,azcGPSStoreArgs[0]); /* start GPS and INS data stores */ // fprintf(stdout,"%s Launching GPSStore: %s\n",MODULE_NAME,azcLaunchPath); // iReturnValue = posix_spawn(&pidGPSStore, /* storage for child pid */ // azcCurrentWorkingDirectory, /* current working directory */ // NULL, /* posix_spawn_file_actions_t */ // NULL, /* posix_spawnattr_t */ // azcGPSStoreArgs, /* GPS Store Args - serial port, baud */ // NULL); /* environment */ // if(iReturnValue != 0) // { // perror("posix_spawn(): GPSStore"); // } /* start GPS and INS threads */ iReturnValue = pthread_create(&ptINSThread,NULL,INSThread,(void *)&mqdINS); if(iReturnValue < 0) { perror("pthread_create(): INS Thread"); } iReturnValue = pthread_create(&ptGPSINSThread,NULL,GPSINSThread,(void *)&mqdGPSINS); if(iReturnValue < 0) { perror("pthread_create(): GPS-INS Thread"); } #ifndef USE_RTAI /* open real time clock if we are not using RTAI */ iRTCDevice = open("/dev/rtc",O_RDONLY); if (iRTCDevice < 0) { perror("open: RTC: "); } else { ioctl(iRTCDevice,RTC_UIE_ON,NULL); log("Successfully opened RTC"); } #endif while(iShutdown == 0) { iReturnValue = mq_receive(mqdControl,(char *)&mMessage,sizeof(message),NULL); if(iReturnValue < 0) { /* perror("mq_receive():"); */ } /* log("Received Message"); fprintf(stdout,"Rx: %d, %d\n",iReturnValue, mMessage.iMessageType); */ if(mMessage.iMessageType == 1) { // exit log("Received Shutdown Message"); iShutdown = 1; break; } /* this read will return at 1 second intervals */ read(iRTCDevice,&lRTCBuffer,sizeof(long)); /* send message to run threads */ mMessage.iMessageType = CMD_RUNLOOP; iReturnValue = mq_send(mqdGPSINS,(const char *)&mMessage,sizeof(message),1); } log("Shutting Down"); /* send message to shutdown threads */ mMessage.iMessageType = CMD_SHUTDOWN; iReturnValue = mq_send(mqdGPSINS,(const char *)&mMessage,sizeof(message),1); if(iReturnValue < 0) { perror("mq_send(): Thread Shutdown"); } iReturnValue = mq_send(mqdINS,(const char *)&mMessage,sizeof(message),1); if(iReturnValue < 0) { perror("mq_send(): Thread Shutdown"); } iReturnValue = mq_send(mqdControl,(const char *)&mMessage,sizeof(message),1); if(iReturnValue < 0) { perror("mq_send(): Thread Shutdown"); } /* wait for threads to shutdown */ //sleep(2); fprintf(stdout,"%s Waiting for INS thread to join...", MODULE_NAME); pthread_join(ptINSThread,NULL); fprintf(stdout,"DONE\n"); fprintf(stdout,"%s Waiting for GPS-INS thread to join...", MODULE_NAME); pthread_join(ptGPSINSThread,NULL); fprintf(stdout,"DONE\n"); fprintf(stdout,"%s Waiting for Control thread to join...", MODULE_NAME); pthread_join(ptControlThread,NULL); fprintf(stdout,"DONE\n"); #ifndef USE_RTAI /* close rtc */ close(iRTCDevice); #endif /* close and unlink message queues */ fprintf(stdout,"%s Unlinking Message Queues...",MODULE_NAME); mq_close(mqdControl); mq_unlink(CONTROL_MQUEUE_NAME); mq_close(mqdGPSINS); mq_unlink(GPSINS_MQUEUE_NAME); mq_close(mqdINS); mq_unlink(INS_MQUEUE_NAME); fprintf(stdout,"DONE\n"); log("Exiting"); pthread_exit(NULL); return 0; } /* end main */ /* * ControlThread - controls execution of the program */ void *ControlThread(void *ThreadArgs) { char c[100]; mqd_t *ptmqdControl; int iReturnValue; message mMessage; fprintf(stdout,"%s Control Thread Initialised - press 'q <enter>' to exit!\n",MODULE_NAME); /* initialise message */ memset(&mMessage,0,sizeof(message)); /* read arguments */ ptmqdControl = (mqd_t *)ThreadArgs; while(scanf("%s",c)) { /* check for message (non blocking) */ iReturnValue = mq_receive(*ptmqdControl,(char *)&mMessage,sizeof(message),NULL); if(iReturnValue < 0) { perror("mq_recieve(): Control Thread"); } if(mMessage.iMessageType == CMD_SHUTDOWN) { log("Control Thread Received SHUTDOWN command"); //pthread_exit(NULL); break; } switch(strlen(c)) { case 1: /* command character */ switch(c[0]) { case 'q': mMessage.iMessageType = CMD_SHUTDOWN; /* send shutdown message */ iReturnValue = mq_send(*ptmqdControl, (const char *)&mMessage, sizeof(message), 1); if(iReturnValue < 0) { perror("mq_send():"); } break; default: fprintf(stderr,"%s Unknown command: %c\n",MODULE_NAME, c[0]); break; } default: /* do nothing */ break; } } fprintf(stdout,"%s Control Thread Exiting\n", MODULE_NAME); /* never reached */ pthread_exit(NULL); } int iINSThreadCounter; void *INSThread(void *ThreadArgs) { /* message storage */ message mMessage; /* generic return storage */ int iReturnValue; /* message queue pointer */ mqd_t *ptmqdINS; /* timer variables */ int iSigNumber; sigset_t ssSigSet; struct sigevent seSigEvent; timer_t tPeriodicTimer; struct timespec first,period; struct itimerspec required,old; long lThreadPeriod = 10000000; /* 10ms = 100 hz */ /* shared memory variables */ int iUseSHM = 1; shm_struct *shm = NULL; int iSHM_FID; double EarthRate[3]; double Tecef2ned[3][3]; double RM,RP; double Lat,Long; double LatDot,LongDot; double sLat,cLat; double OMEGA_b[3][3]; double Coriolis[3]; double Acc_XYZ[3]; double omega_x,omega_y,omega_z; double OMEGA_e_n[3]; double OMEGA_in[3][3]; fprintf(stdout,"%s INS Thread Started\n",MODULE_NAME); /* initialise message */ memset(&mMessage,0,sizeof(message)); /* setup message queue */ ptmqdINS = (mqd_t *)ThreadArgs; /* setup thread timer */ seSigEvent.sigev_notify = SIGEV_SIGNAL; seSigEvent.sigev_signo = SIGRTMIN; clock_gettime(CLOCK_REALTIME, &first); first.tv_sec = first.tv_sec + 1; fprintf(stdout,"INS: First loop runs at %ld.%ld\n", (long)first.tv_sec,(long)first.tv_nsec); period.tv_sec = 0; period.tv_nsec = lThreadPeriod; required.it_value = first; required.it_interval = period; iReturnValue = timer_create(CLOCK_REALTIME,&seSigEvent,&tPeriodicTimer); if(iReturnValue < 0) { perror("INS: timer_create():"); } sigemptyset(&ssSigSet); sigaddset(&ssSigSet,SIGRTMIN); //pthread_sigmask(SIG_UNBLOCK, &ssSigSet, NULL); iReturnValue = timer_settime(tPeriodicTimer,TIMER_ABSTIME,&required, &old); if(iReturnValue < 0) { perror("INS: timer_settime():"); } /* setup shared memory */ if(iUseSHM == 1) { iSHM_FID = shm_open("/novatel0",O_RDWR,0777); if(iSHM_FID == -1) { perror("shm_open: "); iUseSHM = 0; } else { /* memory map the shm object */ shm = mmap(0,sizeof(*shm),PROT_READ,MAP_SHARED,iSHM_FID,0); if(shm == MAP_FAILED) { perror("shm mmap: "); iUseSHM = 0; } else { fprintf(stdout,"%s SHM Address Is: 0x%08x\n",MODULE_NAME,(unsigned int)shm); } } } /* initialise INS parameters */ C_BN[0][0] = 1.0; C_BN[1][1] = 1.0; C_BN[2][2] = 1.0; GyroBias[0] = 0.0; GyroBias[1] = 0.0; GyroBias[2] = 0.0; AccBias[0] = 0.0; AccBias[1] = 0.0; AccBias[2] = 0.0; /* position */ Pos_LLH[0] = -27.5*DEG2RAD; Pos_LLH[1] = 153.0*DEG2RAD; Pos_LLH[2] = 90.0; /* velocity */ Vel_NED[0] = 0.0; Vel_NED[1] = 0.0; Vel_NED[2] = 0.0; /* acceleration */ Acc_NED[0] = 0.0; Acc_NED[1] = 0.0; Acc_NED[2] = -LOCAL_GRAVITY; Acc_XYZ[0] = 0.0; Acc_XYZ[1] = 0.0; Acc_XYZ[2] = -LOCAL_GRAVITY; EarthRate[0] = 0.0; EarthRate[1] = 0.0; EarthRate[2] = OMEGA_e; Coriolis[0] = 0.0; Coriolis[1] = 0.0; Coriolis[2] = 0.0; RM = WGS84_a; RP = WGS84_a; WGS84_calcRnRe(Pos_LLH[0], &RM, &RP); OMEGA_e_n[0] = 0.0; OMEGA_e_n[1] = 0.0; OMEGA_e_n[2] = 0.0; log("INS Thread Commencing Periodic"); while(1) { //fprintf(stdout,"Waiting..."); /* wait for signal */ sigwait(&ssSigSet, &iSigNumber); iINSThreadCounter++; /* check for messages */ iReturnValue = mq_receive(*ptmqdINS,(char *)&mMessage,sizeof(message),NULL); if(iReturnValue < 0 && errno != EAGAIN) { perror("INS: mq_recieve(): "); //fprintf(stdout,"%d",iReturnValue); } if(mMessage.iMessageType == CMD_SHUTDOWN) { break; } /* get current lat and long */ Lat = Pos_LLH[0]; Long = Pos_LLH[1]; cLat = cos(Lat); sLat = sin(Lat); T_ECEF2NED(Lat, Long, (double **)Tecef2ned); /* attitude update */ omega_x = shm->CurrentIMUData.dRate[0] - GyroBias[0]; omega_y = shm->CurrentIMUData.dRate[1] - GyroBias[1]; omega_z = shm->CurrentIMUData.dRate[2] - GyroBias[2]; /* form the skew symmetric form */ OMEGA_b[0][0] = 0.0; OMEGA_b[0][1] = -omega_z; OMEGA_b[0][2] = omega_y; OMEGA_b[1][0] = omega_z; OMEGA_b[1][1] = 0.0; OMEGA_b[1][2] = -omega_x; OMEGA_b[2][0] = -omega_y; OMEGA_b[2][1] = omega_x; OMEGA_b[2][2] = 0.0; /* navigation frame rotation correction */ OMEGA_in[0][0] = 0.0; OMEGA_in[0][1] = -OMEGA_e * sLat; OMEGA_in[0][2] = 0.0; OMEGA_in[1][0] = OMEGA_e * sLat; OMEGA_in[1][1] = 0.0; OMEGA_in[1][2] = -OMEGA_e * cLat; OMEGA_in[2][0] = 0.0; OMEGA_in[2][1] = OMEGA_e * cLat; OMEGA_in[2][2] = 0.0; /* DCM Update */ /* C_BN = C_BN + (C_BN * OMEGA_b - OMEGA_in * C_BN)*INS_DT */ /* acceleration calculation */ /* Acc_NED = C_BN * Acc_XYZ */ Acc_XYZ[0] = shm->CurrentIMUData.dAcc[0] - AccBias[0]; Acc_XYZ[1] = shm->CurrentIMUData.dAcc[1] - AccBias[1]; Acc_XYZ[2] = shm->CurrentIMUData.dAcc[2] - AccBias[2] -LOCAL_GRAVITY; MatMul331(C_BN, Acc_XYZ, Acc_NED); /* correct vertical channel for gravity */ Acc_NED[2] = Acc_NED[2] + LOCAL_GRAVITY; /* coriolis correction */ MatMul331(Tecef2ned, EarthRate, OMEGA_e_n); /* Coriolis = cross(2 * OMEGA_e_n,[0,0,0]); */ Acc_NED[0] = Acc_NED[0] - Coriolis[0]; Acc_NED[1] = Acc_NED[1] - Coriolis[1]; Acc_NED[2] = Acc_NED[2] - Coriolis[2]; /* velocity update */ Vel_NED[0] = Vel_NED[0] + Acc_NED[0] * INS_DT; Vel_NED[1] = Vel_NED[1] + Acc_NED[1] * INS_DT; Vel_NED[2] = Vel_NED[2] + Acc_NED[2] * INS_DT; WGS84_calcRnRe(Pos_LLH[0], &RM, &RP); LatDot = Vel_NED[0] / (RM + Pos_LLH[2]); LongDot = Vel_NED[1] / (cos(Pos_LLH[0])*(RP + Pos_LLH[2])); /* position update */ Pos_LLH[0] = Pos_LLH[0] + LatDot * INS_DT; Pos_LLH[1] = Pos_LLH[1] + LongDot * INS_DT; Pos_LLH[2] = Pos_LLH[2] + -Vel_NED[2] * INS_DT; /* covariance update */ /* P = PHI * P * PHI' + Qd */ } /* exit */ fprintf(stdout,"%s INS Thread Exiting\n",MODULE_NAME); pthread_exit(NULL); } void *GPSINSThread(void *ThreadArgs) { int iRunThread = 1; /* pointer to message queue designator passed from arguments */ mqd_t *ptmqdGPSINS; /* generic return value storage */ int iReturnValue; /* generic message storage */ message mMessage; #ifdef USE_RTAI /* real time task */ static RT_TASK *rttGPSINS; #endif /* KF stuff */ int iNumberStates,iNumberMeasurements; /* matrices */ gsl_matrix *EKF_Q; gsl_matrix *EKF_PHI; /* phi ~= I + Fdt */ gsl_matrix *EKF_F; gsl_matrix *EKF_P_minus; gsl_matrix *tempP; gsl_matrix *EKF_H; gsl_matrix *EKF_R; gsl_matrix *EKF_K; gsl_matrix *EKF_V; gsl_matrix *EKF_Vinv; gsl_matrix *tempV; gsl_matrix *tempK; gsl_matrix *KH; gsl_matrix *I_17by17; gsl_matrix *IminusKH; gsl_matrix *KHPminus; gsl_matrix *KRKT; gsl_matrix *tempKRKT; /* svd stuff */ gsl_vector *SVD_S; gsl_vector *SVD_Sinv; gsl_matrix *SVD_SinvMat; gsl_vector *SVDWork; gsl_matrix *SVD_V; gsl_matrix *SVD_U; gsl_matrix *tempNN; /* vectors */ gsl_vector *EKF_z; gsl_vector *EKF_deltaz; gsl_vector *EKF_x_hat_out; gsl_vector *temp1; double x_gyro_beta; double y_gyro_beta; double z_gyro_beta; double x_accel_beta; double y_accel_beta; double z_accel_beta; double user_x,user_y,user_z,user_t; double user_xdot,user_ydot,user_zdot,user_tdot; double sat_x,sat_y,sat_z,sat_t; double sat_xdot,sat_ydot,sat_zdot,sat_tdot; double ION_Alpha[4]; double ION_Beta[4]; unsigned short usPRN; double range,rangerate; double geo_vel_to_sat; double delta_pr_omegaedot; double Rm,Rp; double Rmh,Rph,Rg; double IonoDelay[NOVATEL_MAXCHANNELS],TropoDelay[NOVATEL_MAXCHANNELS]; double SV_Azimuth[NOVATEL_MAXCHANNELS]; double SV_Elevation[NOVATEL_MAXCHANNELS]; // double llh[3]; // double ecef[3]; double dTransmissionTime; GPSTime gtObservationTime; RANGE GPSRangeData; GPSEPHEM GPSEphemData[NOVATEL_MAXPRNS]; int iIndex; int iNumberValidObservations; int iNumberValidEphemeris; int iUseSV[NOVATEL_MAXCHANNELS]; double UserPos[3]; double UserVel[3]; double Tecef2ned[3][3]; double Tned2ecef[3][3]; double SVPos_calc[4]; double SVVel_calc[4]; double SVAcc_calc[4]; double C_BN_new[3][3]; double EKF_H_E[3][3]; double EKF_H_LTP[3][3]; double del_alpha,del_beta,del_gamma; double del_att_skew[3][3]; /* matrix counter variables */ int iRowIndex,iColIndex; /* shared memory variables */ int iUseSHM = 1; shm_struct *shm = NULL; int iSHM_FID; /* log message */ fprintf(stdout,"%s GPS-INS Thread Started\n",MODULE_NAME); /* initialise message */ memset(&mMessage,0,sizeof(message)); /* setup message queue */ ptmqdGPSINS = (mqd_t *)ThreadArgs; /* setup EKF */ iNumberStates = NUMBER_STATES; iNumberMeasurements = 0; EKF_x_hat = gsl_vector_alloc(iNumberStates); EKF_x_hat_out = gsl_vector_alloc(iNumberStates); EKF_Q = gsl_matrix_alloc(iNumberStates,iNumberStates); EKF_P = gsl_matrix_alloc(iNumberStates,iNumberStates); EKF_P_minus = gsl_matrix_alloc(iNumberStates,iNumberStates); tempP = gsl_matrix_alloc(iNumberStates,iNumberStates); EKF_PHI = gsl_matrix_alloc(iNumberStates,iNumberStates); EKF_F = gsl_matrix_alloc(iNumberStates,iNumberStates); I_17by17 = gsl_matrix_alloc(iNumberStates,iNumberStates); KH = gsl_matrix_alloc(iNumberStates,iNumberStates); IminusKH = gsl_matrix_alloc(iNumberStates,iNumberStates); KHPminus = gsl_matrix_alloc(iNumberStates,iNumberStates); gsl_matrix_set_identity(EKF_P); gsl_matrix_scale(EKF_P,10.0); temp1 = gsl_vector_alloc(3); x_gyro_beta = 1/100.0; y_gyro_beta = 1/100.0; z_gyro_beta = 1/100.0; x_accel_beta = 1/100.0; y_accel_beta = 1/100.0; z_accel_beta = 1/100.0; UserClock[0] = 0.0; UserClock[1] = 0.0; #ifdef USE_RTAI /* make this thread real time */ rt_set_oneshot_mode(); start_rt_timer(0); rttGPSINS = rt_task_init_schmod(nam2num("GPSINS"), 10, 0, 0, SCHED_FIFO, 0); if (rttGPSINS == NULL) { perror("rt_task_init(): GPSINS"); exit(-1); } rt_make_hard_real_time(); rt_task_make_periodic(rttGPSINS, rt_get_time()+nano2count(1000000000)*2, nano2count(1000000000)); #endif /* setup shared memory */ if(iUseSHM == 1) { iSHM_FID = shm_open("/novatel0",O_RDWR,0777); if(iSHM_FID == -1) { perror("shm_open: "); iUseSHM = 0; } else { /* memory map the shm object */ shm = mmap(0,sizeof(*shm),PROT_READ,MAP_SHARED,iSHM_FID,0); if(shm == MAP_FAILED) { perror("shm mmap: "); iUseSHM = 0; } else { fprintf(stdout,"%s SHM Address Is: 0x%08x\n",MODULE_NAME,(unsigned int)shm); } } } /* reset INS thread counter */ iINSThreadCounter = 0; while(iRunThread == 1) { /* wait for message */ /* non blocking if using RTAI*/ iReturnValue = mq_receive(*ptmqdGPSINS,(char *)&mMessage,sizeof(message),NULL); if(iReturnValue < 0) { /* check value of errno */ switch(errno) { case EAGAIN: /* return with no message - do nothing */ break; default: perror("mq_recieve(): GPSINSThread"); break; } } // if(mMessage.iMessageType == CMD_SHUTDOWN) // { // break; // } switch(mMessage.iMessageType) { case CMD_RUNLOOP: break; case CMD_SHUTDOWN: iRunThread = 0; break; default: err("GPSINSThread Unknown Message"); break; } #ifdef USE_RTAI /* wait until its time to run */ rt_task_wait_period(); #endif // fprintf(stdout,".\n"); fprintf(stdout,"%s: GPSINS Counter: %d\n",MODULE_NAME,iINSThreadCounter); /* RUN PERIODIC TASKS HERE */ /* get INS update from store */ T_ECEF2NED(Pos_LLH[0],Pos_LLH[1],(double **)Tecef2ned); /* get GPS measurements */ memcpy(&GPSEphemData,&shm->CurrentGPSEPHEM,sizeof(GPSEPHEM)*NOVATEL_MAXPRNS); // get the current observation time to compare with ephemeris memcpy(&gtObservationTime,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime)); /* ensure we have ephemeris for all measurements, otherwise exclude */ iNumberValidEphemeris = 0; for(iIndex=0;iIndex<NOVATEL_MAXPRNS;iIndex++) { if((GPSEphemData[iIndex].ulPRN != 0) && (GPSEphemData[iIndex].ulHealth == 0) && (GPSEphemData[iIndex].dTOE < (gtObservationTime.fGPSSecondOfWeek+7500.0)) && (GPSEphemData[iIndex].dTOE > (gtObservationTime.fGPSSecondOfWeek-7500.0)) ) { iUseSV[iIndex] = 1; iNumberValidEphemeris++; } else { iUseSV[iIndex] = 0; } } /* loop through measurements and see if we have valid ephem for each */ memcpy(&GPSRangeData.gtTimeStamp,&shm->CurrentRANGE.gtTimeStamp,sizeof(GPSTime)); iNumberValidObservations = 0; for(iIndex=0;iIndex<shm->CurrentRANGE.lNumberObservations;iIndex++) { if(iUseSV[shm->CurrentRANGE.usPRN[iIndex]] == 1) { // use current range data for now memcpy(&GPSRangeData.usPRN[iNumberValidObservations], &shm->CurrentRANGE.usPRN[iIndex],sizeof(unsigned short)); memcpy(&GPSRangeData.dPseudorange[iNumberValidObservations], &shm->CurrentRANGE.dPseudorange[iIndex], sizeof(double)); iNumberValidObservations++; } else { fprintf(stdout,"NE: %d; ",shm->CurrentRANGE.usPRN[iIndex]); } } fprintf(stdout,"Obs: %d; \n",iNumberValidObservations); GPSRangeData.lNumberObservations = iNumberValidObservations; iNumberMeasurements = GPSRangeData.lNumberObservations; if(iNumberMeasurements < 4) { log("GPSINS Less than 4 Measurements.... "); if(iRunThread == 1) { log("GPSINS Continuing..."); continue; } else { log("GPSINS Exiting.."); break; } } fprintf(stdout,"Allocating Matrices\n"); EKF_z = gsl_vector_alloc(2*iNumberMeasurements); EKF_deltaz = gsl_vector_alloc(2*iNumberMeasurements); EKF_R = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); EKF_H = gsl_matrix_alloc(2*iNumberMeasurements,iNumberStates); tempV = gsl_matrix_alloc(2*iNumberMeasurements,iNumberStates); EKF_V = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); EKF_Vinv = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); EKF_K = gsl_matrix_alloc(iNumberStates,2*iNumberMeasurements); tempK = gsl_matrix_alloc(iNumberStates,2*iNumberMeasurements); tempKRKT = gsl_matrix_alloc(iNumberStates,2*iNumberMeasurements); KRKT = gsl_matrix_alloc(iNumberStates,iNumberStates); SVDWork = gsl_vector_alloc(2*iNumberMeasurements); SVD_S = gsl_vector_alloc(2*iNumberMeasurements); SVD_U = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); SVD_SinvMat = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); tempNN = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); SVD_V = gsl_matrix_alloc(2*iNumberMeasurements,2*iNumberMeasurements); SVD_Sinv = gsl_vector_alloc(2*iNumberMeasurements); /* now that all our memory is allocated, disable paging */ // mlockall(MCL_CURRENT | MCL_FUTURE); // user_x = gsl_vector_get(EKF_x_hat,0); // user_y = gsl_vector_get(EKF_x_hat,1); // user_z = gsl_vector_get(EKF_x_hat,2); // user_t = gsl_vector_get(EKF_x_hat,15); // UserPos[0] = user_x; // UserPos[1] = user_y; // UserPos[2] = user_z; // UserPos[3] = user_t; WGS84_LLH2ECEF(Pos_LLH, UserPos); user_x = UserPos[0]; user_y = UserPos[1]; user_z = UserPos[2]; user_t = UserClock[0]; // user_xdot = gsl_vector_get(EKF_x_hat,3); // user_ydot = gsl_vector_get(EKF_x_hat,4); // user_zdot = gsl_vector_get(EKF_x_hat,5); // user_tdot = gsl_vector_get(EKF_x_hat,16); // UserVel[0] = user_xdot; // UserVel[1] = user_ydot; // UserVel[2] = user_zdot; // UserVel[3] = user_tdot; T_NED2ECEF(Pos_LLH[0], Pos_LLH[1], (double **)Tned2ecef); MatMul331(Tned2ecef, Vel_NED, UserVel); user_xdot = UserVel[0]; user_ydot = UserVel[1]; user_zdot = UserVel[2]; user_tdot = UserClock[1]; ION_Alpha[0] = shm->CurrentIONUTC.a0; ION_Alpha[1] = shm->CurrentIONUTC.a1; ION_Alpha[2] = shm->CurrentIONUTC.a2; ION_Alpha[3] = shm->CurrentIONUTC.a3; ION_Beta[0] = shm->CurrentIONUTC.b0; ION_Beta[1] = shm->CurrentIONUTC.b1; ION_Beta[2] = shm->CurrentIONUTC.b2; ION_Beta[3] = shm->CurrentIONUTC.b3; // fprintf(stdout,"User: [%+10.3f\t%+10.3f\t%+10.3f\t%+10.3f]\n",user_x,user_y,user_z,user_t); fprintf(stdout,"Organising Measurements\n"); for (iIndex=0;iIndex<iNumberMeasurements;iIndex++) { dTransmissionTime = (double)gtObservationTime.fGPSSecondOfWeek - GPSRangeData.dPseudorange[iIndex]/GPS_SPEEDOFLIGHT; GPSOrbitPropagator(dTransmissionTime, GPSRangeData.usPRN[iIndex], &GPSEphemData[GPSRangeData.usPRN[iIndex]], 7500.0, SVPos_calc); GPSOrbitPropagatorVelocities(dTransmissionTime, GPSRangeData.usPRN[iIndex], &GPSEphemData[GPSRangeData.usPRN[iIndex]], 7500.0, SVVel_calc, SVAcc_calc); usPRN = GPSRangeData.usPRN[iIndex]; sat_x = SVPos_calc[0]; sat_y = SVPos_calc[1]; sat_z = SVPos_calc[2]; sat_t = SVPos_calc[3]*GPS_SPEEDOFLIGHT; sat_xdot = SVVel_calc[0]; sat_ydot = SVVel_calc[1]; sat_zdot = SVVel_calc[2]; sat_tdot = SVVel_calc[3]; // find the range gsl_vector_set(temp1,0,sat_x - user_x); gsl_vector_set(temp1,1,sat_y - user_y); gsl_vector_set(temp1,2,sat_z - user_z); range = gsl_blas_dnrm2(temp1); /* calculate the range rate (relative velocity) to the SV */ geo_vel_to_sat = (sat_xdot - user_xdot)*(sat_x-user_x) + (sat_ydot - user_ydot)*(sat_y-user_y) + (sat_zdot - user_zdot)*(sat_z-user_z); rangerate = geo_vel_to_sat / range; EKF_H_E[iIndex][0] = -(sat_x - user_x)/range; EKF_H_E[iIndex][1] = -(sat_y - user_y)/range; EKF_H_E[iIndex][2] = -(sat_z - user_z)/range; // gsl_matrix_set(EKF_H,iIndex,0,-(sat_x - user_x)/range); // gsl_matrix_set(EKF_H,iIndex,1,-(sat_y - user_y)/range); // gsl_matrix_set(EKF_H,iIndex,2,-(sat_z - user_z)/range); // gsl_matrix_set(EKF_H,iIndex,15,1.0); // gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,3,-(sat_x - user_x)/range); // gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,4,-(sat_y - user_y)/range); // gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,5,-(sat_z - user_z)/range); // gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,16,1.0); gsl_vector_set(EKF_z,iIndex,GPSRangeData.dPseudorange[iIndex]); // calculate earth rotation correction delta_pr_omegaedot = -(GPS_OMEGAEDOT/GPS_SPEEDOFLIGHT) * (sat_x*user_y - sat_y*user_x); // calculate iono correction ICD200_IonoModel(gtObservationTime, UserPos, SVPos_calc, ION_Alpha, ION_Beta, &IonoDelay[iIndex], &SV_Azimuth[iIndex], &SV_Elevation[iIndex]); TropoDelay[iIndex] = TropoDelayModel(SV_Elevation[iIndex],Pos_LLH[3]); /* set PR measurement */ gsl_vector_set(EKF_deltaz,iIndex, GPSRangeData.dPseudorange[iIndex] - range - (user_t-sat_t) + delta_pr_omegaedot - IonoDelay[iIndex] - TropoDelay[iIndex]); // fprintf(stdout,"%f %f %f %f %f %f\n", // range, // user_t, // sat_t, // delta_pr_omegaedot, // IonoDelay[iIndex], // TropoDelay[iIndex]); /* set doppler measurement */ gsl_vector_set(EKF_deltaz,iIndex+iNumberMeasurements, -(double)GPSRangeData.fDoppler[iIndex]*GPS_L1_Wavelength - rangerate - (user_tdot)); } // end for i=1:NumberMeasurements // rotate H matrix to local MatMul333(Tecef2ned,EKF_H_E,EKF_H_LTP); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { gsl_matrix_set(EKF_H,iIndex,0,EKF_H_LTP[iIndex][0]); gsl_matrix_set(EKF_H,iIndex,1,EKF_H_LTP[iIndex][1]); gsl_matrix_set(EKF_H,iIndex,2,EKF_H_LTP[iIndex][2]); gsl_matrix_set(EKF_H,iIndex,15,1.0); gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,3,EKF_H_LTP[iIndex][0]); gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,4,EKF_H_LTP[iIndex][1]); gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,5,EKF_H_LTP[iIndex][2]); gsl_matrix_set(EKF_H,iIndex+iNumberMeasurements,16,1.0); } // gsl_vector_fprintf(stdout,EKF_deltaz,"[%f]"); // gsl_matrix_fprintf(stdout,EKF_H,"%f"); fprintf(stdout,"Setting up PHI matrix\n"); WGS84_calcRnRe(Pos_LLH[0], &Rm, &Rp); Rmh = Rm+Pos_LLH[3]; Rph = Rp+Pos_LLH[3]; Rg = sqrt(Rmh*Rmh + Rph*Rph); /* kalman filter */ gsl_matrix_set_zero(EKF_F); gsl_matrix_set(EKF_F,0,3,1.0/Rmh); gsl_matrix_set(EKF_F,1,4,1.0/(Rph*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,2,5,-1.0); gsl_matrix_set(EKF_F,0,2,-Vel_NED[0]/(Rg*Rg)); gsl_matrix_set(EKF_F,1,0,Vel_NED[1]*sin(Pos_LLH[0])/(Rg*cos(Pos_LLH[0])*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,1,2,-Vel_NED[1]/(Rg*Rg*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,1,4,1.0/(Rg*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,3,0,-Vel_NED[1]*2.0*OMEGA_e*cos(Pos_LLH[0]) - Vel_NED[1]*Vel_NED[1]/(Rph*cos(Pos_LLH[0])*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,3,2,(Vel_NED[1]*Vel_NED[1] * tan(Pos_LLH[0]) - Vel_NED[0]*Vel_NED[2])/(Rg*Rg)); gsl_matrix_set(EKF_F,3,3,Vel_NED[2]/Rg); gsl_matrix_set(EKF_F,3,4,-2.0*(OMEGA_e*sin(Pos_LLH[0]) + Vel_NED[1]*tan(Pos_LLH[0])/Rg)); gsl_matrix_set(EKF_F,3,5,Vel_NED[0]/Rg); gsl_matrix_set(EKF_F,4,0,2.0*OMEGA_e*(Vel_NED[0]*cos(Pos_LLH[0]) - Vel_NED[2]*sin(Pos_LLH[0])) + (Vel_NED[0]*Vel_NED[1]/(Rg*cos(Pos_LLH[0])*cos(Pos_LLH[0])))); gsl_matrix_set(EKF_F,4,2,-Vel_NED[1]*(Vel_NED[0]*tan(Pos_LLH[0]) - Vel_NED[1]*Vel_NED[2])/(Rg*Rg)); gsl_matrix_set(EKF_F,4,3,2.0*OMEGA_e*sin(Pos_LLH[0]) + Vel_NED[1]*tan(Pos_LLH[0])/Rg); gsl_matrix_set(EKF_F,4,4,(Vel_NED[0]*tan(Pos_LLH[0])+Vel_NED[2])/Rg); gsl_matrix_set(EKF_F,4,5,2.0*OMEGA_e * cos(Pos_LLH[0]) + Vel_NED[1]/Rg); // velocity error due to tilt error gsl_matrix_set(EKF_F,3,7,-(Acc_NED[2] - LOCAL_GRAVITY)); // -fd gsl_matrix_set(EKF_F,3,8,(Acc_NED[1])); // fe gsl_matrix_set(EKF_F,4,6,(Acc_NED[2] - LOCAL_GRAVITY)); // fd gsl_matrix_set(EKF_F,4,8,-(Acc_NED[0])); // -fn gsl_matrix_set(EKF_F,5,6,-(Acc_NED[1])); // -fe gsl_matrix_set(EKF_F,5,7,(Acc_NED[0])); // fn gsl_matrix_set(EKF_F,5,0,2.0*OMEGA_e*Vel_NED[1]*sin(Pos_LLH[0])); gsl_matrix_set(EKF_F,5,2,(Vel_NED[0]*Vel_NED[0] + Vel_NED[1]*Vel_NED[1])/(Rg*Rg)); // note: gravity correction term missing gsl_matrix_set(EKF_F,5,3,-2.0*Vel_NED[0]/Rg); gsl_matrix_set(EKF_F,5,4,-2.0*(OMEGA_e * cos(Pos_LLH[0]) + Vel_NED[1]/Rg)); gsl_matrix_set(EKF_F,6,0,-OMEGA_e * sin(Pos_LLH[0])); gsl_matrix_set(EKF_F,6,2,-Vel_NED[1]/(Rg*Rg)); gsl_matrix_set(EKF_F,7,2,Vel_NED[0] / (Rg*Rg)); gsl_matrix_set(EKF_F,8,0,-OMEGA_e * cos(Pos_LLH[0]) - Vel_NED[1]/(Rg*cos(Pos_LLH[0])*cos(Pos_LLH[0]))); gsl_matrix_set(EKF_F,8,2,Vel_NED[1]*tan(Pos_LLH[0])/(Rg*Rg)); // tilt error due to velocity error gsl_matrix_set(EKF_F,6,4,1.0/Rg); gsl_matrix_set(EKF_F,7,3,-1.0/Rg); gsl_matrix_set(EKF_F,8,4,-tan(Pos_LLH[0])/Rg); // tilt error due to inertial rotation of the reference frame gsl_matrix_set(EKF_F,6,7,-OMEGA_e*sin(Pos_LLH[0]) - Vel_NED[1]*tan(Pos_LLH[0])/Rg); gsl_matrix_set(EKF_F,6,8,Vel_NED[0]/Rg); gsl_matrix_set(EKF_F,7,6,OMEGA_e*sin(Pos_LLH[0]) + Vel_NED[1]*tan(Pos_LLH[0])/Rg); gsl_matrix_set(EKF_F,8,6,-Vel_NED[0]/Rg); gsl_matrix_set(EKF_F,8,7,-OMEGA_e*cos(Pos_LLH[0]) - Vel_NED[1]/Rg); gsl_matrix_set(EKF_F,7,8,OMEGA_e*cos(Pos_LLH[0]) + Vel_NED[1]/Rg); for(iRowIndex=0;iRowIndex<3;iRowIndex++) { for(iColIndex=0;iColIndex<3;iColIndex++) { gsl_matrix_set(EKF_F,6+iRowIndex,9+iColIndex,-C_BN[iRowIndex][iColIndex]); gsl_matrix_set(EKF_F,3+iRowIndex,12+iColIndex,C_BN[iRowIndex][iColIndex]); } } gsl_matrix_set(EKF_F,9,9, -x_gyro_beta); gsl_matrix_set(EKF_F,10,10, -y_gyro_beta); gsl_matrix_set(EKF_F,11,11, -z_gyro_beta); gsl_matrix_set(EKF_F,12,12, -x_accel_beta); gsl_matrix_set(EKF_F,13,13, -y_accel_beta); gsl_matrix_set(EKF_F,14,14, -z_accel_beta); /* PHI = I + F * dt */ gsl_matrix_set_identity(EKF_PHI); gsl_matrix_scale (EKF_F, 1.0/GPS_RATE); gsl_matrix_add (EKF_PHI, EKF_F); // gsl_matrix_fprintf(stdout,EKF_PHI,"%f"); fprintf(stdout,"Q-Matrix\n"); /* Continuous Q-Matrix */ gsl_matrix_set_identity(EKF_Q); /* Discrete Qd = PHI * G * Q * G' * PHI' */ // TODO: Qd fprintf(stdout,"R-Matrix\n"); /* R - Matrix */ gsl_matrix_set_identity(EKF_R); for(iIndex=0;iIndex<iNumberMeasurements;iIndex++) { gsl_matrix_set(EKF_R,iIndex,iIndex,3.0); gsl_matrix_set(EKF_R,iIndex+iNumberMeasurements,iIndex+iNumberMeasurements,0.3); } /* prediction step */ /* x- = PHI * x+ */ /* z- = H * x- */ /* P- = PHI * P+ * PHI' + Q */ gsl_matrix_memcpy(EKF_P_minus,EKF_Q); gsl_matrix_set_zero(tempP); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,EKF_PHI,EKF_P,1.0, tempP); gsl_blas_dgemm(CblasNoTrans,CblasTrans,1.0,tempP,EKF_PHI,1.0,EKF_P_minus); //V = H * P_minus * H' + R; fprintf(stdout,"HPH'+R\n"); gsl_matrix_set_zero (tempV); gsl_matrix_set_zero(EKF_V); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, EKF_H, EKF_P_minus, 1.0, tempV); gsl_matrix_memcpy(EKF_V,EKF_R); gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,tempV, EKF_H, 1.0,EKF_V); //this adds V = V + A*B /* calculate inv(EKF_V) */ /* */ fprintf(stdout,"inv(V)\n"); iReturnValue = gsl_linalg_SV_decomp (EKF_V,SVD_V,SVD_S,SVDWork); gsl_matrix_memcpy(SVD_U,EKF_V); // get element wise inverse of S gsl_vector_set_all(SVD_Sinv,1.0); gsl_vector_div(SVD_Sinv, SVD_S); gsl_matrix_set_zero (SVD_SinvMat); for(iIndex=0;iIndex<2*iNumberMeasurements;iIndex++) { gsl_matrix_set(SVD_SinvMat,iIndex,iIndex,gsl_vector_get(SVD_Sinv,iIndex)); } // inv(S)*UT gsl_matrix_set_zero (tempNN); gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0, SVD_SinvMat, SVD_U, 1.0, tempNN); // A = V * inv(S) * UT gsl_matrix_set_zero(EKF_Vinv); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, SVD_V, tempNN, 1.0, EKF_Vinv); fprintf(stdout,"PH'*inv(V)\n"); //K = P_minus * H' * inv(V); gsl_matrix_set_zero (tempK); gsl_matrix_set_zero(EKF_K); gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0, EKF_P_minus, EKF_H, 1.0, tempK); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,tempK, EKF_Vinv, 1.0,EKF_K); // x_hat_out = K * (z); gsl_vector_set_zero(EKF_x_hat_out); fprintf(stdout,"Kz\n"); gsl_blas_dgemv (CblasNoTrans, 1.0, EKF_K, EKF_deltaz, 1.0, EKF_x_hat_out); // %symmetric form of the P-update equation to ward off divergence p347 //%Brown and Hwang // P_out = (eye(NumberStates) - K*H)*P_minus*(eye(NumberStates)-K*H)' + K*R*K'; //K*H gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0,EKF_K, EKF_H, 1.0,KH); //(eye(NumberStates) - K*H) gsl_matrix_set_identity(I_17by17); gsl_matrix_memcpy(IminusKH,I_17by17); gsl_matrix_sub(IminusKH, KH); //(eye(NumberStates) - K*H)*P_minus gsl_matrix_set_zero(KHPminus); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, IminusKH, EKF_P_minus, 1.0, KHPminus); //(eye(NumberStates) - K*H)*P_minus*(eye(NumberStates)-K*H)' gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0, KHPminus, IminusKH, 1.0, EKF_P); //K*R*K' gsl_matrix_set_zero (tempKRKT); gsl_matrix_set_zero(KRKT); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, EKF_K, EKF_R, 1.0, tempKRKT); gsl_blas_dgemm(CblasNoTrans,CblasTrans, 1.0,tempKRKT, EKF_K, 1.0,KRKT); gsl_matrix_sub(EKF_P, KRKT); // apply correction Pos_LLH[0] -= gsl_vector_get(EKF_x_hat_out,0); Pos_LLH[1] -= gsl_vector_get(EKF_x_hat_out,1); Pos_LLH[2] -= gsl_vector_get(EKF_x_hat_out,2); Vel_NED[0] -= gsl_vector_get(EKF_x_hat_out,3); Vel_NED[1] -= gsl_vector_get(EKF_x_hat_out,4); Vel_NED[2] -= gsl_vector_get(EKF_x_hat_out,5); AccBias[0] -= gsl_vector_get(EKF_x_hat_out,9); AccBias[1] -= gsl_vector_get(EKF_x_hat_out,10); AccBias[2] -= gsl_vector_get(EKF_x_hat_out,11); GyroBias[0] -= gsl_vector_get(EKF_x_hat_out,12); GyroBias[1] -= gsl_vector_get(EKF_x_hat_out,13); GyroBias[2] -= gsl_vector_get(EKF_x_hat_out,14); // attitude del_alpha = -gsl_vector_get(EKF_x_hat_out,6); del_beta = -gsl_vector_get(EKF_x_hat_out,7); del_gamma = -gsl_vector_get(EKF_x_hat_out,8); del_att_skew[0][0] = 1.0; del_att_skew[0][1] = -del_gamma; del_att_skew[0][2] = del_beta; del_att_skew[1][0] = del_gamma; del_att_skew[1][1] = 1.0; del_att_skew[1][2] = -del_alpha; del_att_skew[2][0] = -del_beta; del_att_skew[2][1] = del_alpha; del_att_skew[2][2] = 1.0; /* C_BN = (eye(3,3) + del_att_skew) * C_BN */ MatMul333(del_att_skew,C_BN,C_BN_new); memcpy(C_BN_new,C_BN,sizeof(C_BN)); // clock UserClock[0] -= gsl_vector_get(EKF_x_hat_out,15); UserClock[1] -= gsl_vector_get(EKF_x_hat_out,16); /* re-enable paging */ // munlockall(); log("Result: \n"); fprintf(stdout,"Pos: %f %f %f\n", Pos_LLH[0]*RAD2DEG, Pos_LLH[1]*RAD2DEG, Pos_LLH[2]); fprintf(stdout,"Vel: %f %f %f\n", Vel_NED[0], Vel_NED[1], Vel_NED[2]); fprintf(stdout,"Clock: %f %f\n", UserClock[0],UserClock[1]); fprintf(stdout,"X-out\n"); gsl_vector_fprintf(stdout,EKF_x_hat_out,"[%f]"); // fprintf(stdout,"delta Z\n"); // gsl_vector_fprintf(stdout,EKF_deltaz,"[%f]"); log("Releasing Matrices"); gsl_vector_free(EKF_z); gsl_vector_free(EKF_deltaz); gsl_matrix_free(EKF_H); gsl_matrix_free(EKF_R); gsl_matrix_free(tempV); gsl_matrix_free(EKF_V); gsl_matrix_free(tempNN); gsl_vector_free(SVD_S); gsl_vector_free(SVD_Sinv); gsl_matrix_free(SVD_SinvMat); gsl_matrix_free(SVD_V); gsl_vector_free(SVDWork); gsl_matrix_free(EKF_K); gsl_matrix_free(tempK); gsl_matrix_free(KRKT); gsl_matrix_free(tempKRKT); } /* exit */ fprintf(stdout,"%s GPS-INS Thread Exiting\n",MODULE_NAME); gsl_matrix_free(EKF_PHI); gsl_matrix_free(EKF_F); gsl_matrix_free(EKF_P_minus); gsl_matrix_free(tempP); gsl_matrix_free(EKF_P); gsl_matrix_free(I_17by17); gsl_vector_free(EKF_x_hat); gsl_matrix_free(EKF_Q); gsl_vector_free(temp1); gsl_matrix_free(KH); gsl_matrix_free(IminusKH); gsl_matrix_free(KHPminus); #ifdef USE_RTAI rt_make_soft_real_time(); if(rttGPSINS) { rt_task_delete(rttGPSINS); } stop_rt_timer(); #endif pthread_exit(NULL); }
{ "alphanum_fraction": 0.681381733, "avg_line_length": 25.9574468085, "ext": "c", "hexsha": "0574a2d86b3a1c7b3021d45ead80335372f3f709", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2019-11-14T08:30:11.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-01T20:17:26.000Z", "max_forks_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "duncang/gpsins", "max_forks_repo_path": "src/gpsins.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "duncang/gpsins", "max_issues_repo_path": "src/gpsins.c", "max_line_length": 130, "max_stars_count": 2, "max_stars_repo_head_hexsha": "729c561ebf3b08d6dc9f57814c550a4724a386af", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "duncang/gpsins", "max_stars_repo_path": "src/gpsins.c", "max_stars_repo_stars_event_max_datetime": "2020-07-11T06:23:46.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T14:23:48.000Z", "num_tokens": 14763, "size": 42700 }
/* Copyright 2010-2011, D. E. Shaw Research. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of D. E. Shaw Research nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <gsl/gsl_randist.h> #include <stdio.h> #include "Random123/philox.h" #include "Random123/threefry.h" #include "Random123/conventional/gsl_cbrng.h" #include <assert.h> /* Exercise the GSL_CBRNG macro */ GSL_CBRNG(cbrng, threefry4x64); /* creates gsl_rng_cbrng */ int main(int argc, char **argv){ int i; gsl_rng *r; gsl_rng *rcopy; unsigned long save, x; unsigned long saved[5]; double sum = 0.; (void)argc; (void)argv; /* unused */ r = gsl_rng_alloc(gsl_rng_cbrng); assert (gsl_rng_min(r) == 0); assert (gsl_rng_max(r) == 0xffffffffUL); // Not necessarily ~0UL assert (gsl_rng_size(r) > 0); printf("%s\nulongs from %s in initial state\n", argv[0], gsl_rng_name(r)); for (i = 0; i < 5; i++) { x = gsl_rng_get(r); saved[i] = x; printf("%d: 0x%lx\n", i, x); assert(x != 0); } printf("uniforms from %s\n", gsl_rng_name(r)); for (i = 0; i < 5; i++) { double z = gsl_rng_uniform(r); sum += z; printf("%d: %.4g\n", i, z); } assert( sum < 0.9*5 && sum > 0.1*5 && (long)"sum must be reasonably close to 0.5*number of trials"); save = gsl_rng_get(r); gsl_rng_set(r, 0xdeadbeef); /* set a non-zero seed */ printf("ulongs from %s after seed\n", gsl_rng_name(r)); for (i = 0; i < 5; i++) { x = gsl_rng_get(r); printf("%d: 0x%lx\n", i, x); assert(x != 0); } /* make a copy of the total state */ rcopy = gsl_rng_alloc(gsl_rng_cbrng); gsl_rng_memcpy(rcopy, r); printf("uniforms from %s\n", gsl_rng_name(r)); sum = 0.; for (i = 0; i < 5; i++) { double x = gsl_rng_uniform(r); double y = gsl_rng_uniform(rcopy); printf("%d: %.4g\n", i, x); sum += x; assert(x == y); } assert(gsl_rng_get(r) != save); assert( sum < 0.9*5 && sum > 0.1*5 && (long)"sum must be reasonably close to 0.5*number of trials"); /* gsl_rng_set(*, 0) is supposed to recover the default seed */ gsl_rng_set(r, 0); printf("ulongs from %s after restore to initial\n", gsl_rng_name(r)); for (i = 0; i < 5; i++) { x = gsl_rng_get(r); assert( x == saved[i] ); printf("%d: 0x%lx\n", i, x); assert(x != 0); } printf("uniforms from %s\n", gsl_rng_name(r)); for (i = 0; i < 5; i++) { printf("%d: %.4g\n", i, gsl_rng_uniform(r)); } assert(gsl_rng_get(r) == save); gsl_rng_free (r); return 0; }
{ "alphanum_fraction": 0.6584992343, "avg_line_length": 34.6725663717, "ext": "c", "hexsha": "986de7ce2b65c6fe21d920bf007950793f2d9adf", "lang": "C", "max_forks_count": 27, "max_forks_repo_forks_event_max_datetime": "2021-06-15T18:20:06.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-22T19:25:27.000Z", "max_forks_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "Yeahhhh/module", "max_forks_repo_path": "Random123/examples/ut_gsl.c", "max_issues_count": 68, "max_issues_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:14:13.000Z", "max_issues_repo_issues_event_min_datetime": "2015-08-21T11:28:54.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "Yeahhhh/module", "max_issues_repo_path": "Random123/examples/ut_gsl.c", "max_line_length": 105, "max_stars_count": 44, "max_stars_repo_head_hexsha": "ea486690d2c7958b5bcdda9102ca14591952bc6f", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "Yeahhhh/module", "max_stars_repo_path": "Random123/examples/ut_gsl.c", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:29:00.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-28T06:48:43.000Z", "num_tokens": 1119, "size": 3918 }
/* histogram/get.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> #include "find.c" double gsl_histogram_get (const gsl_histogram * h, size_t i) { const size_t n = h->n; if (i >= n) { GSL_ERROR_VAL ("index lies outside valid range of 0 .. n - 1", GSL_EDOM, 0); } return h->bin[i]; } int gsl_histogram_get_range (const gsl_histogram * h, size_t i, double *lower, double *upper) { const size_t n = h->n; if (i >= n) { GSL_ERROR ("index lies outside valid range of 0 .. n - 1", GSL_EDOM); } *lower = h->range[i]; *upper = h->range[i + 1]; return GSL_SUCCESS; } int gsl_histogram_find (const gsl_histogram * h, const double x, size_t * i) { int status = find (h->n, h->range, x, i); if (status) { GSL_ERROR ("x not found in range of h", GSL_EDOM); } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6470588235, "avg_line_length": 24.7714285714, "ext": "c", "hexsha": "6e832a55d24a57bd16afff3a08cc83895e61d40b", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/histogram/get.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 475, "size": 1734 }
#include "lib.h" #include "defines.h" #include "milosUtils.h" #include "time.h" #include <complex.h> #include <fftw3.h> //siempre a continuacion de complex.h #include <math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <complex.h> #include <fftw3.h> //siempre a continuacion de complex.h #include "convolution.h" #include "svdcmp.h" extern PRECISION **PUNTEROS_CALCULOS_COMPARTIDOS; extern int POSW_PUNTERO_CALCULOS_COMPARTIDOS; extern int POSR_PUNTERO_CALCULOS_COMPARTIDOS; extern REAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov; extern REAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2; extern REAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt; extern REAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv; extern REAL *dfi, *dshi; extern REAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r; extern REAL *spectra, *d_spectra, *spectra_mac, *spectra_slight; extern REAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn; extern REAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov; extern REAL *parcial1, *parcial2, *parcial3; extern REAL *nubB, *nupB, *nurB; extern PRECISION *G,*GMAC; extern fftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF; extern fftw_plan planForwardPSF, planBackwardPSF; extern fftw_complex * fftw_G_PSF; extern Cuantic *cuantic; // Variable global, está hecho así, de momento,para parecerse al original extern gsl_vector *eval; extern gsl_matrix *evec; extern gsl_eigen_symmv_workspace * workspace; extern int NTERMS; void AplicaDelta(Init_Model *model, PRECISION *delta, int *fixed, Init_Model *modelout) { int index =0; if (fixed[0]) // ETHA 0 { modelout->eta0 = model->eta0 - delta[0]; // 0 } if (fixed[1]) // B { if (delta[1] < -300) //300 delta[1] = -300; else if (delta[1] > 300) delta[1] = 300; modelout->B = model->B - delta[1]; //magnetic field } if (fixed[2]) // VLOS { modelout->vlos = model->vlos - delta[2]; } if (fixed[3]) // DOPPLER WIDTH { modelout->dopp = model->dopp - delta[3]; } if (fixed[4]) // DAMPING modelout->aa = model->aa - delta[4]; if (fixed[5]) // GAMMA { if (delta[5] < -30) //15 delta[5] = -30; else if (delta[5] > 30) delta[5] = 30; modelout->gm = model->gm - delta[5]; //5 } if (fixed[6]) // AZIMUTH { if (delta[6] < -30) delta[6] = -30; else if (delta[6] > 30) delta[6] = 30; modelout->az = model->az - delta[6]; } if (fixed[7]) modelout->S0 = model->S0 - delta[7]; if (fixed[8]) modelout->S1 = model->S1 - delta[8]; if (fixed[9]){ modelout->mac = model->mac - delta[9]; //9 } if (fixed[10]){ if(NTERMS==11) modelout->alfa = model->alfa - delta[10]; else { modelout->alfa = model->alfa - delta[9]; } } } int check(Init_Model *model) { //Magnetic field if (model->B < 0) { model->B = -(model->B); model->gm = 180.0 - (model->gm); } if (model->B > 5000) model->B = 5000; //Inclination if (model->gm < 0) model->gm = -(model->gm); if (model->gm > 180) { model->gm = 360.0 - model->gm; } //azimuth if (model->az < 0) model->az = 180 + (model->az); //model->az= 180 + (model->az); if (model->az > 180) { model->az = model->az - 180.0; } //Eta0 if (model->eta0 < 1) model->eta0 = 1; if (model->eta0 > 2500) //idl 2500 model->eta0 = 2500; //velocity if (model->vlos < (-20)) //20 model->vlos = (-20); if (model->vlos > 20) model->vlos = 20; //doppler width ;Do NOT CHANGE THIS if (model->dopp < 0.0001) model->dopp = 0.0001; if (model->dopp > 0.6) // idl 0.6 model->dopp = 0.6; // damping if (model->aa < 0.0001) // idl 1e-4 model->aa = 0.0001; if (model->aa > 10.0) //10 model->aa = 10.0; //S0 if (model->S0 < 0.0001) model->S0 = 0.0001; if (model->S0 > 2.00) model->S0 = 2.00; //S1 if (model->S1 < 0.0001) model->S1 = 0.0001; if (model->S1 > 2.00) model->S1 = 2.00; //macroturbulence if (model->mac < 0) model->mac = 0; if (model->mac > 4) model->mac = 4; // filling factor if(model->alfa<0) model->alfa = 0.0; if(model->alfa>1.0) model->alfa = 1.0; return 1; } void FijaACeroDerivadasNoNecesarias(REAL *d_spectra, int *fixed, int nlambda) { int In, j, i; if(NTERMS==9 || NTERMS==11){ for (In = 0; In < NTERMS; In++) if (fixed[In] == 0) for (j = 0; j < NPARMS; j++) for (i = 0; i < nlambda; i++) d_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0; } else if (NTERMS==10){ for (In = 0; In < NTERMS; In++){ if(In<9){ if (fixed[In] == 0) for (j = 0; j < NPARMS; j++) for (i = 0; i < nlambda; i++) d_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0; } else{ if (fixed[9] == 0 && fixed[10] == 0) for (j = 0; j < NPARMS; j++) for (i = 0; i < nlambda; i++) d_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0; } } } } /* Tamaño de H es NTERMS x NTERMS Tamaño de beta es 1xNTERMS return en delta tam 1xNTERMS */ int mil_svd(PRECISION *h, REAL *beta, PRECISION *delta) { const PRECISION epsilon = 1e-12; PRECISION *v, *w; int i, j; PRECISION aux2[NTERMS]; gsl_matrix_view gsl_h1 = gsl_matrix_view_array (h, NTERMS, NTERMS); gsl_eigen_symmv(&gsl_h1.matrix, eval, evec, workspace); w = gsl_vector_ptr(eval,0); v = gsl_matrix_ptr(evec,0,0); PRECISION sum; for ( j = 0; j < NTERMS; j++){ sum=0; for ( i = 0; i < NTERMS; i++){ sum += beta[i] * v[i*NTERMS+j]; } aux2[j] = sum * ((fabs(w[j]) > epsilon) ? (1/w[j]): 0.0); } for ( i = 0; i < NTERMS; i++){ sum=0; for ( j = 0; j < NTERMS; j++){ sum += v[i*NTERMS+j] * aux2[j]; } delta[i] = sum; } return 1; } /* * * * Cálculo de las estimaciones clásicas. * * * lambda_0 : centro de la línea * lambda : vector de muestras * nlambda : numero de muesras * spectro : vector [I,Q,U,V] * initModel: Modelo de atmosfera a ser modificado * */ void estimacionesClasicas(PRECISION lambda_0, PRECISION *lambda, int nlambda, float *spectro, Init_Model *initModel, int forInitialUse) { double x, y, aux, LM_lambda_plus, LM_lambda_minus, Blos, Ic, Vlos; double aux_vlos,x_vlos,y_vlos; float *spectroI, *spectroQ, *spectroU, *spectroV; double L, m, gamma, gamma_rad, tan_gamma, C; int i; spectroI = spectro; spectroQ = spectro + nlambda; spectroU = spectro + nlambda * 2; spectroV = spectro + nlambda * 3; //check if there is ghost lambdas in the extrems int beginLambda = 0; int exit=0; for(i=0;i<nlambda && !exit;i++){ if(spectroI[i]<0){ beginLambda++; } else { exit=1; } } int endLambda = nlambda; exit=0; for(i=nlambda-1;i>=0 && !exit;i--){ if(spectroI[i]<0){ endLambda--; } else { exit=1; } } Ic = spectro[endLambda - 1]; // Continuo ultimo valor de I x = 0; y = 0; x_vlos = 0; y_vlos = 0; for (i = beginLambda; i < endLambda-1 ; i++) { if(spectroI[i]>-1 && spectroV[i]>-1){ aux = (Ic - (spectroI[i] + spectroV[i])); aux_vlos = (Ic - spectroI[i]); x += (aux * (lambda[i] - lambda_0)); x_vlos += (aux_vlos * (lambda[i] - lambda_0)); y += aux; y_vlos += aux_vlos; } } //Para evitar nan if (fabs(y) > 1e-15) LM_lambda_plus = x / y; else LM_lambda_plus = 0; x = 0; y = 0; for (i = beginLambda; i < endLambda-1 ; i++) { if(spectroI[i]>-1 && spectroV[i]>-1){ aux = (Ic - (spectroI[i] - spectroV[i])); x += (aux * (lambda[i] - lambda_0)); y += aux; } } if (fabs(y) > 1e-15) LM_lambda_minus = x / y; else LM_lambda_minus = 0; C = (CTE4_6_13 * (lambda_0*lambda_0) * cuantic->GEFF); Blos = (1 / C) * ((LM_lambda_plus - LM_lambda_minus) / 2); Vlos = (VLIGHT / (lambda_0)) * ((x_vlos/y_vlos) / 2); // for now use the center without spectroV only spectroI //inclinacion x = 0; y = 0; for (i = beginLambda; i < endLambda - 1; i++) { if(spectroQ[i]>-1 && spectroU[i]>-1 && spectroV[i]>-1){ L = FABS(SQRT(spectroQ[i] * spectroQ[i] + spectroU[i] * spectroU[i])); m = fabs((4 * (lambda[i] - lambda_0) * L)); x = x + FABS(spectroV[i]) * m; y = y + FABS(spectroV[i]) * FABS(spectroV[i]); } } y = y * fabs((3 * C * Blos)); tan_gamma = fabs(sqrt(x / y)); gamma_rad = atan(tan_gamma); //gamma en radianes gamma = gamma_rad * (180 / PI); //gamma en grados if(forInitialUse){ if(gamma>=85 && gamma <=90){ gamma_rad = 85 *(PI/180); } if(gamma>90 && gamma <=95){ gamma_rad = 95 *(PI/180); } } //correction //we use the sign of Blos to see to correct the quadrant if (Blos < 0) gamma = (180) - gamma; // CALCULATIONS FOR AZIMUTH PRECISION tan2phi, phi; double sum_u =0.0, sum_q = 0.0; for(i=0;i<nlambda;i++){ if(spectroU[i]>-1 && spectroQ[i]>-1){ if( fabs(spectroU[i])>0.0001 || fabs(spectroQ[i])>0.0001 ){ sum_u += spectroU[i]; sum_q += spectroQ[i]; } } } tan2phi = sum_u/sum_q; phi = (atan(tan2phi) * 180 / PI) / 2; if ( sum_u > 0 && sum_q > 0 ) phi = phi; else if ( sum_u < 0 && sum_q > 0 ) phi = phi + 180; else if ( sum_u< 0 && sum_q < 0 ) phi = phi + 90; else if ( sum_u > 0 && sum_q < 0 ) phi = phi + 90; // END CALCULATIONS FOR AZIMUTH PRECISION B_aux; B_aux = fabs(Blos / cos(gamma_rad)); // if (Vlos < (-4)) Vlos = -4; if (Vlos > (4)) Vlos = 4; initModel->B = (B_aux > 4000 ? 4000 : B_aux); initModel->vlos = Vlos; initModel->gm = gamma; initModel->az = phi; if(!forInitialUse) // store Blos in SO if we are in non-initialization use initModel->S0 = Blos; } /* * * nwlineas : numero de lineas espectrales * wlines : lineas spectrales * lambda : wavelength axis in angstrom longitud nlambda * spectra : IQUV por filas, longitud ny=nlambda */ int lm_mils(Cuantic *cuantic, PRECISION *wlines, PRECISION *lambda, int nlambda, float *spectro, int nspectro, Init_Model *initModel, REAL *spectra, float *chisqrf, REAL * slight, PRECISION toplim, int miter, REAL *weight, int *fix, REAL *vSigma, REAL sigma, REAL ilambda, int * INSTRUMENTAL_CONVOLUTION, int * iter, REAL ah, int logclambda) { REAL PARBETA_better = 5.0; REAL PARBETA_worst = 10.0; REAL PARBETA_FACTOR = 1.0; //int iter; int i, *fixed, nfree, n_ghosts=0, log = 0; PRECISION delta[NTERMS]; for(i=0;i<nlambda*NPARMS;i++){ if(spectro[i]<=-1){ vSigma[i]= 1000000000000000000000.0; n_ghosts++; } else{ vSigma[i] = sigma; } } // we use *iter to know if we are in the first pixel inverted if(*iter==0){ printf("\n--------------------------------------------------------------------------------"); printf("\n %d points in the profiles not inverted because they are smaller than -1",n_ghosts); printf("\n--------------------------------------------------------------------------------\n"); log=1; } REAL flambda,s_n; REAL beta[NTERMS], alpha[NTERMS * NTERMS]; REAL chisqr, ochisqr, chisqr0; int clanda, ind; Init_Model model; nfree = CalculaNfree(nspectro); nfree = nfree - n_ghosts; if (nfree == 0) { return -1; //'NOT ENOUGH POINTS' } flambda = ilambda; if (fix == NULL) { int fixed_static[NTERMS]; fixed = fixed_static; for (i = 0; i < NTERMS; i++) { fixed[i] = 1; } } else { fixed = fix; } clanda = 0; *iter = 0; PRECISION covar[NTERMS * NTERMS]; mil_sinrf(cuantic, initModel, wlines, lambda, nlambda, spectra, ah,slight,spectra_mac, spectra_slight, *INSTRUMENTAL_CONVOLUTION); me_der(cuantic, initModel, wlines, lambda, nlambda, d_spectra, spectra_mac, spectra_slight,ah, slight, *INSTRUMENTAL_CONVOLUTION,fixed); FijaACeroDerivadasNoNecesarias(d_spectra,fixed,nlambda); covarm2(weight, vSigma, spectro, nlambda, spectra, d_spectra, beta, alpha); for (i = 0; i < NTERMS * NTERMS; i++){ covar[i] = alpha[i]; } ochisqr = fchisqr(spectra, nspectro, spectro, weight, vSigma, nfree); chisqr0 = ochisqr; model = *initModel; if(log){ printf("\n______________________________________________________________________"); printf("\nit\tDE \t s/n \t chi**2 \t mac\t fill\n"); } do { // CHANGE VALUES OF DIAGONAL for (i = 0; i < NTERMS; i++) { ind = i * (NTERMS + 1); covar[ind] = alpha[ind] * (1.0 + flambda); } mil_svd(covar, beta, delta); AplicaDelta(initModel, delta, fixed, &model); check(&model); mil_sinrf(cuantic, &model, wlines, lambda, nlambda, spectra, ah,slight,spectra_mac,spectra_slight,*INSTRUMENTAL_CONVOLUTION); chisqr = fchisqr(spectra, nspectro, spectro, weight, vSigma, nfree); /**************************************************************************/ //printf("\n CHISQR EN LA ITERACION %d,: %e",*iter,chisqr); /**************************************************************************/ if ((FABS((ochisqr-chisqr)*100/chisqr) < toplim) || (chisqr < 0.0001)) // condition to exit of the loop clanda = 1; if (chisqr - ochisqr < 0.) { //flambda = flambda / 10.0; flambda=flambda/(PARBETA_better*PARBETA_FACTOR); *initModel = model; me_der(cuantic, initModel, wlines, lambda, nlambda, d_spectra, spectra_mac,spectra, ah, slight,*INSTRUMENTAL_CONVOLUTION,fixed); FijaACeroDerivadasNoNecesarias(d_spectra,fixed,nlambda); covarm2(weight, vSigma, spectro, nlambda, spectra, d_spectra, beta, alpha); for (i = 0; i < NTERMS * NTERMS; i++) covar[i] = alpha[i]; ochisqr = chisqr; if(log){ float suma_aux =0; float f_aux; for(i=0;i<nspectro;i++){ f_aux = (spectro[i]-spectra[i]); suma_aux = suma_aux + (f_aux*f_aux); } s_n= (nlambda*(nspectro-n_ghosts))/suma_aux; printf("\n%d\t%f\t%9.2e\t%10.3e\t%6.3f\t%6.3f",*iter,flambda,s_n,ochisqr,initModel->mac,initModel->alfa); } } else { for (i = 0; i < NTERMS * NTERMS; i++) covar[i] = alpha[i]; flambda=flambda*PARBETA_worst*PARBETA_FACTOR; if(log) printf("\n%d\t%f\t increases\t______________________________",*iter,flambda); } if ((flambda > 1e+7) || (flambda < 1e-25)) clanda=1 ; // condition to exit of the loop (*iter)++; if(logclambda) PARBETA_FACTOR = log10f(chisqr)/log10f(chisqr0); } while (*iter < miter && !clanda); *chisqrf = ochisqr; if(log){ printf("\n______________________________________________________________________\n"); } if (fix == NULL) free(fixed); return 1; } /** * Make the interpolation between deltaLambda and PSF where deltaLambda es x and PSF f(x) * Return the array with the interpolation. * */ int interpolationSplinePSF(PRECISION *deltaLambda, PRECISION * PSF, PRECISION * lambdasSamples, size_t N_PSF, PRECISION * fInterpolated, size_t NSamples){ size_t i; gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline_cubic = gsl_spline_alloc(gsl_interp_cspline, N_PSF); //gsl_spline *spline_akima = gsl_spline_alloc(gsl_interp_akima, NSamples); //gsl_spline *spline_steffen = gsl_spline_alloc(gsl_interp_steffen, NSamples); gsl_spline_init(spline_cubic, deltaLambda, PSF, N_PSF); //gsl_spline_init(spline_akima, deltaLambda, PSF, N_PSF); //gsl_spline_init(spline_steffen, deltaLambda, PSF, N_PSF); for (i = 0; i < NSamples; ++i){ //fInterpolated[i] = gsl_spline_eval(spline_cubic, xi, acc); //PRECISION yi_akima = gsl_spline_eval(spline_akima, xi, acc); //PRECISION yi_steffen = gsl_spline_eval(spline_steffen, lambdasSamples[i], acc); PRECISION yi = gsl_spline_eval(spline_cubic, lambdasSamples[i], acc); if(!gsl_isnan(yi)){ fInterpolated[i] = yi; } else { fInterpolated[i] = 0.0f; } } gsl_spline_free(spline_cubic); //gsl_spline_free(spline_akima); //gsl_spline_free(spline_steffen); gsl_interp_accel_free(acc); return 1; } /** * Make the interpolation between deltaLambda and PSF where deltaLambda es x and PSF f(x) * Return the array with the interpolation. * */ int interpolationLinearPSF(PRECISION *deltaLambda, PRECISION * PSF, PRECISION * lambdasSamples, size_t N_PSF, PRECISION * fInterpolated, size_t NSamples,double offset){ size_t i; gsl_interp *interpolation = gsl_interp_alloc (gsl_interp_linear,N_PSF); gsl_interp_init(interpolation, deltaLambda, PSF, N_PSF); gsl_interp_accel * accelerator = gsl_interp_accel_alloc(); for (i = 0; i < NSamples; ++i){ double aux; if(offset>=0){ if(lambdasSamples[i]-offset>= deltaLambda[0]){ aux = gsl_interp_eval(interpolation, deltaLambda, PSF, lambdasSamples[i]-offset, accelerator); // if lambdasSamples[i] is out of range from deltaLambda then aux is GSL_NAN, we put nan values to 0. if(!gsl_isnan(aux)) fInterpolated[i] = aux; else fInterpolated[i] = 0.0f; } else { aux = 0.0f; } } else{ if(lambdasSamples[i]-offset>= deltaLambda[NSamples-1]){ aux = gsl_interp_eval(interpolation, deltaLambda, PSF, lambdasSamples[i]-offset, accelerator); // if lambdasSamples[i] is out of range from deltaLambda then aux is GSL_NAN, we put nan values to 0. if(!gsl_isnan(aux)) fInterpolated[i] = aux; else fInterpolated[i] = 0.0f; } else { aux = 0.0f; } } } // normalizations double cte = 0; for(i=0; i< NSamples; i++){ cte += fInterpolated[i]; } for(i=0; i< NSamples; i++){ fInterpolated[i] /= cte; } gsl_interp_accel_free(accelerator); gsl_interp_free(interpolation); return 1; }
{ "alphanum_fraction": 0.6168943956, "avg_line_length": 23.3721244926, "ext": "c", "hexsha": "95966861ef263bcfa94d5dd70fc366cf99f51554", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z", "max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dcalc/hrt_pipeline", "max_forks_repo_path": "p-milos/src/milosUtils.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dcalc/hrt_pipeline", "max_issues_repo_path": "p-milos/src/milosUtils.c", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dcalc/hrt_pipeline", "max_stars_repo_path": "p-milos/src/milosUtils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6369, "size": 17272 }
/** * * @file core_dlansy.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:44:46 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_double * * CORE_PLASMA_dlansy returns the value * * dlansy = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm * ( * ( norm1(A), NORM = PlasmaOneNorm * ( * ( normI(A), NORM = PlasmaInfNorm * ( * ( normF(A), NORM = PlasmaFrobeniusNorm * * where norm1 denotes the one norm of a matrix (maximum column sum), * normI denotes the infinity norm of a matrix (maximum row sum) and * normF denotes the Frobenius norm of a matrix (square root of sum * of squares). Note that max(abs(A(i,j))) is not a consistent matrix * norm. * ******************************************************************************* * * @param[in] norm * = PlasmaMaxNorm: Max norm * = PlasmaOneNorm: One norm * = PlasmaInfNorm: Infinity norm * = PlasmaFrobeniusNorm: Frobenius norm * * @param[in] uplo * = PlasmaUpper: Upper triangle of A is stored; * = PlasmaLower: Lower triangle of A is stored. * * @param[in] N * The number of columns/rows of the matrix A. N >= 0. When N = 0, * the returned value is set to zero. * * @param[in] A * The N-by-N matrix A. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,N). * * @param[in,out] work * Array of dimension (MAX(1,LWORK)), where LWORK >= N when norm = * PlasmaInfNorm or PlasmaOneNorm; otherwise, work is not referenced. * * @param[out] normA * On exit, normA is the norm of matrix A. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlansy = PCORE_dlansy #define CORE_dlansy PCORE_dlansy #endif void CORE_dlansy(int norm, PLASMA_enum uplo, int N, const double *A, int LDA, double *work, double *normA) { *normA = LAPACKE_dlansy_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), N, A, LDA, work); }
{ "alphanum_fraction": 0.5397505846, "avg_line_length": 30.9156626506, "ext": "c", "hexsha": "bd341d3bbfdafb6184784e487a9dc789ad1acd1f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_dlansy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_dlansy.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_dlansy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 679, "size": 2566 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2003-2009 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #include <time.h> #include <gsl/gsl_randist.h> #include "ObitThread.h" #include "ObitOTFUtil.h" #include "ObitOTFGetSoln.h" #include "ObitTableOTFIndex.h" #include "ObitTableOTFTargetUtil.h" #include "ObitImageUtil.h" /*----------------Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitOTFUtil.c * ObitOTF class utility function definitions. */ /*---------------Private structures----------------*/ /* SubImage threaded function argument */ typedef struct { /* OTF data set to model and subtract from current buffer */ ObitOTF *otfdata; /* First (1-rel) record in otfdata buffer to process this thread */ olong first; /* Highest (1-rel) record in otfdata buffer to process this thread */ olong last; /* thread number, <0 -> no threading */ olong ithread; /* Obit error stack object */ ObitErr *err; /* Image Interpolator */ ObitFInterpolate *Interp; /* Scaling factor for model */ ofloat factor; /* Work arrays the size of ndetect */ ofloat *xpos, *ypos; } SubImageFuncArg; /*---------------Private function prototypes----------------*/ /** Private: Subtract an image interpolator from a buffer of data. */ void ObitOTFUtilSubImageBuff (ObitOTF *in, ObitFInterpolate *image, ofloat factor, olong nThread, SubImageFuncArg **args, ObitErr *err); /** Private: Convert an ObitOTFDesc to an ObitImageDesc */ static void ObitOTFUtilOTF2ImageDesc(ObitOTFDesc *OTFDesc, ObitImageDesc *imageDesc, gchar *Proj); /** Private: Get Date string for current date */ static void ObitOTFUtilCurDate (gchar *date, olong len); /** Private: Threaded OTFUtilSubImageBuff */ static gpointer ThreadOTFUtilSubImageBuff (gpointer arg); /** Private: Make arguments for Threaded OTFUtilSubImageBuff */ static olong MakeOTFUtilSubImageArgs (ObitOTF *in, ObitErr *err, SubImageFuncArg ***args); /** Private: Delete arguments for Threaded OTFUtilSubImageBuff */ static void KillOTFUtilSubImageArgs (olong nargs, SubImageFuncArg **args); #define MAXSAMPLE 10000 /* Maximum number of samples in a scan */ /*----------------------Public functions---------------------------*/ /** * Subtract a 2D ObitFArray from an OTF * \param inOTF Input OTF * \param outOTF Output OTF, must already be defined * \param image Image plane to subtract * \param desc Image descriptor for image * \param err Error stack */ void ObitOTFUtilSubImage(ObitOTF *inOTF, ObitOTF *outOTF, ObitFArray *image, ObitImageDesc *desc, ObitErr *err) { ObitFInterpolate *imageInt=NULL; ObitIOCode retCode; gboolean doCalSelect, done, same, doScale; olong firstRec; ObitInfoType type; ObitIOAccess access; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat scale = 1.0; olong NPIO, nThreads=1; SubImageFuncArg **targs=NULL; /* Don't copy Cal and Soln or data or flag tables */ gchar *exclude[]={"OTFSoln", "OTFCal", "OTFScanData", "OTFFlag", NULL}; gchar *routine = "ObitOTFUtilSubImage"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitFArrayIsA(image)); g_assert (ObitImageDescIsA(desc)); g_assert (ObitOTFIsA(inOTF)); g_assert (ObitOTFIsA(outOTF)); /* An interpolator for the image */ imageInt = newObitFInterpolateCreate (image->name, image, desc, 2); /* are input and utput the same? */ same = ObitOTFSame (inOTF, outOTF, err); /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Make sure NPIO the same */ NPIO = 1000; dim[0] = 1; ObitInfoListGetTest (inOTF->info, "nRecPIO", &type, dim, &NPIO); ObitInfoListAlwaysPut (inOTF->info, "nRecPIO", OBIT_long, dim, &NPIO); ObitInfoListAlwaysPut (outOTF->info, "nRecPIO", OBIT_long, dim, &NPIO); /* Open Input Data */ retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; if (!same) { /* use same data buffer on input and output so don't assign buffer for output */ if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */ outOTF->buffer = inOTF->buffer; outOTF->bufferSize = inOTF->bufferSize; /* Open Output Data */ retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; } /* Copy tables before data if they are different */ if (!same) { retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err); if (err->error) goto cleanup; } /* Close and reopen input to init calibration which will have been disturbed by the table copy */ retCode = ObitOTFClose (inOTF, err); if (err->error) goto cleanup; retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; /* Scaling if needed to convert from image brightness to data square of ratio of beam areas */ doScale = TRUE; ObitInfoListGetTest(inOTF->info, "doScale", &type, dim, &doScale); if (doScale) { scale = inOTF->myDesc->beamSize / desc->beamMaj; scale = scale * scale; } else { scale = 1.0; } /*fprintf (stderr,"Scaling image to data by %f\n",scale); *//*debug */ /* Setup Threading */ nThreads = MakeOTFUtilSubImageArgs (inOTF, err, &targs); /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */# retCode = ObitOTFRead (inOTF, NULL, err); if (err->error) goto cleanup; done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; firstRec = inOTF->myDesc->firstRec; /* How many? */ outOTF->myDesc->numRecBuff = inOTF->myDesc->numRecBuff; if (outOTF->myDesc->numRecBuff>0) { /* Subtract image from this buffer */ ObitOTFUtilSubImageBuff (outOTF, imageInt, scale, nThreads, targs, err); /* Write buffer */ retCode = ObitOTFWrite (outOTF, NULL, err); } if (err->error) goto cleanup; /* suppress vis number update if rewriting the same file */ if (same) { outOTF->myDesc->firstRec = firstRec; ((ObitOTFDesc*)(outOTF->myIO->myDesc))->firstRec = firstRec; } } /* end scan loop */ cleanup: /* unset output buffer (may be multiply deallocated ;'{ ) */ if (!same) { outOTF->buffer = NULL; outOTF->bufferSize = 0; retCode = ObitOTFClose (outOTF, err); /* Close output */ } /* Close input */ retCode = ObitOTFClose (inOTF, err); /* cleanup */ imageInt = ObitFInterpolateUnref(imageInt); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); /* Shutdown Threading */ KillOTFUtilSubImageArgs (nThreads, targs); } /* end ObitOTFUtilSubImage */ /** * Replace the data in an OTF with the model values from FArray image * \param inOTF Input OTF * \param outOTF Output OTF, must already be defined * \param image Image plane to subtract * \param desc Image descriptor for image * \param err Error stack */ void ObitOTFUtilModelImage(ObitOTF *inOTF, ObitOTF *outOTF, ObitFArray *image, ObitImageDesc *desc, ObitErr *err) { ObitFInterpolate *imageInt=NULL; ObitIOCode retCode; gboolean doCalSelect, done, same, doScale; olong firstRec; ObitInfoType type; ObitIOAccess access; gint32 dim[MAXINFOELEMDIM]; ofloat scale = 1.0; olong NPIO; /* Don't copy Cal and Soln or data or flag tables */ gchar *exclude[]={"OTFSoln", "OTFCal", "OTFScanData", "OTFFlag", NULL}; gchar *routine = "ObitOTFUtilModelImage"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitFArrayIsA(image)); g_assert (ObitImageDescIsA(desc)); g_assert (ObitOTFIsA(inOTF)); g_assert (ObitOTFIsA(outOTF)); /* An interpolator for the image */ imageInt = newObitFInterpolateCreate (image->name, image, desc, 2); /* are input and utput the same? */ same = ObitOTFSame (inOTF, outOTF, err); /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Make sure NPIO the same */ NPIO = 1000; dim[0] = 1; ObitInfoListGetTest (inOTF->info, "nRecPIO", &type, dim, &NPIO); ObitInfoListAlwaysPut (inOTF->info, "nRecPIO", OBIT_long, dim, &NPIO); ObitInfoListAlwaysPut (outOTF->info, "nRecPIO", OBIT_long, dim, &NPIO); /* Open Input Data */ retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; if (!same) { /* use same data buffer on input and output so don't assign buffer for output */ if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */ outOTF->buffer = inOTF->buffer; outOTF->bufferSize = inOTF->bufferSize; /* Open Output Data */ retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; } /* Copy tables before data if they are different */ if (!same) { retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err); if (err->error) goto cleanup; } /* Close and reopen input to init calibration which will have been disturbed by the table copy */ retCode = ObitOTFClose (inOTF, err); if (err->error) goto cleanup; retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) goto cleanup; /* Scaling if needed to convert from image brightness to data square of ratio of beam areas */ doScale = TRUE; ObitInfoListGetTest(inOTF->info, "doScale", &type, dim, &doScale); if (doScale) { scale = inOTF->myDesc->beamSize / desc->beamMaj; scale = scale * scale; } /*fprintf (stderr,"Scaling image to data by %f\n",scale); *//*debug */ /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */# retCode = ObitOTFRead (inOTF, NULL, err); if (err->error) goto cleanup; done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; firstRec = inOTF->myDesc->firstRec; /* How many? */ outOTF->myDesc->numRecBuff = inOTF->myDesc->numRecBuff; if (outOTF->myDesc->numRecBuff>0) { /* Replace data with model in this buffer */ ObitOTFUtilModelImageBuff (outOTF, imageInt, scale, err); /* Write buffer */ retCode = ObitOTFWrite (outOTF, NULL, err); } if (err->error) goto cleanup; /* suppress vis number update if rewriting the same file */ if (same) { outOTF->myDesc->firstRec = firstRec; ((ObitOTFDesc*)(outOTF->myIO->myDesc))->firstRec = firstRec; } } /* end scan loop */ cleanup: /* unset output buffer (may be multiply deallocated ;'{ ) */ if (!same) { outOTF->buffer = NULL; outOTF->bufferSize = 0; retCode = ObitOTFClose (outOTF, err); /* Close output */ } /* Close input */ retCode = ObitOTFClose (inOTF, err); /* cleanup */ imageInt = ObitFInterpolateUnref(imageInt); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); } /* end ObitOTFUtilModelImage */ /** * Multiply all data in an OTF by a scale factor and add an offset * out = in*scale + offset * \param inOTF Input OTF * \param outOTF Output OTF, must already be defined * \param scale scaling factor for data * \param offset additive term to be applied to all data. * \param err Error stack */ void ObitOTFUtilScale(ObitOTF *inOTF, ObitOTF *outOTF, ofloat scale, ofloat offset, ObitErr *err) { ObitIOCode retCode; gboolean doCalSelect, done; ObitInfoType type; ObitIOAccess access; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat *data, fblank = ObitMagicF(); olong i, j, ndetect, ndata; olong incdatawt; ObitOTFDesc* desc; /* Don't copy Cal and Soln or data or flag tables */ gchar *exclude[]={"OTFSoln", "OTFCal", "OTFScanData", "OTFFlag", NULL}; gchar *routine = "ObitOTFUtilScale"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitOTFIsA(inOTF)); g_assert (ObitOTFIsA(outOTF)); /* Local pointers */ desc = inOTF->myDesc; incdatawt = desc->incdatawt; /* increment in data-wt axis */ /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Open Input Data */ retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inOTF->name); /* use same data buffer on input and output so don't assign buffer for output */ if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */ outOTF->buffer = inOTF->buffer; outOTF->bufferSize = inOTF->bufferSize; /* Open Output Data */ retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) { outOTF->buffer = NULL; /* remove pointer to inOTF buffer */ outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, outOTF->name); } /* Copy tables before data */ retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err); if (err->error) {/* add traceback,return */ outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } /* Close and reopen input to init calibration which will have been disturbed by the table copy */ retCode = ObitOTFClose (inOTF, err); if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } ndetect = inOTF->geom->numberDetect; /* How many detectors */ /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */ retCode = ObitOTFRead (inOTF, NULL, err); if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; /* How many? */ ndata = inOTF->myDesc->numRecBuff; outOTF->myDesc->numRecBuff = ndata; if (ndata>0) { /* Modify data from this buffer */ data = inOTF->buffer; /* data pointer */ /* Loop over buffer */ for (i=0; i<ndata; i++) { /* Loop over detectors */ for (j=0; j<ndetect; j++) { /* Modify */ if (data[desc->ilocdata+j*incdatawt]!=fblank) { data[desc->ilocdata+j*incdatawt] *= scale; data[desc->ilocdata+j*incdatawt] += offset; } } /* end loop over detectors */ data += desc->lrec; /* update buffer pointer */ } /* end Loop over buffer */ /* Write buffer */ retCode = ObitOTFWrite (outOTF, NULL, err); } if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, outOTF->name); } } /* end data loop */ /* unset output buffer (may be multiply deallocated ;'{ ) */ outOTF->buffer = NULL; outOTF->bufferSize = 0; /* Close input */ retCode = ObitOTFClose (inOTF, err); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); /* Close output */ retCode = ObitOTFClose (outOTF, err); if (err->error) Obit_traceback_msg (err, routine, outOTF->name); } /* end ObitOTFUtilScale */ /** * Add Gaussian noise to an OTF * out = in*scale +offset + noise (sigma) * \param inOTF Input OTF * \param outOTF Output OTF, must already be defined * \param scale scaling factor for data * \param offset additive term to be applied to all data. * \param sigma Standard deviation of Gaussian noise . * \param err Error stack */ void ObitOTFUtilNoise(ObitOTF *inOTF, ObitOTF *outOTF, ofloat scale, ofloat offset, ofloat sigma, ObitErr *err) { ObitIOCode retCode; gboolean doCalSelect, done; ObitInfoType type; ObitIOAccess access; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat *data, fblank = ObitMagicF(); odouble dsigma = sigma; olong i, j, ndetect, ndata; olong incdatawt; ObitOTFDesc* desc; /* Don't copy Cal and Soln or data or flag tables */ gchar *exclude[]={"OTFSoln", "OTFCal", "OTFScanData", "OTFFlag", NULL}; gsl_rng *ran=NULL; gchar *routine = "ObitOTFUtilNoise"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitOTFIsA(inOTF)); g_assert (ObitOTFIsA(outOTF)); /* Local pointers */ desc = inOTF->myDesc; incdatawt = desc->incdatawt; /* increment in data-wt axis */ /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Open Input Data */ retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inOTF->name); /* use same data buffer on input and output so don't assign buffer for output */ if (outOTF->buffer) ObitIOFreeBuffer(outOTF->buffer); /* free existing */ outOTF->buffer = inOTF->buffer; outOTF->bufferSize = inOTF->bufferSize; /* Open Output Data */ retCode = ObitOTFOpen (outOTF, OBIT_IO_WriteOnly, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) { outOTF->buffer = NULL; /* remove pointer to inOTF buffer */ outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, outOTF->name); } /* Copy tables before data */ retCode = ObitOTFCopyTables (inOTF, outOTF, exclude, NULL, err); if (err->error) {/* add traceback,return */ outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } /* Close and reopen input to init calibration which will have been disturbed by the table copy */ retCode = ObitOTFClose (inOTF, err); if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } retCode = ObitOTFOpen (inOTF, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } ndetect = inOTF->geom->numberDetect; /* How many detectors */ /* Init random number generator */ ran = gsl_rng_alloc(gsl_rng_taus); /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */ retCode = ObitOTFRead (inOTF, NULL, err); if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, inOTF->name); } done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; /* How many? */ ndata = inOTF->myDesc->numRecBuff; outOTF->myDesc->numRecBuff = ndata; if (ndata>0) { /* Modify data from this buffer */ data = inOTF->buffer; /* data pointer */ /* Loop over buffer */ for (i=0; i<ndata; i++) { /* Loop over detectors */ for (j=0; j<ndetect; j++) { /* Modify */ if (data[desc->ilocdata+j*incdatawt]!=fblank) { data[desc->ilocdata+j*incdatawt] *= scale; data[desc->ilocdata+j*incdatawt] += offset + (ofloat)gsl_ran_gaussian (ran, dsigma); } } /* end loop over detectors */ data += desc->lrec; /* update buffer pointer */ } /* end Loop over buffer */ /* Write buffer */ retCode = ObitOTFWrite (outOTF, NULL, err); } if (err->error) { outOTF->buffer = NULL; outOTF->bufferSize = 0; Obit_traceback_msg (err, routine, outOTF->name); } } /* end data loop */ /* unset output buffer (may be multiply deallocated ;'{ ) */ outOTF->buffer = NULL; outOTF->bufferSize = 0; /* Free random number generator */ gsl_rng_free(ran); /* Close input */ retCode = ObitOTFClose (inOTF, err); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); /* Close output */ retCode = ObitOTFClose (outOTF, err); if (err->error) Obit_traceback_msg (err, routine, outOTF->name); } /* end ObitOTFUtilNoise */ /** * Subtract a sky model from a buffer full of OTF data. * \param in OTF with internal buffer to be modified. * \param sky OTFSkyModel to subtract. * \param factor Scaling factor for sky model. */ void ObitOTFUtilSubSkyModelBuff (ObitOTF *in, ObitOTFSkyModel *sky, ofloat factor) { ofloat *xpos, *ypos, *data, dist, maxdist, arg, gf1, gf2, sigma; olong incdatawt; olong ndetect, ndata, ncomp, i, j, k; ObitOTFDesc* desc; ObitOTFArrayGeom* geom; /* Error checks */ g_assert (ObitOTFIsA(in)); g_assert (ObitOTFSkyModelIsA(sky)); /* Local pointers */ desc = in->myDesc; geom = in->geom; data = in->buffer; ndetect = geom->numberDetect; /* How many detectors */ ndata = desc->numRecBuff; /* How many data records */ ncomp = sky->numberComp; /* How many components */ incdatawt = desc->incdatawt; /* increment in data-wt axis */ /* Allocate temporary arrays */ /* Projected data locations */ xpos = g_malloc0(ndetect*sizeof(float)); ypos = g_malloc0(ndetect*sizeof(float)); /* How close (deg^2) to consider 3 * beam size */ maxdist = (desc->beamSize * 3.0) * (desc->beamSize * 3.0); /* Gaussian factors */ sigma = desc->beamSize/2.35; gf1 = 1.0 / (2.0 * sigma * sigma); /* Normalize the flux integral rather than the peak */ gf2 = factor / sqrt(2.0 * G_PI); /* debug - normalize peak */ gf2 = -1.0; /* Loop over data records */ for (i=0; i<ndata; i++) { /* Get Sky locations of the data */ ObitOTFArrayGeomProj (geom, data[desc->ilocra], data[desc->ilocdec], data[desc->ilocrot], sky->RACenter, sky->DecCenter, sky->proj, xpos, ypos); /* Loop over the array */ for (j=0; j<ndetect; j++) { /* loop over components in Sky model */ for (k=0; k<ncomp; k++) { /* how far is the measurement from the component (distance^2) */ dist = (xpos[j]-sky->RAOffset[k]) * (xpos[j]-sky->RAOffset[k]) + (ypos[j]-sky->DecOffset[k]) * (ypos[j]-sky->DecOffset[k]); /* Is this one close enough? */ if (dist<maxdist) { arg = -dist * gf1; data[desc->ilocdata+j*incdatawt] -= gf2 * exp (arg) * sky->flux[k]; /* subtract */ } } /* end loop over components */ } /* end loop over array */ data += desc->lrec; /* update buffer pointer */ } /* end loop over buffer */ /* cleanup */ if (xpos) g_free(xpos); if (ypos) g_free(ypos); } /* end ObitOTFUtilSubSkyModelBuff */ /** * Subtract the values in an image from a buffer full of OTF data. * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1) * If threading has been enabled by a call to ObitThreadAllowThreads * this routine will divide the buffer up amount the number of processors * returned by ObitThreadNumProc. * \param in OTF with internal buffer to be modified. * \param image Image interpolator * \param factor Scaling factor for model. * \param nThreads Number of elements in args * \param args Threaded function argument structs * \param err Error stack */ void ObitOTFUtilSubImageBuff (ObitOTF *in, ObitFInterpolate *image, ofloat factor, olong nThreads, SubImageFuncArg **args, ObitErr *err) { olong i, nrec, lorec, hirec, nTh, nrecPerThread; gboolean OK = TRUE; gchar *routine = "ObitOTFUtilSubImageBuff"; /* error checks - assume most done at higher level */ if (err->error) return; /* Divide up work */ nrec = in->myDesc->numRecBuff; nrecPerThread = nrec/nThreads; nTh = nThreads; if (nrec<100) {nrecPerThread = nrec; nTh = 1;} lorec = 1; hirec = nrecPerThread; hirec = MIN (hirec, nrec); /* Set up thread arguments */ for (i=0; i<nTh; i++) { if (i==(nTh-1)) hirec = nrec; /* Make sure do all */ args[i]->otfdata = in; args[i]->first = lorec; args[i]->last = hirec; if (i==0) args[i]->Interp = ObitFInterpolateRef(image); else args[i]->Interp = ObitFInterpolateClone(image, NULL); args[i]->factor = factor; if (nTh>1) args[i]->ithread = i; else args[i]->ithread = -1; /* Update which rec */ lorec += nrecPerThread; hirec += nrecPerThread; hirec = MIN (hirec, nrec); } /* Do operation */ OK = ObitThreadIterator (in->thread, nTh, (ObitThreadFunc)ThreadOTFUtilSubImageBuff, (gpointer**)args); /* Check for problems */ if (!OK) Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); } /* end ObitOTFUtilSubImageBuff */ /** * Replace data with the values in an image in a buffer full of OTF data. * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1) * \param in OTF with internal buffer to be modified. * \param image Image interpolator * \param factor Scaling factor for model. * \param err Error stack */ void ObitOTFUtilModelImageBuff (ObitOTF *in, ObitFInterpolate *image, ofloat factor, ObitErr *err) { ofloat *xpos, *ypos, *data, ffact, value, RACenter, DecCenter; ObitOTFProj proj; odouble coord[IM_MAXDIM]; olong ndetect, ndata, i, j; olong incfeed, itemp,incdatawt ; gboolean CCBBS, isRef; ObitOTFDesc* desc; ObitOTFArrayGeom* geom; ofloat fblank = ObitMagicF(); gchar Proj[5]; /* Error checks */ g_assert (ObitOTFIsA(in)); g_assert (ObitFInterpolateIsA(image)); /* Local pointers */ desc = in->myDesc; geom = in->geom; data = in->buffer; ndetect = geom->numberDetect; /* How many detectors */ ndata = desc->numRecBuff; /* How many data records */ if (in->myDesc->jlocfeed>=0) incfeed = in->myDesc->incfeed / in->myDesc->incdatawt; else incfeed = 1; /* This is probably a bad sign */ /* Get Model center */ RACenter = image->myDesc->crval[0]; DecCenter = image->myDesc->crval[1]; strncpy (Proj, &image->myDesc->ctype[0][4], 5); proj = ObitOTFSkyModelProj (Proj); incdatawt = desc->incdatawt; /* increment in data-wt axis */ /* Is this CCB beamswitched data? */ CCBBS = (in->myDesc->OTFType==OBIT_GBTOTF_CCB) && (in->myDesc->jlocstate>=0) && (in->myDesc->inaxes[in->myDesc->jlocstate]==1); /* Allocate temporary arrays */ /* Projected data locations */ xpos = g_malloc0(ndetect*sizeof(float)); ypos = g_malloc0(ndetect*sizeof(float)); ffact = factor; /* Loop over data records */ for (i=0; i<ndata; i++) { /* Get Sky locations of the data projected onto the image */ ObitOTFArrayGeomProj(geom, data[desc->ilocra], data[desc->ilocdec], data[desc->ilocrot], RACenter, DecCenter, proj, xpos, ypos); /* Loop over the array */ for (j=0; j<ndetect; j++) { /* Interpolate - use coordinates on a flat plane at the tangent point of the image xpos and ypos are offsets from the image center projected onto the plane of the image, ObitFInterpolateOffset does a linear approximation. */ coord[0] = xpos[j]; /* + RACenter; */ coord[1] = ypos[j]; /* + DecCenter; */ value = ObitFInterpolateOffset (image, coord, err); /* Replace */ if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank)) data[desc->ilocdata+j*incdatawt] = value * ffact; else { data[desc->ilocdata+j*incdatawt] = fblank; } /* For CCB beamswitched data add value corresponding to this feeds reference beam */ if (CCBBS) { /* is this the reference or signal beam? */ itemp = j / incfeed; /* itemp odd means reference beam */ isRef = itemp != 2*(itemp/2); /* Use feed offset for feed 1 if this is reference, else feed 2 */ if (isRef) itemp = 0; else itemp = incfeed; /* interpolate */ coord[0] = xpos[itemp]; /* + RACenter; */ coord[1] = ypos[itemp]; /* + DecCenter; */ value = ObitFInterpolateOffset (image, coord, err); /* Replace */ if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank)) data[desc->ilocdata+j*incdatawt] = value * ffact; else { data[desc->ilocdata+j*incdatawt] = fblank; } } /* end adding to reference beam position */ } /* end loop over array */ data += desc->lrec; /* update buffer pointer */ } /* end loop over buffer */ /* cleanup */ if (xpos) g_free(xpos); if (ypos) g_free(ypos); } /* end ObitOTFUtilModelImageBuff */ /** * Create basic ObitImage structure and fill out descriptor. * Imaging parameters are on the inOTF info member. * \li "nx" OBIT_int (1,1,1) Dimension of image in RA [no default]. * \li "ny" OBIT_int (1,1,1) Dimension of image in declination[no default] * \li "RA" OBIT_float (1,1,1) Right Ascension of center of image * Default is observed position center in inOTF * \li "Dec" OBIT_float (1,1,1) Declination of center of image * Default is observed position center in inOTF * \li "xCells" OBIT_float (1,1,1) X (=RA) cell spacing in asec [no default] * \li "yCells" OBIT_float (1,1,1) Y (=dec) cell spacing in asec [no default] * \li "Proj" OBIT_string (4,1,1) Projection string "-SIN", "-ARC", "-TAN" * [Default "-SIN"] * \param inOTF Input OTF data. * \param err Error stack, returns if not empty. * \return Pointer to the newly created ObitImage. */ ObitImage* ObitOTFUtilCreateImage (ObitOTF *inOTF, ObitErr *err) { ObitImage *outImage=NULL; gchar outName[121], Proj[8]; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitInfoType type; olong itemp[10], nx, ny; ofloat ftemp[10], xCells, yCells, RA, Dec; gchar *routine = "ObitOTFUtilCreateImage"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return outImage; g_assert (ObitOTFIsA(inOTF)); /* open/close OTF data to fully instantiate if not already open */ if (inOTF->myStatus==OBIT_Inactive) { ObitOTFFullInstantiate (inOTF, TRUE, err); if (err->error) Obit_traceback_val (err, routine, inOTF->name, outImage); } /* Create output */ g_snprintf (outName, 120, "%s",inOTF->name); outImage = newObitImage(outName); /* Get parameters for image */ /* Image size */ itemp[0] = -1; if (!ObitInfoListGetTest(inOTF->info, "nx", &type, dim, itemp)) Obit_log_error(err, OBIT_Error, "%s: %s MUST define nx", routine, inOTF->name); nx = itemp[0]; if (!ObitInfoListGetTest(inOTF->info, "ny", &type, dim, itemp)) Obit_log_error(err, OBIT_Error, "%s: %s MUST define ny", routine, inOTF->name); ny = itemp[0]; /* Cell Spacing */ ftemp[0] = 0.0; if (!ObitInfoListGetTest(inOTF->info, "xCells", &type, dim, ftemp)) Obit_log_error(err, OBIT_Error, "%s: %s MUST define xCells", routine, inOTF->name); xCells = ftemp[0]; if (!ObitInfoListGetTest(inOTF->info, "yCells", &type, dim, ftemp)) Obit_log_error(err, OBIT_Error, "%s: %s MUST define yCells", routine, inOTF->name); yCells = ftemp[0]; /* Center Default is observed position center in inOTF */ ftemp[0] = inOTF->myDesc->obsra; ObitInfoListGetTest(inOTF->info, "RA", &type, dim, ftemp); RA = ftemp[0]; ftemp[0] = inOTF->myDesc->obsdec; ObitInfoListGetTest(inOTF->info, "Dec", &type, dim, ftemp); Dec = ftemp[0]; /* Default projection is -SIN */ Proj[0] = '-'; Proj[1] = 'S'; Proj[2] = 'I'; Proj[3] = 'N'; Proj[4] = 0; ObitInfoListGetTest(inOTF->info, "Proj", &type, dim, (gpointer*)&Proj); Proj[4] = 0; /* bail out if an error so far */ if (err->error) return outImage; /* Set values on descriptor(s) */ outImage->myDesc->xshift = 0.0; outImage->myDesc->yshift = 0.0; outImage->myDesc->crota[0] = 0.0; outImage->myDesc->crota[1] = 0.0; outImage->myDesc->cdelt[0] = xCells / 3600.0; outImage->myDesc->cdelt[1] = yCells / 3600.0; outImage->myDesc->inaxes[0] = nx; outImage->myDesc->inaxes[1] = ny; outImage->myDesc->crval[0] = RA; outImage->myDesc->crval[1] = Dec; /* Fill in descriptor */ ObitOTFUtilOTF2ImageDesc (inOTF->myDesc, outImage->myDesc, Proj); return outImage; } /* end ObitOTFUtilCreateImage */ /** * Convolves data onto a grid, accumulated and normalizes. * Imaging parameters are on the inOTF info member. * \li "ConvType" OBIT_long scalar = Convolving function type: [def=3] * 0 = pillbox, 3 = Gaussian, 4 = Exp*Sinc, 5 = Spherodial wave * \li "ConvParm" OBIT_float[10] = Convolving function parameters * \li "deBias" OBIT_bool scalar = Subtract calibration bias from image? [def False] * Note, this doesn't really work the way you would like * \li "deMode" OBIT_bool scalar = Subtract image mode from image? [def False] * \li "minWt" OBIT_float (1,1,1) Minimum summed gridding convolution weight * as a fraction of the maximum [def 0.01] * \li "doScale" OBIT_bool scalar If true, convolve/scale beam [def TRUE] * \li "doConvBeam" OBIT_bool scalar If true, convolve beam [def FALSE] * \li "doFilter" OBIT_bool scalar If true, filter out of band noise[def TRUE] * \param inOTF Input OTF data. * \param outImage Image to be written. Must be previously instantiated. * \param doBeam If TRUE also make convolved beam. * Will make the myBeam member of outImage. * \param Beam If non NULL use as instrumental response beam * \param Wt If non NULL write weight array to. * \param err Error stack, returns if not empty. */ void ObitOTFUtilMakeImage (ObitOTF *inOTF, ObitImage *outImage, gboolean doBeam, ObitImage *Beam, ObitImage *Wt, ObitErr *err) { ObitIOSize IOBy; gchar *outName=NULL; ObitOTFGrid *myGrid=NULL; ObitFArray *biasArray=NULL; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong blc[IM_MAXDIM] = {1,1,1,1,1}; olong trc[IM_MAXDIM] = {0,0,0,0,0}; ofloat parms[10], xparms[10], mode, radius; olong i, nparms, cType, tcType; gboolean deBias, replCal, tbool, deMode, doFilter; gchar *parmList[] = {"minWt","Clip","beamNx","beamNy","doScale","doConvBeam", NULL}; gchar *routine = "ObitOTFUtilMakeImage"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitOTFIsA(inOTF)); g_assert (ObitImageIsA(outImage)); /* Make Gridding object */ outName = g_strconcat ("OTFGrid for: ", inOTF->name, NULL); myGrid = newObitOTFGrid(outName); g_free(outName); /* Copy control parameters to grid object */ ObitInfoListCopyList (inOTF->info, myGrid->info, parmList); /* Now make image */ /* Set blc, trc */ blc[0] = 1; blc[1] = 1; blc[2] = 1; trc[0] = outImage->myDesc->inaxes[0]; trc[1] = outImage->myDesc->inaxes[0]; trc[2] = 1; IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListPut (outImage->info, "IOBy", OBIT_long, dim, (gpointer)&IOBy, err); dim[0] = 7; ObitInfoListPut (outImage->info, "BLC", OBIT_long, dim, (gpointer)blc, err); ObitInfoListPut (outImage->info, "TRC", OBIT_long, dim, (gpointer)trc, err); /* Open image to get descriptor */ if ((ObitImageOpen (outImage, OBIT_IO_WriteOnly, err) != OBIT_IO_OK) || (err->error>0)) Obit_log_error(err, OBIT_Error, "ERROR opening image %s", outImage->name); if (err->error) return; /* reset max, min */ outImage->myDesc->minval = 1.0e20; outImage->myDesc->maxval = -1.0e20; ((ObitImageDesc*)outImage->myIO->myDesc)->minval = 1.0e20; ((ObitImageDesc*)outImage->myIO->myDesc)->maxval = -1.0e20; /* Gaussian beam */ outImage->myDesc->beamMaj = inOTF->myDesc->beamSize; outImage->myDesc->beamMin = inOTF->myDesc->beamSize; outImage->myDesc->beamPA = 0.0; /* Gridding setup */ ObitOTFGridSetup (myGrid, inOTF, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Beam if requested */ if (doBeam) ObitOTFGridMakeBeam (myGrid, outImage, Beam, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Grid */ ObitOTFGridReadOTF (myGrid, inOTF, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Normalize */ ObitOTFGridNorm(myGrid, outImage->image, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* reset beam size on IO descriptor for the effects of convolution */ ((ObitImageDesc*)outImage->myIO->myDesc)->beamMaj = outImage->myDesc->beamMaj; ((ObitImageDesc*)outImage->myIO->myDesc)->beamMin = outImage->myDesc->beamMin; /* Remove image Mode */ deMode = FALSE; ObitInfoListGetTest(inOTF->info, "deMode", &type, dim, &deMode); if (deMode) { /* remove mode of image */ mode = ObitFArrayMode(outImage->image); ObitFArraySAdd(outImage->image, -mode); /* Message */ Obit_log_error(err, OBIT_InfoErr, "Subtract image Mode %g",mode); } /* Debias? */ deBias = FALSE; ObitInfoListGetTest(inOTF->info, "deBias", &type, dim, &deBias); if (deBias) { /* Save image array */ biasArray = ObitFArrayCopy (outImage->image, biasArray, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* This time replace data with cal value */ replCal = FALSE; ObitInfoListGetTest(inOTF->info, "replCal", &type, dim, &replCal); tbool = TRUE; ObitInfoListAlwaysPut(inOTF->info, "replCal", OBIT_bool, dim, &tbool); /* Use large Gaussian convolving fn twice beam size*/ cType = 3; ObitInfoListGetTest(inOTF->info, "ConvType", &type, dim, &cType); tcType = 3; ObitInfoListAlwaysPut(inOTF->info, "ConvType", OBIT_long, dim, &tcType); for (i=0; i<10; i++) parms[i] = 0.0; /* Default 0.0 */ dim[0] = 1; ObitInfoListGetTest(inOTF->info, "ConvParm", &type, dim, parms); nparms = dim[0]; for (i=0; i<10; i++) xparms[i] = parms[i]; xparms[0] = 7.0; xparms[1] = 2.0; ObitInfoListAlwaysPut(inOTF->info, "ConvParm", OBIT_float, dim, xparms); /* Gridding setup */ ObitOTFGridSetup (myGrid, inOTF, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* reGrid */ ObitOTFGridReadOTF (myGrid, inOTF, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Normalize bias image */ ObitOTFGridNorm(myGrid, outImage->image, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Subtract bias image array */ ObitFArraySub(biasArray, outImage->image, outImage->image); /* remove mode of image */ mode = ObitFArrayMode(outImage->image); ObitFArraySAdd(outImage->image, -mode); /* Restore the state of things */ dim[0] = 1; ObitInfoListAlwaysPut(inOTF->info, "replCal", OBIT_bool, dim, &replCal); ObitInfoListAlwaysPut(inOTF->info, "ConvType", OBIT_long, dim, &cType); dim[0] = nparms; ObitInfoListAlwaysPut(inOTF->info, "ConvParm", OBIT_float, dim, parms); if (biasArray) ObitFArrayUnref(biasArray); } /* end debias */ /* Write image */ ObitImageWrite (outImage, NULL, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* tell Max/Min */ Obit_log_error(err, OBIT_InfoErr, "Image max %g, min %g for %s", outImage->myDesc->maxval, outImage->myDesc->minval, outImage->name); /* Close Image */ ObitImageClose (outImage, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* Filter if requested */ doFilter = TRUE; ObitInfoListGetTest(inOTF->info, "doFilter", &type, dim, &doFilter); radius = 0.5 * inOTF->myDesc->diameter; if (radius<=0.0) radius = 50.0; /* Default = GBT */ /* radius *= 0.25;Factor of two squared somewhere? */ radius *= 0.5;/* Factor of two somewhere? */ if (doFilter) { Obit_log_error(err, OBIT_InfoErr, "Filtering out of band noise for for %s", outImage->name); ObitImageUtilUVFilter(outImage, outImage, radius, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); } /* Save Weight image? */ if (Wt!=NULL) { ObitImageClone (outImage, Wt, err); /* Looks like outImage */ ObitImageOpen (Wt, OBIT_IO_WriteOnly, err); /* reset max, min */ Wt->myDesc->minval = 1.0e20; Wt->myDesc->maxval = -1.0e20; ((ObitImageDesc*)Wt->myIO->myDesc)->minval = 1.0e20; ((ObitImageDesc*)Wt->myIO->myDesc)->maxval = -1.0e20; ObitImageWrite (Wt, myGrid->gridWt->array, err); ObitImageClose (Wt, err); if (err->error) Obit_traceback_msg (err, routine, Wt->name); } /* Free myGrid */ myGrid = ObitOTFGridUnref(myGrid); } /* end ObitOTFUtilMakeImage */ /** * Reads the OTF and rewrites its OTFIndex table * \param inOTF Input OTF data. * \param err Error stack, returns if not empty. */ void ObitOTFUtilIndex (ObitOTF *inOTF, ObitErr *err) { ObitIOCode retCode; ObitTableOTFIndex* table; ObitTableOTFIndexRow* row; olong num, i, lrec, iRow, ver, lastscan, iscan, target, lastTarget=0, startRec=1, curRec; ofloat *rec; odouble startTime=0.0, endTime=0.0; gchar *routine = "ObitOTFUtilIndex"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitOTFIsA(inOTF)); /* Open OTF */ retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadWrite, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inOTF->name); lrec = inOTF->myDesc->lrec; /* Size of record */ lastscan = -1000; /* initialize scan number */ curRec = 0; /* record counter */ /* create Index table object */ ver = 1; table = newObitTableOTFIndexValue ("Index table", (ObitData*)inOTF, &ver, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); /* Open Index table */ if ((ObitTableOTFIndexOpen (table, OBIT_IO_ReadWrite, err) != OBIT_IO_OK) || (err->error)) { /* error test */ Obit_log_error(err, OBIT_Error, "ERROR opening output OTFIndex table"); return; } /* Create Index Row */ row = newObitTableOTFIndexRow (table); /* initialize row */ row->ScanID = 0; row->TargetID = 0; row->Time = 0.0; row->TimeI = 0.0; row->StartRec = -1; row->EndRec = -1; /* attach to table buffer */ ObitTableOTFIndexSetRow (table, row, err); if (err->error) Obit_traceback_msg (err, routine, inOTF->name); /* Write at beginning of OTFIndex Table */ iRow = 0; table->myDesc->nrow = 0; /* ignore any previous entries */ /* Loop over OTF */ while (retCode==OBIT_IO_OK) { retCode = ObitOTFRead (inOTF, inOTF->buffer, err); if (retCode!=OBIT_IO_OK) break; /* How many */ num = inOTF->myDesc->numRecBuff; /* Record pointer */ rec = inOTF->buffer; /* initialize on first record */ if (curRec<=0) { startRec = 1; startTime = rec[inOTF->myDesc->iloct]; } /* Loop over buffer */ for (i=0; i<num; i++) { iscan = rec[inOTF->myDesc->ilocscan] + 0.5; /* Which scan number */ target = rec[inOTF->myDesc->iloctar] + 0.5; /* Target number */ curRec++; /* Current OTF record number */ /* Initialize? */ if (lastscan<=0) lastscan = iscan; if (lastTarget<=0) lastTarget = target; /* New scan? */ if ((iscan!=lastscan) && (lastscan>0)) { /* Write index */ /* Record values */ row->ScanID = lastscan; row->TargetID = lastTarget; row->Time = 0.5 * (startTime + endTime); row->TimeI = (endTime - startTime); row->StartRec = startRec; row->EndRec = curRec-1; /* Write OTFIndex table */ iRow++; if ((ObitTableOTFIndexWriteRow (table, iRow, row, err) != OBIT_IO_OK) || (err->error>0)) { Obit_log_error(err, OBIT_Error, "ERROR writing OTFIndex Table file"); return; } /* Initialize next scan */ lastscan = iscan; lastTarget = target; startRec = curRec; startTime = rec[inOTF->myDesc->iloct]; endTime = rec[inOTF->myDesc->iloct]; } /* end of if new scan */ endTime = rec[inOTF->myDesc->iloct]; /* potential end time */ rec += inOTF->myDesc->lrec; /* Update data record pointer */ } /* end loop over buffer */ } /* End loop over OTF */ /* Last Scan */ /* Record values */ row->ScanID = lastscan; row->TargetID = lastTarget; row->Time = 0.5 * (startTime + endTime); row->TimeI = (endTime - startTime); row->StartRec = startRec; row->EndRec = curRec-1; /* Write OTFIndex table */ iRow++; if ((ObitTableOTFIndexWriteRow (table, iRow, row, err) != OBIT_IO_OK) || (err->error>0)) { Obit_log_error(err, OBIT_Error, "ERROR writing OTFIndex Table file"); return; } /* Close OTFIndex table */ if ((ObitTableOTFIndexClose (table, err) != OBIT_IO_OK) || (err->error>0)) { /* error test */ Obit_log_error(err, OBIT_Error, "ERROR closing output OTFIndex Table file"); return; } /* Cleanup */ row = ObitTableOTFIndexRowUnref(row); table = ObitTableOTFIndexUnref(table); /* Close OTF */ retCode = ObitOTFClose (inOTF, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inOTF->name); } /* end ObitOTFUtilIndex */ /** * Differences the Ons and Offs in a beamswitched nodding scan * Output values on inOTF * \li "OnOff" OBIT_float (*,1,1) Differences of On-Off for each detector * in the same order as defined in the data. For beamswitched * data this will be twice the source strength. * \param inOTF Input OTF data. Applies any calibration specified * Target position must be in OTFTarget table. * \param scan Scan number * \param err Error stack, returns if not empty. */ void ObitOTFUtilDiffNod (ObitOTF *inOTF, olong scan, ObitErr *err) { ObitIOCode retCode; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitTableOTFTarget* targetTable=NULL; ofloat *avgOff=NULL, *avgOn=NULL, *feedRA=NULL, *feedDec=NULL; olong *cntOn=NULL, *cntOff=NULL; olong i, state, ndetect, incfeed, itemp, iDet; olong scans[2], doCal, incdatawt, targID=0; olong ver; gboolean doCalSelect, isCal, isRef, gotTarinfo=FALSE; odouble RACal, DecCal, dra, ddec, val; ofloat *rec, FluxCal, fblank = ObitMagicF(); gchar *routine = "ObitOTFUtilDiffNod"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitOTFIsA(inOTF)); /* How many detectors? */ ndetect = inOTF->geom->numberDetect; /* Create arrays */ avgOff = g_malloc0(ndetect*sizeof(ofloat)); avgOn = g_malloc0(ndetect*sizeof(ofloat)); cntOff = g_malloc0(ndetect*sizeof(olong)); cntOn = g_malloc0(ndetect*sizeof(olong)); feedRA = g_malloc(ndetect*sizeof(ofloat)); feedDec = g_malloc(ndetect*sizeof(ofloat)); for (i=0; i<ndetect; i++) avgOff[i] = avgOn[i] = 0.0; for (i=0; i<ndetect; i++) cntOff[i] = cntOn[i] = 0; /* Select scan on input */ doCalSelect = TRUE; dim[0] = 1; ObitInfoListAlwaysPut(inOTF->info, "doCalSelect", OBIT_bool, dim, &doCalSelect); doCal = 1; ObitInfoListAlwaysPut(inOTF->info, "doCalib", OBIT_bool, dim, &doCal); scans[0] = scan; scans[1] = scan; dim[0] = 2; ObitInfoListAlwaysPut(inOTF->info, "Scans", OBIT_long, dim, scans); incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */ /* open OTF data to fully instantiate */ retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadCal, err); if (err->error) goto cleanup; /* loop reading data */ retCode = OBIT_IO_OK; while (retCode == OBIT_IO_OK) { /* read buffer */ retCode = ObitOTFReadSelect (inOTF, NULL, err); if (err->error) goto cleanup; if (retCode==OBIT_IO_EOF) break; /* done? */ /* Record pointer */ rec = inOTF->buffer; /* Feed increment in data */ if (inOTF->myDesc->jlocfeed>=0) incfeed = inOTF->myDesc->incfeed / inOTF->myDesc->incdatawt; else incfeed = 1; /* This is probably a bad sign */ /* Loop over buffer */ for (i=0; i<inOTF->myDesc->numRecBuff; i++) { /* Get source info on first record */ if (!gotTarinfo) { gotTarinfo = TRUE; /* Get position from table */ ver = 1; targID = (olong)rec[inOTF->myDesc->iloctar]; targetTable = newObitTableOTFTargetValue ("TargetTable", (ObitData*)inOTF, &ver, OBIT_IO_ReadWrite, err); ObitTableOTFTargetGetSource (targetTable, targID, &RACal, &DecCal, &FluxCal, err); targetTable = ObitTableOTFTargetUnref(targetTable); if (err->error) goto cleanup; /* Make sure there is something */ if ((RACal==0.0) || (DecCal==0.0)) { Obit_log_error(err, OBIT_Error, "%s: MISSING Calibrator info for %d %lf %lf in %s", routine, targID, RACal, DecCal, inOTF->name); goto cleanup; } } /* End of get target info & create arrays */ /* Get feed positions */ ObitOTFArrayGeomCoord (inOTF->geom, rec[inOTF->myDesc->ilocra], rec[inOTF->myDesc->ilocdec], rec[inOTF->myDesc->ilocrot], feedRA, feedDec); /* Three states here, sig beam on source (state=1), ref beam on source (state=-1) or neither (state=0) */ state = 0; /* Close to sig beam? */ itemp = 0; dra = feedRA[itemp] - RACal; ddec = feedDec[itemp] - DecCal; if (sqrt(dra*dra+ddec*ddec) < 0.3*inOTF->myDesc->beamSize) state = 1; if (!state) { /* Close to reference beam? */ itemp = inOTF->myDesc->incfeed; dra = feedRA[itemp] - RACal; ddec = feedDec[itemp] - DecCal; if (sqrt(dra*dra+ddec*ddec) < 0.3*inOTF->myDesc->beamSize) state = -1; } /* sum values if on sig or ref position and cal off */ isCal = rec[inOTF->myDesc->iloccal]!=0.0; /* Cal on? */ if ((!isCal) && (state!=0)) { for (iDet=0; iDet<=ndetect; iDet++) { val = rec[inOTF->myDesc->ilocdata+iDet*incdatawt]; if (val==fblank) continue; /* Is this a sig or ref beam */ itemp = iDet / incfeed; /* itemp odd is reference beam */ isRef = itemp != 2*(itemp/2); if (isRef) { /* reference beam */ if (state<0) {avgOn[iDet] += val; cntOn[iDet]++;} else if (state>0) {avgOff[iDet] += val; cntOff[iDet]++;} } else { /* signal beam */ if (state>0) {avgOn[iDet] += val; cntOn[iDet]++;} else if (state<0) {avgOff[iDet] += val; cntOff[iDet]++;} } } } rec += inOTF->myDesc->lrec; /* Data record pointer */ } /* end loop over buffer load */ } /* end loop reading data */ /* Close data */ retCode = ObitOTFClose (inOTF, err); if (err->error) goto cleanup; /* Get On-Off */ for (i=0; i<ndetect; i++) { /* Average */ if (cntOn[i]>0) avgOn[i] /= cntOn[i]; else avgOn[i] = fblank; if (cntOff[i]>0) avgOff[i] /= cntOff[i]; else avgOff[i] = fblank; if ((avgOff[i]!=fblank) && (avgOn[i]!=fblank)) { avgOn[i] = (avgOn[i] - avgOff[i]); } else { avgOn[i] = fblank; } } /* end loop over detectors */ /* Save values on inOTF */ dim[0] = ndetect; dim[1] = 1; ObitInfoListPut (inOTF->info, "OnOff", OBIT_float, dim, avgOn, err); /* Cleanup */ cleanup: if (avgOn) g_free(avgOn); if (avgOff) g_free(avgOff); if (cntOn) g_free(cntOn); if (cntOff) g_free(cntOff); if (feedRA) g_free(feedRA); if (feedDec) g_free(feedDec); } /* end ObitOTFUtilDiffNod */ /** * Create an image and fill the descriptor values for an image cube * based on the descriptor for a single plane and for the uv data * creating the image. * This should be called before the image is Opened or instantiated. * \param inDesc Input Image Descriptor. * \param UVDesc Input UV Descriptor. * \param outDesc Output Image Descriptor * \param Stokes Stokes parameter of image ' '=>'I', (I, Q, U, V, R, L) * \param bchan first (1-rel) channel in UVDesc * \param echan highest (1-rel) channel in UVDesc * \param incr channel increment in input * \param nchavg How many uv channels to average per image channel. * Ignored if uv data has multiple IFs. */ void ObitOTFUtilMakeCube (ObitImageDesc *inDesc, ObitOTFDesc *OTFDesc, ObitImageDesc *outDesc, gchar *Stokes, olong bchan, olong echan, olong incr, ObitErr *err) { olong numberChann; gchar *name; gchar *routine = "ObitOTFUtilMakeCube"; /* error checks */ g_assert(ObitErrIsA(err)); if (err->error) return; g_assert (ObitImageDescIsA(inDesc)); g_assert (ObitOTFDescIsA(OTFDesc)); /* Save output name */ if (outDesc->name) name = g_strdup (outDesc->name); else name = g_strdup ("Descriptor"); /* Most info from inDesc */ outDesc = ObitImageDescCopy (inDesc, outDesc, err); if (err->error) Obit_traceback_msg (err, routine, inDesc->name); /* restore name */ if (outDesc->name) g_free(outDesc->name); outDesc->name = name; /* Set number of channels */ numberChann = MIN (echan, OTFDesc->inaxes[OTFDesc->jlocf]) - MAX (1, bchan) + 1; outDesc->inaxes[outDesc->jlocf] = MAX (1, numberChann / MAX (1, incr)); /* Stokes parameter */ if ((Stokes[0]=='I') || (Stokes[0]==' ')) outDesc->crval[outDesc->jlocs] = 1.0; else if (Stokes[0]=='Q') outDesc->crval[outDesc->jlocs] = 2.0; else if (Stokes[0]=='U') outDesc->crval[outDesc->jlocs] = 3.0; else if (Stokes[0]=='V') outDesc->crval[outDesc->jlocs] = 4.0; else if (Stokes[0]=='R') outDesc->crval[outDesc->jlocs] = -1.0; else if (Stokes[0]=='L') outDesc->crval[outDesc->jlocs] = -1.0; /* reset image max/min */ outDesc->maxval = -1.0e20; outDesc->minval = 1.0e20; return; } /* end ObitOTFUtilMakeCube */ /** * Convolve a set of Clean components with a beam image * \param CCTab CC Table, following parameters on infoList * \li "BComp" OBIT_int (1,1,1) Start CC to use, 1-rel [def 1 ] * \li "EComp" OBIT_int (1,1,1) Highest CC to use, 1-rel [def to end ] * \param Beam Beam image to convolve with CCs * \param Template Template for output array * \param err Obit Error stack * \return An ObitFArray whose size is that of Template, spacing is that of Beam * with the CCs in CCTab convolved with Beam and the (0,0) position is * (nx/2,ny/2) (0-rel) */ ObitFArray* ObitOTFUtilConvBeam (ObitTableCC *CCTab, ObitImage *Beam, ObitFArray *Template, ObitErr *err) { ObitFArray *out = NULL; ObitFArray *beamArray = NULL; olong iRow; ObitIOSize IOsize = OBIT_IO_byPlane; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong *iptr, bcomp, ecomp; olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1}; olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0}; olong pos[2], loop, beamCen[2], nrow, nx, ny, xcen, ycen; ofloat xdelt, ydelt; ObitTableCCRow *row=NULL; gchar *routine = "ObitOTFUtilConvBeam"; /* error checks */ if (err->error) return out; g_assert (ObitTableCCIsA(CCTab)); g_assert (ObitImageIsA(Beam)); g_assert (ObitFArrayIsA(Template)); /* Make output array */ out = ObitFArrayCreate(routine, Template->ndim, Template->naxis); /* Size and center */ nx = (olong)Template->naxis[0]; xcen = nx/2; ny = (olong)Template->naxis[1]; ycen = ny/2; /* Range of CCs - start CC number */ if (ObitInfoListGetP(CCTab->info, "BComp", &type, dim, (gpointer)&iptr)) { bcomp = iptr[0]; } else bcomp = 1; /* End CC number */ if (ObitInfoListGetP(CCTab->info, "EComp", &type, dim, (gpointer)&iptr)) { ecomp = iptr[0]; } else ecomp = 0; /* Read beam image - Full field */ dim[0] = IM_MAXDIM; ObitInfoListPut (Beam->info, "BLC", OBIT_long, dim, blc, err); ObitInfoListPut (Beam->info, "TRC", OBIT_long, dim, trc, err); dim[0] = 1; ObitInfoListPut (Beam->info, "IOBy", OBIT_long, dim, &IOsize, err); Beam->extBuffer = FALSE; ObitImageOpen (Beam, OBIT_IO_ReadOnly, err); ObitImageRead (Beam, NULL, err); ObitImageClose (Beam, err); if (err->error) Obit_traceback_val (err, routine, Beam->name, out); beamArray = Beam->image; /* FArray with beam */ beamCen[0] = (olong)(Beam->myDesc->crpix[0] + 0.5); beamCen[1] = (olong)(Beam->myDesc->crpix[1] + 0.5); xdelt = 1.0 / Beam->myDesc->cdelt[0]; ydelt = 1.0 / Beam->myDesc->cdelt[1]; /* Open CC table */ ObitTableCCOpen (CCTab, OBIT_IO_ReadOnly, err); if (err->error) Obit_traceback_val (err, routine, Beam->name, out); row = newObitTableCCRow(CCTab); /* Restoration loop */ nrow = CCTab->myDesc->nrow; if (ecomp<1) ecomp = nrow; Obit_log_error(err, OBIT_InfoErr, "%s: Using %d components", routine, ecomp-bcomp+1); for (loop=bcomp; loop<=ecomp; loop++) { /* Read CC table */ iRow = loop; ObitTableCCReadRow (CCTab, iRow, row, err); if (err->error) Obit_traceback_val (err, routine, CCTab->name, out); /* Restore to residual */ pos[0] = (olong)(xcen + (row->DeltaX * xdelt) + 1.5); pos[1] = (olong)(ycen + (row->DeltaY * ydelt) + 1.5); ObitFArrayShiftAdd (out, pos, beamArray, beamCen, row->Flux, out); } /* End Restoration loop */ /* Close CC table */ ObitTableCCClose (CCTab, err); if (err->error) Obit_traceback_val (err, routine, CCTab->name, out); Beam->image = ObitFArrayUnref(Beam->image); /* Cleanup */ row = ObitTableCCRowUnref(row); return out; } /* end ObitOTFUtilConvBeam */ /** * Determine an OTFSoln residual calibration table * If a model is given, a residual timestream data set is generated * by subtracting the model from the input data to a scratch file. * The scratch file (or input if no model given) is low pass filtered to * generate the solution table. * Calibration parameters are on the inOTF info member. * \li "calType" OBIT_string (*,1,1) Calibration type desired * "Both" => Detector offsets (per scan/maxInt) and common mode poly * "Common" => common mode poly * "Offset" Detector offsets * "Gain" => Gain (multiplicative, cal) solution only * "Offset" => Offset (additive) solution only * "GainOffset" both gain and offset calibration (probably bad idea). * "Filter" detector offsets from FFT low pass filter * \li "minResFlx" OBIT_float (1,1,1) Min. model value, [ def -1.0e20] * \li "maxResFlx" OBIT_float (1,1,1) Max. model value [def 1.0e20] * \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 1 sec]. * \li "maxInt" OBIT_float (1,1,1) max. Interval in days [def 10 min]. * Scans longer than this will be broken into pieces, * for offset determination in calType "Both" only. * \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg) * \li "Clip" OBIT_float (1,1,1) data outside of range +/- Clip are replaced by * + or - Clip. [Def 1.0e20] * \li "doScale" OBIT_bool scalar If true, convolve/scale beam [def TRUE] * \param inOTF Input OTF data. * \param outOTF OTF with which the output OTFSoln is to be associated * \param model If given the image to use as a model * \param doCC If true use CC model, else pixels [def FALSE] * \param PSF PSF of instrument to use in generating model from CC table * \param err Error stack, returns if not empty. * \return Pointer to the newly created OTFSoln object which is * associated with outOTF. */ ObitTableOTFSoln* ObitOTFUtilResidCal (ObitOTF *inOTF, ObitOTF *outOTF, ObitImage *model, gboolean doModel, ObitImage *PSF, ObitErr *err) { ObitTableOTFSoln *outSoln=NULL; ObitOTF *residOTF=NULL; ObitTableCC *CCTab=NULL; ObitFArray *modPix; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitInfoType type; ObitIOAccess access; gboolean doCalSelect; gchar calType[50]; olong i, ver, noParms; ofloat maxResFlx, minResFlx; gchar *SolnParms[] = { /* Solution parameters */ "calType", "solInt", "maxInt", "minEl", "clipSig", "doScale", NULL }; gchar *routine = "ObitOTFUtilResidCal"; /* error checks */ if (err->error) return outSoln; g_assert (ObitOTFIsA(inOTF)); /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Control parameters */ minResFlx = -1.0e20; ObitInfoListGetTest(inOTF->info, "minResFlx", &type, dim, &minResFlx); maxResFlx = 1.0e20; ObitInfoListGetTest(inOTF->info, "maxResFlx", &type, dim, &maxResFlx); /* calibration type */ for (i=0; i<50; i++) calType[i] = 0; strcpy (calType, "Both"); ObitInfoListGetTest(inOTF->info, "calType", &type, dim, calType); /* Using model? */ if (model) { /* Have model */ residOTF = newObitOTFScratch(inOTF, err); /* Scratch file for residual */ /* Read model Image */ ObitImageOpen (model, OBIT_IO_ReadOnly, err); ObitImageRead (model, NULL, err); modPix = model->image; ObitImageClose (model, err); if (err->error) Obit_traceback_val (err, routine, model->name, outSoln); /* Replace pixels with CC model? */ if (doModel) { /* Get CC table */ noParms = 0; ver = 1; CCTab = newObitTableCCValue ("Temp CC", (ObitData*)model, &ver, OBIT_IO_ReadOnly, noParms, err); if (err->error) Obit_traceback_val (err, routine, model->name, outSoln); modPix = ObitOTFUtilConvBeam (CCTab, PSF, model->image, err); if (err->error) Obit_traceback_val (err, routine, model->name, outSoln); CCTab = ObitTableCCUnref(CCTab); } else { modPix = ObitFArrayRef(model->image); } /* Clip model */ if ((minResFlx>-1.0e19) || (minResFlx<1.0e19)) { ObitFArrayClip (modPix, -1.0e20, maxResFlx, maxResFlx); ObitFArrayClip (modPix, minResFlx, 1.0e20, minResFlx); Obit_log_error(err, OBIT_InfoErr, "Clip model to range %12.4g %12.4g", minResFlx, maxResFlx); } /* Subtract to form residuals */ ObitOTFUtilSubImage (inOTF, residOTF, modPix, model->myDesc, err); if (err->error) Obit_traceback_val (err, routine, model->name, outSoln); /* Copy soln parameters to residOTF */ ObitInfoListCopyList (inOTF->info, residOTF->info, SolnParms); /* DEBUG write as FITS ObitImageUtilFArray2FITS(modPix, "ModelImage.fits", 0, model->myDesc, err);*/ /* Cleanup */ modPix = ObitUnref(modPix); model->image = ObitUnref(model->image); } else { /* no model */ residOTF = ObitOTFRef(inOTF); } /* Do solutions */ if (!strncmp(calType, "Common",4)) outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err); else if (!strncmp(calType, "Offset",6)) outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err); else if (!strncmp(calType, "Both",10)) outSoln = ObitOTFGetSolnMBBase (residOTF, outOTF, err); else if (!strncmp(calType, "Gain",10)) outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err); else if (!strncmp(calType, "Offset",10)) outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err); else if (!strncmp(calType, "GainOffset",10)) outSoln = ObitOTFGetSolnGain (residOTF, outOTF, err); else if (!strncmp(calType, "Filter",10)) outSoln = ObitOTFGetSolnCal (residOTF, outOTF, err); if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln); /* Cleanup */ residOTF = ObitOTFUnref(residOTF); return outSoln; } /* end ObitOTFUtilResidCal */ /*----------------------Private functions---------------------------*/ /** * Fill in an image Descriptor from a OTF Descriptor. * Needs size, cell spacing and center filled in * Information about the first two axes other than the type an * coordinate value need to be set separately. * to get the final position correct. * \param OTFDesc Input OTF Descriptor. * \param imageDesc Output image Descriptor * \param Proj Projection code. */ static void ObitOTFUtilOTF2ImageDesc(ObitOTFDesc *OTFDesc, ObitImageDesc *imageDesc, gchar *Proj) { olong i, iaxis; gchar *st1; /* error checks */ g_assert (ObitOTFDescIsA(OTFDesc)); g_assert (ObitImageDescIsA(imageDesc)); /* Be sure OTF descriptor is indexed */ ObitOTFDescIndex(OTFDesc); /* loop over axes */ iaxis = 0; /* RA axis, pos, inaxes, cdelt, crota, xshift set else where */ /* Form label string */ st1 = imageDesc->ctype[iaxis]; st1[0] = 'R'; st1[1] = 'A'; st1[2] = '-'; st1[3] = '-'; for (i=0; i<4; i++) st1[i+4]=Proj[i]; st1[9] = 0; /* Reference pixel */ imageDesc->crpix[iaxis] = 1.0 + imageDesc->inaxes[iaxis] / 2.0; /* Dec axis, pos, inaxes, cdelt, crota, xshift set else where */ iaxis++; /* Form label string */ st1 = imageDesc->ctype[iaxis]; st1[0] = 'D'; st1[1] = 'E'; st1[2] = 'C'; st1[3] = '-'; for (i=0; i<4; i++) st1[i+4]=Proj[i]; st1[9] = 0; /* Reference pixel */ imageDesc->crpix[iaxis] = 1.0 + imageDesc->inaxes[iaxis] / 2.0; /* Frequency Axis */ iaxis++; /* Initially set for continuum */ strncpy (imageDesc->ctype[iaxis], "FREQ ", IMLEN_KEYWORD-1); imageDesc->inaxes[iaxis] = 1; /* Only one for continuum */ imageDesc->crpix[iaxis] = 1.0; /* reference pixel */ imageDesc->crota[iaxis] = 0.0; /* no possible meaning */ imageDesc->cdelt[iaxis] = OTFDesc->cdelt[OTFDesc->jlocf]; if (OTFDesc->jlocf>=0) imageDesc->crval[iaxis] = OTFDesc->crval[OTFDesc->jlocf]; else imageDesc->crval[iaxis] = 1.0e9; /* unknown frequency */ /* Stokes Axis */ iaxis++; imageDesc->inaxes[iaxis] = 1; /* Only one */ strncpy (imageDesc->ctype[iaxis], "STOKES ", IMLEN_KEYWORD-1); imageDesc->crval[iaxis] = 1.0; imageDesc->crpix[iaxis] = 1.0; /* reference pixel */ imageDesc->cdelt[iaxis] = 1.0; /* coordinate increment */ imageDesc->crota[iaxis] = 0.0; /* no possible meaning */ /* Total number of axes */ imageDesc->naxis = iaxis+1; /* Copy information not directly related to an axis */ /* Strings */ strncpy (imageDesc->object, OTFDesc->object, IMLEN_VALUE-1); strncpy (imageDesc->teles, OTFDesc->teles, IMLEN_VALUE-1); strncpy (imageDesc->origin, OTFDesc->origin, IMLEN_VALUE-1); strncpy (imageDesc->bunit, "JY/BEAM ", IMLEN_VALUE-1); /* Set current date */ ObitOTFUtilCurDate (imageDesc->date, IMLEN_VALUE-1); /* Observing date */ if (OTFDesc->JDObs>1.0) ObitOTFDescJD2Date (OTFDesc->JDObs, imageDesc->obsdat); imageDesc->epoch = OTFDesc->epoch; imageDesc->obsra = OTFDesc->obsra; imageDesc->obsdec = OTFDesc->obsdec; /* initialize some values */ imageDesc->areBlanks = FALSE; imageDesc->niter = 0; imageDesc->maxval = -1.0e20; imageDesc->minval = 1.0e20; imageDesc->bitpix = -32; imageDesc->beamMaj = OTFDesc->beamSize; imageDesc->beamMin = OTFDesc->beamSize; imageDesc->beamPA = 0.0; /* Index Image descriptor */ ObitImageDescIndex(imageDesc); } /* end ObitOTFUtilOTF2ImageDesc */ /** * Fills an existing character array with the string for the current date. * \param date Character string to accept the string (10 char+null) * \param len Actual length of date (should be at least 11) */ static void ObitOTFUtilCurDate (gchar *date, olong len) { struct tm *lp; time_t clock; /* Get time since 00:00:00 GMT, Jan. 1, 1970 in seconds. */ time (&clock); /* Convert to broken-down time. */ lp = localtime (&clock); /* Full year */ if (lp->tm_year<1000) lp->tm_year += 1900; lp->tm_mon++; /* Month 0-rel rest 1-rel */ /* to output */ g_snprintf (date, len, "%4.4d-%2.2d-%2.2d", lp->tm_year, lp->tm_mon, lp->tm_mday); } /* end ObitOTFUtilCurDate */ /** * Subtract the values in an image from a portion of a buffer of OTF data. * For CCB beamswitched data (OTFType=OBIT_GBTOTF_CCB, no. States=1) * Callable as thread * Arguments are given in the structure passed as arg * \param arg Pointer to SubImageFuncArg argument with elements: * \li sky OTFSkyModel * \li otfdata OTF data set to model and subtract from current buffer * \li first First (1-rel) rec in otfdata buffer to process this thread * \li last Highest (1-rel) rec inotfdata buffer to process this thread * \li ithread thread number, >0 -> no threading * \li err Obit error stack object. * \li factor Scaling factor for sky model * \li Interp Image Interpolator * \li xpos, ypos, float arrays the size of ndetect * \return NULL */ gpointer ThreadOTFUtilSubImageBuff (gpointer args) { SubImageFuncArg *largs = (SubImageFuncArg*)args; ObitOTF *in = largs->otfdata; olong loRec = largs->first-1; olong hiRec = largs->last; ofloat factor = largs->factor; ObitFInterpolate *image = largs->Interp; ofloat *xpos = largs->xpos; ofloat *ypos = largs->ypos; ObitErr *err = largs->err; ofloat *data, ffact, value, RACenter, DecCenter; ObitOTFProj proj; odouble coord[IM_MAXDIM]; olong ndetect, ndata, i, j; olong incfeed, itemp,incdatawt ; gboolean CCBBS, isRef; ObitOTFDesc* desc; ObitOTFArrayGeom* geom; ofloat fblank = ObitMagicF(); gchar Proj[5]; /* Error checks */ if (err->error) goto finish; /* Local pointers */ desc = in->myDesc; geom = in->geom; data = in->buffer+loRec*desc->lrec; /* Appropriate offset in buffer */ ndetect = geom->numberDetect; /* How many detectors */ ndata = desc->numRecBuff; /* How many data records */ if (in->myDesc->jlocfeed>=0) incfeed = in->myDesc->incfeed / in->myDesc->incdatawt; else incfeed = 1; /* This is probably a bad sign */ /* Get Model center */ RACenter = image->myDesc->crval[0]; DecCenter = image->myDesc->crval[1]; strncpy (Proj, &image->myDesc->ctype[0][4], 5); proj = ObitOTFSkyModelProj (Proj); incdatawt = desc->incdatawt; /* increment in data-wt axis */ /* Is this CCB beamswitched data? */ CCBBS = (in->myDesc->OTFType==OBIT_GBTOTF_CCB) && (in->myDesc->jlocstate>=0) && (in->myDesc->inaxes[in->myDesc->jlocstate]==1); ffact = factor; /* Loop over data records */ for (i=loRec; i<hiRec; i++) { /* Get Sky locations of the data projected onto the image */ ObitOTFArrayGeomProj(geom, data[desc->ilocra], data[desc->ilocdec], data[desc->ilocrot], RACenter, DecCenter, proj, xpos, ypos); /* Loop over the array */ for (j=0; j<ndetect; j++) { /* Interpolate - use coordinates on a flat plane at the tangent point of the image xpos and ypos are offsets from the image center projected onto the plane of the image, ObitFInterpolateOffset does a linear approximation. */ coord[0] = xpos[j]; /* + RACenter; */ coord[1] = ypos[j]; /* + DecCenter; */ value = ObitFInterpolateOffset (image, coord, err); /* debug if ((fabs(data[desc->ilocdata+j]-value*ffact)>1.0) && (j<=3)) { fprintf (stderr,"debugSig: val %g pos %lf %lf in data %f %f pos %f %f\n", value, coord[0]*3600.0, coord[1]*3600.0, data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]-value*ffact), data[desc->ilocra], data[desc->ilocdec]); } */ /* debug if ((fabs(coord[0])<0.0014) && (fabs(coord[1])<0.0014) && (j<=3)) { fprintf (stderr,"debugSig: val %g pos %lf %lf in data %f %f pos %f %f\n", value, coord[0]*3600.0, coord[1]*3600.0, data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]-value*ffact), data[desc->ilocra], data[desc->ilocdec]); }*/ /* debug if (value>0.2) { fprintf (stderr,"debug: val %g pos %lf %lf in data %f %f pos %f %f\n", value, coord[0]*3600.0, coord[1]*3600.0, data[desc->ilocdata], factor*(data[desc->ilocdata]-value), data[desc->ilocra], data[desc->ilocdec]); }*/ /* Subtract */ if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank)) data[desc->ilocdata+j*incdatawt] -= value * ffact; else { data[desc->ilocdata+j*incdatawt] = fblank; } /* For CCB beamswitched data add value corresponding to this feeds reference beam */ if (CCBBS) { /* is this the reference or signal beam? */ itemp = j / incfeed; /* itemp odd means reference beam */ isRef = itemp != 2*(itemp/2); /* Use feed offset for feed 1 if this is reference, else feed 2 */ if (isRef) itemp = 0; else itemp = incfeed; /* interpolate */ coord[0] = xpos[itemp]; /* + RACenter; */ coord[1] = ypos[itemp]; /* + DecCenter; */ value = ObitFInterpolateOffset (image, coord, err); /* debug if ((fabs(data[desc->ilocdata+j*incdatawt]+value*ffact)>1.0) && (j<=3)) { fprintf (stderr,"debugRef: val %g pos %lf %lf in data %f %f pos %f %f\n", value, coord[0]*3600.0, coord[1]*3600.0, data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]+value*ffact), data[desc->ilocra], data[desc->ilocdec]); } */ /* debug if ((fabs(coord[0])<0.0014) && (fabs(coord[1])<0.0014) && (j<=3)) { fprintf (stderr,"debugRef: val %g pos %lf %lf in data %f %f pos %f %f\n", value, coord[0]*3600.0, coord[1]*3600.0, data[desc->ilocdata+j*incdatawt], (data[desc->ilocdata+j*incdatawt]+value*ffact), data[desc->ilocra], data[desc->ilocdec]); } */ /* Add */ if ((value!=fblank) && (data[desc->ilocdata+j*incdatawt]!=fblank)) data[desc->ilocdata+j*incdatawt] += value * ffact; else { data[desc->ilocdata+j*incdatawt] = fblank; } } /* end adding to reference beam position */ } /* end loop over array */ data += desc->lrec; /* update buffer pointer */ } /* end loop over buffer */ /* Indicate completion */ finish: if (largs->ithread>=0) ObitThreadPoolDone (in->thread, (gpointer)&largs->ithread); return NULL; } /* end ThreadOTFUtilSubImageBuff */ /** * Make arguments for Threaded OTFUtilSubImageBuff * \param in OTF with internal buffer to be modified. * \param sky OTFSkyModel to subtract. * \param factor Scaling factor for sky model. * \param err Obit error stack object. * \param args Created array of SubImageFuncArg, * delete with KillOTFUtilSubImageArgs * \return number of elements in args. */ static olong MakeOTFUtilSubImageArgs (ObitOTF *in, ObitErr *err, SubImageFuncArg ***args) { olong i, nThreads, ndetect; /* Setup for threading */ /* How many threads? */ nThreads = MAX (1, ObitThreadNumProc(in->thread)); /* Initialize threadArg array */ *args = g_malloc0(nThreads*sizeof(SubImageFuncArg*)); for (i=0; i<nThreads; i++) (*args)[i] = g_malloc0(sizeof(SubImageFuncArg)); ndetect = in->geom->numberDetect; /* How many detectors */ for (i=0; i<nThreads; i++) { (*args)[i]->otfdata = in; (*args)[i]->ithread = i; (*args)[i]->err = err; (*args)[i]->Interp = NULL; (*args)[i]->factor = 1.0; (*args)[i]->xpos = g_malloc0(ndetect*sizeof(ofloat)); (*args)[i]->ypos = g_malloc0(ndetect*sizeof(ofloat)); } return nThreads; } /* end MakeOTFUtilSubImageArgs */ /** * Delete arguments for Threaded OTFUtilSubImageBuff * \param nargs number of elements in args. * \param args Array of SubImageFuncArg, type SubImageFuncArg */ static void KillOTFUtilSubImageArgs (olong nargs, SubImageFuncArg **args) { olong i; if (args==NULL) return; for (i=0; i<nargs; i++) { if (args[i]) { if (args[i]->Interp) ObitFInterpolateUnref(args[i]->Interp); if (args[i]->xpos) g_free (args[i]->xpos); if (args[i]->ypos) g_free (args[i]->ypos); g_free(args[i]); } } g_free(args); } /* end KillOTFUtilSubImageArgs */
{ "alphanum_fraction": 0.6332693966, "avg_line_length": 34.632634864, "ext": "c", "hexsha": "99393b58e907e70d5fe8eb6930f951604109a402", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_line_length": 92, "max_stars_count": 5, "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_path": "ObitSystem/ObitSD/src/ObitOTFUtil.c", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "num_tokens": 25323, "size": 77681 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "monotonic.h" #include <memcached/dockey.h> #include <platform/sized_buffer.h> #include <gsl/gsl> #include <unordered_map> #include <vector> namespace Collections { // The reserved name of the system owned, default collection. const char* const _DefaultCollectionIdentifier = "_default"; static cb::const_char_buffer DefaultCollectionIdentifier( _DefaultCollectionIdentifier); const char* const _DefaultScopeIdentifier = "_default"; static cb::const_char_buffer DefaultScopeIdentifier(_DefaultScopeIdentifier); // SystemEvent keys or parts which will be made into keys const char* const SystemSeparator = ":"; // Note this never changes const char* const SystemEventPrefix = "_collections"; const char* const SystemEventPrefixWithSeparator = "_collections:"; const char* const DeleteKey = "_collections_delete:"; // Couchstore private file name for manifest data const char CouchstoreManifest[] = "_local/collections_manifest"; // Length of the string excluding the zero terminator (i.e. strlen) const size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1; using ManifestUid = WeaklyMonotonic<uint64_t>; // Map used in summary stats using Summary = std::unordered_map<CollectionID, uint64_t>; struct ManifestUidNetworkOrder { ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) { } ManifestUid to_host() const { return ntohll(uid); } ManifestUid uid; }; /** * Return a ManifestUid from a C-string. * A valid ManifestUid is a C-string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid C-string uid * @param len a length for validation purposes * @throws std::invalid_argument if uid is invalid */ ManifestUid makeUid(const char* uid, size_t len = 16); /** * Return a ManifestUid from a std::string * A valid ManifestUid is a std::string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline ManifestUid makeUid(const std::string& uid) { return makeUid(uid.c_str()); } /** * Return a CollectionID from a C-string. * A valid CollectionID is a C-string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul. * * @param uid C-string uid * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const char* uid) { // CollectionID is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<CollectionID>(makeUid(uid, 8)); } /** * Return a CollectionID from a std::string * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const std::string& uid) { return makeCollectionID(uid.c_str()); } /** * Return a ScopeID from a C-string. * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid C-string uid * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const char* uid) { // ScopeId is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<ScopeID>(makeUid(uid, 8)); } /** * Return a ScopeID from a std::string * A valid ScopeID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid std::string * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const std::string& uid) { return makeScopeID(uid.c_str()); } /** * All of the data a system event needs */ struct SystemEventData { ManifestUid manifestUid; // The Manifest which created the event ScopeID sid; // The scope that the collection belongs to CollectionID cid; // The collection the event belongs to }; /** * All of the data a DCP system event message will transmit in the value of the * message. This is the layout to be used on the wire and is in the correct * byte order */ struct SystemEventDcpData { SystemEventDcpData(const SystemEventData& data) : manifestUid(data.manifestUid), sid(data.sid), cid(data.cid) { } /// The manifest uid stored in network byte order ready for sending ManifestUidNetworkOrder manifestUid; /// The scope id stored in network byte order ready for sending ScopeIDNetworkOrder sid; /// The collection id stored in network byte order ready for sending CollectionIDNetworkOrder cid; // The size is sizeof(manifestUid) + sizeof(cid) + sizeof(sid) (msvc won't // allow that expression) constexpr static size_t size{16}; }; namespace VB { /** * The PersistedManifest which stores a copy of the VB::Manifest, the actual * format of the data is defined by VB::Manifest */ using PersistedManifest = std::vector<uint8_t>; } // namespace VB } // end namespace Collections std::ostream& operator<<(std::ostream& os, const Collections::VB::PersistedManifest& data);
{ "alphanum_fraction": 0.7299282257, "avg_line_length": 34.0397727273, "ext": "h", "hexsha": "2a6d40d89a4cc161e7cc97d5d8048898f392b7cf", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "t3rm1n4l/kv_engine", "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "t3rm1n4l/kv_engine", "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "t3rm1n4l/kv_engine", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1413, "size": 5991 }
/************************************************************************************* Copyright 2010 Philip Waldron This file is part of BayRate. BayRate is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BayRate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************************/ #pragma once #include <string> #include <vector> #include <map> #include <gsl/gsl_math.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_chebyshev.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <boost/date_time/gregorian/gregorian.hpp> #include "player.h" #include "game.h" #include "tdListEntry.h" using namespace std; class collection { public: collection(void); ~collection(void); string tournamentCode; map<int, player> playerHash; vector<game> gameList; std::string tournamentName; boost::gregorian::date tournamentDate; double calc_pt(const gsl_vector *v); double calc_pt_df(const gsl_vector *x, gsl_vector *df); void calc_sigma(); void calc_sigma2(); int calc_ratings(); int calc_ratings_fdf(); void reset(); void initSeeding(map<int, tdListEntry> &tdList); void findImprobables(map<int, tdListEntry> &tdList); void setQuiet(bool q); int getFdfIterations(); int getSimplexIterations(); private: double PI; const gsl_rng_type *T; gsl_rng *r; bool quiet; int fdfiterations; int simplexiterations; };
{ "alphanum_fraction": 0.6656519533, "avg_line_length": 27.7605633803, "ext": "h", "hexsha": "c4f4d39e047e29a64b326b32978060950f8cb85b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-01-15T16:46:32.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-04T11:19:37.000Z", "max_forks_repo_head_hexsha": "50b5443b73daae64306e256205eabee8f4815c65", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "flovo/goratings", "max_forks_repo_path": "reference/aga_bayrate/collection.h", "max_issues_count": 13, "max_issues_repo_head_hexsha": "50b5443b73daae64306e256205eabee8f4815c65", "max_issues_repo_issues_event_max_datetime": "2022-02-27T10:03:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T10:06:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "flovo/goratings", "max_issues_repo_path": "reference/aga_bayrate/collection.h", "max_line_length": 88, "max_stars_count": 13, "max_stars_repo_head_hexsha": "50b5443b73daae64306e256205eabee8f4815c65", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "flovo/goratings", "max_stars_repo_path": "reference/aga_bayrate/collection.h", "max_stars_repo_stars_event_max_datetime": "2021-12-12T00:12:48.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-02T16:43:12.000Z", "num_tokens": 442, "size": 1971 }
#include <gsl/gsl_matrix.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_vector.h> #include "cimple_mpc_computation.h" /** * Set up weight matrices for the quadratic problem */ polytope * set_cost_function(gsl_matrix *P, gsl_vector *q, gsl_matrix *L, gsl_vector *M, current_state *now, system_dynamics *s_dyn, cost_function *f_cost, size_t time_horizon){ size_t N = time_horizon; size_t n = s_dyn->A->size1; size_t m = s_dyn->B->size2; /*Calculate P and q */ // |B 0 0 0 0| // |AB B 0 0 0| // Ct = |A^2B AB B 0 0| // |A^3B A^2B AB B 0| // |A^4B A^3B A^2B AB B| // |I 0 0 0 0| // |A I 0 0 0| // A_K = |A^2 A I 0 0| // |A^3 A^2 A I 0| // |A^4 A^3 A^2 A I| // |A | // |A^2| // A_N = |A^3| // |A^4| // |A^5| //P = Q2 + Ct^T.R2.Ct //q = {([x^T.A_N^T + (A_K.K_hat)^T].[R2.Ct])+(0.5*r^T.Ct)}^T // symmetrize gsl_matrix * Q2 = gsl_matrix_alloc(N*m, N*m); gsl_matrix_view Q_view = gsl_matrix_submatrix(f_cost->Q,(f_cost->Q->size1-N),(f_cost->Q->size2-N),(N),(N)); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &Q_view.matrix,&Q_view.matrix, 0.0, Q2); gsl_matrix * R2 = gsl_matrix_alloc(N*n, N*n); gsl_matrix_view R_view = gsl_matrix_submatrix(f_cost->R,(f_cost->R->size1-N),(f_cost->R->size2-N),(N),(N)); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &R_view.matrix,&R_view.matrix, 0.0, R2); //Calculate P gsl_matrix * R2_dot_Ct = gsl_matrix_alloc(N*n, N*m); gsl_matrix_set_zero(R2_dot_Ct); gsl_matrix_view Ct_view = gsl_matrix_submatrix(s_dyn->aux_matrices->Ct,0,0,N,N); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, R2, &Ct_view.matrix, 0.0, R2_dot_Ct); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &Ct_view.matrix, R2_dot_Ct, 0.0, P); gsl_matrix_add(P, Q2); //Clean up! gsl_matrix_free(R2); gsl_matrix_free(Q2); //Calculate q gsl_vector_set_zero(q); gsl_vector * A_N_dot_x = gsl_vector_alloc(N*n); gsl_vector_set_zero(A_N_dot_x); gsl_matrix_view A_N_view = gsl_matrix_submatrix(s_dyn->aux_matrices->A_N,0,0,N,1); gsl_blas_dgemv(CblasNoTrans, 1.0, &A_N_view.matrix, now->x, 0.0, A_N_dot_x); gsl_vector * A_K_dot_K_hat = gsl_vector_alloc(N*n); gsl_vector_set_zero(A_K_dot_K_hat); gsl_matrix_view A_K_view = gsl_matrix_submatrix(s_dyn->aux_matrices->A_K,0,0,N,N); gsl_vector_view K_hat_view = gsl_vector_subvector(s_dyn->aux_matrices->K_hat,0,N); gsl_blas_dgemv(CblasNoTrans, 1.0, &A_K_view.matrix, &K_hat_view.vector, 0.0, A_K_dot_K_hat); //[x^T.A_N^T + (A_K.K_hat)^T]^T gsl_vector_add(A_N_dot_x, A_K_dot_K_hat); //{([x^T.A_N^T + (A_K.K_hat)^T].[R2.Ct])}^T //R2_dot_Ct was calculated earlier gsl_blas_dgemv(CblasTrans, 1.0, R2_dot_Ct, A_N_dot_x, 0.0, q); //(0.5*r^T.Ct) gsl_vector *Right_side = gsl_vector_alloc(N*m); gsl_vector_view r_view = gsl_vector_subvector(f_cost->r,(f_cost->r->size-N),N); gsl_blas_dgemv(CblasTrans, 0.5, &Ct_view.matrix, &r_view.vector, 0.0, Right_side); gsl_vector_add(q, Right_side); //Clean up! gsl_matrix_free(R2_dot_Ct); gsl_vector_free(A_N_dot_x); gsl_vector_free(A_K_dot_K_hat); gsl_vector_free(Right_side); /*GUROBI Convex Optimization: solve quadratic problem*/ //Minimizing polytope * constraints_polytope = polytope_alloc(L->size1, L->size2); gsl_matrix_memcpy(constraints_polytope->H,L); gsl_vector_memcpy(constraints_polytope->G,M); //back to gsl polytope polytope *opt_constraints = polytope_minimize(constraints_polytope); polytope_free(constraints_polytope); // //Minimizing // polytope * constraints_polytope = polytope_alloc(L->size1, L->size2); // gsl_matrix_memcpy(constraints_polytope->H,L); // gsl_vector_memcpy(constraints_polytope->G,M); // // printf("\n\n\n\nHALT\n\n\n\n\n"); // gsl_matrix_print(constraints_polytope->H,"H"); // gsl_vector_print(constraints_polytope->G,"G"); // // polytope *opt_constraints = polytope_minimize(constraints_polytope); // polytope_free(constraints_polytope); // // // printf("\n\n\n\nNOOOOO\n\n\n\n\n"); // gsl_matrix_print(opt_constraints->H,"H"); // gsl_vector_print(opt_constraints->G,"G"); // // polytope *opt_constraints = polytope_alloc(10,N); // gsl_vector_set(opt_constraints->G,0,1); // gsl_vector_set(opt_constraints->G,1,-1); // gsl_vector_set(opt_constraints->G,2,1); // gsl_vector_set(opt_constraints->G,3,-1); // gsl_vector_set(opt_constraints->G,4,1); // gsl_vector_set(opt_constraints->G,5,-1); // gsl_vector_set(opt_constraints->G,6,1); // gsl_vector_set(opt_constraints->G,7,-1); // gsl_vector_set(opt_constraints->G,8,1); // gsl_vector_set(opt_constraints->G,9,-1); // gsl_matrix_set(opt_constraints->H,0,0,0.2); // gsl_matrix_set(opt_constraints->H,0,1,0); // gsl_matrix_set(opt_constraints->H,0,2,0); // gsl_matrix_set(opt_constraints->H,0,3,0); // gsl_matrix_set(opt_constraints->H,0,4,0); // // gsl_matrix_set(opt_constraints->H,1,0,-20); // gsl_matrix_set(opt_constraints->H,1,1,0); // gsl_matrix_set(opt_constraints->H,1,2,0); // gsl_matrix_set(opt_constraints->H,1,3,0); // gsl_matrix_set(opt_constraints->H,1,4,0); // gsl_matrix_set(opt_constraints->H,2,0,0.2); // gsl_matrix_set(opt_constraints->H,2,1,0.2); // gsl_matrix_set(opt_constraints->H,2,2,0); // gsl_matrix_set(opt_constraints->H,2,3,0); // gsl_matrix_set(opt_constraints->H,2,4,0); // // gsl_matrix_set(opt_constraints->H,3,0,-20); // gsl_matrix_set(opt_constraints->H,3,1,-20); // gsl_matrix_set(opt_constraints->H,3,2,0); // gsl_matrix_set(opt_constraints->H,3,3,0); // gsl_matrix_set(opt_constraints->H,3,4,0); // gsl_matrix_set(opt_constraints->H,4,0,0.2); // gsl_matrix_set(opt_constraints->H,4,1,0.2); // gsl_matrix_set(opt_constraints->H,4,2,0.2); // gsl_matrix_set(opt_constraints->H,4,3,0); // gsl_matrix_set(opt_constraints->H,4,4,0); // // gsl_matrix_set(opt_constraints->H,5,0,-20); // gsl_matrix_set(opt_constraints->H,5,1,-20); // gsl_matrix_set(opt_constraints->H,5,2,-20); // gsl_matrix_set(opt_constraints->H,5,3,0); // gsl_matrix_set(opt_constraints->H,5,4,0); // gsl_matrix_set(opt_constraints->H,6,0,0.2); // gsl_matrix_set(opt_constraints->H,6,1,0.2); // gsl_matrix_set(opt_constraints->H,6,2,0.2); // gsl_matrix_set(opt_constraints->H,6,3,0.2); // gsl_matrix_set(opt_constraints->H,6,4,0); // // gsl_matrix_set(opt_constraints->H,7,0,-20); // gsl_matrix_set(opt_constraints->H,7,1,-20); // gsl_matrix_set(opt_constraints->H,7,2,-20); // gsl_matrix_set(opt_constraints->H,7,3,-20); // gsl_matrix_set(opt_constraints->H,7,4,0); // gsl_matrix_set(opt_constraints->H,8,0,0.2); // gsl_matrix_set(opt_constraints->H,8,1,0.2); // gsl_matrix_set(opt_constraints->H,8,2,0.2); // gsl_matrix_set(opt_constraints->H,8,3,0.2); // gsl_matrix_set(opt_constraints->H,8,4,0.2); // // gsl_matrix_set(opt_constraints->H,9,0,-20); // gsl_matrix_set(opt_constraints->H,9,1,-20); // gsl_matrix_set(opt_constraints->H,9,2,-20); // gsl_matrix_set(opt_constraints->H,9,3,-20); // gsl_matrix_set(opt_constraints->H,9,4,-20); return opt_constraints; } /** * Set up GUROBI environment and solve qp */ void compute_optimal_control_qp(gsl_matrix *low_u, double *low_cost, gsl_matrix *P, gsl_vector* q, polytope *opt_constraints, size_t time_horizon, size_t n){ //Initialization for qp in gurobi GRBenv *env = NULL; GRBmodel *model = NULL; int error = 0; double sol[time_horizon]; int optimstatus; double cost; /* Create environment */ error = GRBloadenv(&env, "qp.log"); if (error) goto QUIT; error = GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0); if (error) goto QUIT; /* Create an empty model */ error = GRBnewmodel(env, &model, "qp", 0, NULL, NULL, NULL, NULL, NULL); if (error) goto QUIT; /* Add variables */ error = GRBaddvars(model, (int)time_horizon, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (error) goto QUIT; /* Quadratic objective terms */ error = gsl_matrix_to_qpterm_gurobi(P, model, time_horizon); if (error) goto QUIT; /* Linear objective term */ error = gsl_vector_to_linterm_gurobi(q, model, time_horizon); if (error) goto QUIT; /* Add constraints*/ error = polytope_to_constraints_gurobi(opt_constraints,model,time_horizon); if (error) goto QUIT; /* Optimize model */ error = GRBoptimize(model); if (error) goto QUIT; /* Write model to 'qp.lp' */ error = GRBwrite(model, "qp.lp"); if (error) goto QUIT; /* Capture solution information */ error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus); if (error) goto QUIT; error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &cost); if (error) goto QUIT; error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, (int)time_horizon, sol); if (error) goto QUIT; printf("\nOptimization complete\n"); if (optimstatus == GRB_OPTIMAL) { printf("\nOptimal objective: %.4e\n", cost); for(size_t i=0;i<time_horizon;i++){ printf(" u%d=%.4f", (int)i,sol[i]); } printf("\n"); } else if (optimstatus == GRB_INF_OR_UNBD) { printf("\nModel is infeasible or unbounded\n"); } else { printf("\nOptimization was stopped early\n"); } if(cost < *low_cost){ for(size_t i = 0; i<n; i++){ for(size_t j = 0; j<time_horizon; j++){ gsl_matrix_set(low_u,i, j,sol[j]); } } *low_cost = cost; } QUIT: /* Error reporting */ if (error) { printf("ERROR: %s\n", GRBgeterrormsg(env)); exit(1); } /* Free model */ error = GRBfreemodel(model); if (error) { printf("ERROR: %s\n", GRBgeterrormsg(env)); exit(1); } /* Free environment */ GRBfreeenv(env); } /** * Calculate (optimal) input that will be applied to take plant from current state (now) to target_abs_state. */ void get_input (gsl_matrix * low_u, current_state * now, discrete_dynamics * d_dyn, system_dynamics * s_dyn, int target_abs_state, cost_function * f_cost, size_t current_time_horizon, polytope **polytope_list_backup) { //Set input back to zero (safety precaution) gsl_matrix_set_zero(low_u); //Help variables: size_t n = now->x->size; size_t N = current_time_horizon; double low_cost = INFINITY; double err_weight = f_cost->distance_error_weight; //Set start region (depends on conservative path or not) polytope *P1; int start = now->current_abs_state; if (d_dyn->conservative == 1){ // Take convex hull or polytope as starting polytope P1 // if convex_hull != NULL => hull was computed => several polytopes in that region if (d_dyn->abstract_states_set[start]->convex_hull->H != NULL){ P1 = d_dyn->abstract_states_set[start]->convex_hull; } else{ P1 = d_dyn->abstract_states_set[start]->cells[0]->polytope_description; } } else{ // Take original proposition preserving abstract state as constraint // must be single polytope (ensuring convex) if (d_dyn->original_regions[start]->cells_count == 1){ P1 = d_dyn->original_regions[start]->cells[0]->polytope_description; } else { fprintf(stderr, "\nIn Region of polytopes(%d): `conservative = False` arg requires that original abstract_states_set be convex\n", now->current_abs_state); exit(EXIT_FAILURE); } } //Find optimal path into target region //by finding polytope that is easiest to reach in target region // for each polytope in target region for (int i = 0; i < d_dyn->abstract_states_set[target_abs_state]->cells_count; i++){ polytope *P3 = d_dyn->abstract_states_set[target_abs_state]->cells[i]->polytope_description; //Finding a path to target region if (err_weight > 0){ //Set r (=xc.R)(from default to polytope specific): double *xc = P3->chebyshev_center; //r[n*(N-1), n*N] += err_weight * xc; for (size_t j = n * (N - 1); j < n*N; j++){ double * element_value = gsl_vector_ptr(f_cost->r, j); * element_value += err_weight * xc[i]; gsl_vector_set(f_cost->r, j, *element_value); } search_better_path(low_u, now,s_dyn, P1, P3,d_dyn->ord, N, f_cost, &low_cost, polytope_list_backup, d_dyn->time_horizon); //Reset r vector to default values for (size_t j = n * (N - 1); j < n*N; j++){ double * element_value = gsl_vector_ptr(f_cost->r, j); * element_value -= err_weight * xc[i]; gsl_vector_set(f_cost->r, j, * element_value); } } else{ search_better_path(low_u, now,s_dyn, P1, P3,d_dyn->ord, N, f_cost, &low_cost, polytope_list_backup, d_dyn->time_horizon); } } if (low_cost == INFINITY){ //raise Exception fprintf(stderr, "\nget_input: Did not find any trajectory\n"); exit(EXIT_FAILURE); } }; /** * Calculates (optimal) input to reach desired state (P3) from current state (now) through convex optimization */ void search_better_path(gsl_matrix *low_u, current_state *now, system_dynamics *s_dyn, polytope *P1, polytope *P3, int ord , size_t time_horizon, cost_function * f_cost, double *low_cost, polytope **polytope_list_backup, size_t total_time){ //Auxiliary variables size_t N = time_horizon; size_t n = s_dyn->A->size2; size_t m = s_dyn->B->size2; //Build list of polytopes that the state is going to be in in the next N time steps polytope **polytope_list = malloc(sizeof(polytope)*(N+1)); polytope_list[0] = polytope_alloc(P1->H->size1,P1->H->size2); gsl_matrix_memcpy(polytope_list[0]->H, P1->H); gsl_vector_memcpy(polytope_list[0]->G, P1->G); for (int i = 1; i < N; i++) { polytope_list[i] = polytope_alloc(P1->H->size1,P1->H->size2); gsl_matrix_memcpy(polytope_list[i]->H, P1->H); gsl_vector_memcpy(polytope_list[i]->G, P1->G); } polytope_list[N] = polytope_alloc(P3->H->size1, P3->H->size2); gsl_matrix_memcpy(polytope_list[N]->H, P3->H); gsl_vector_memcpy(polytope_list[N]->G, P3->G); size_t sum_polytope_sizes = 0; for(int i = 0; i<N+1; i++){ sum_polytope_sizes += polytope_list[i]->H->size1; } polytope *constraints = set_path_constraints(now, s_dyn, polytope_list, N); //Updating backup list of polytopes //If polytope list doesn't have to be initialized completely, old ones have first to be destroyed: if(N< total_time) { for (size_t i = total_time; i > total_time - N - 1; i--) { polytope_free(polytope_list_backup[i]); } } //List is updated (or created, if total_time == N) for(size_t i = total_time-N; i< total_time+1; i++){ size_t k =i-(total_time-N); polytope_list_backup[i] = polytope_alloc(polytope_list[k]->H->size1,polytope_list[k]->H->size2); gsl_matrix_memcpy(polytope_list_backup[i]->H,polytope_list[k]->H); gsl_vector_memcpy(polytope_list_backup[i]->G,polytope_list[k]->G); } for(int i = 0; i< N+1; i++){ polytope_free(polytope_list[i]); } free(polytope_list); if (ord == 2){ gsl_matrix * P = gsl_matrix_alloc(N*m, N*m); gsl_vector * q = gsl_vector_alloc(N*m); polytope *opt_constraints = set_cost_function(P, q, constraints->H, constraints->G, now, s_dyn, f_cost, N); compute_optimal_control_qp(low_u, low_cost, P, q, opt_constraints, N, n); polytope_free(opt_constraints); gsl_vector_free(q); gsl_matrix_free(P); } polytope_free(constraints); }; /** * Compute a polytope that constraints the system over the next N time steps to fullfill the GR(1) specifications */ polytope * set_path_constraints(current_state * now, system_dynamics * s_dyn, polytope **list_polytopes, size_t N){ //Disturbance assumed at every step and full dimension of s_dyn.Wset // Help variables size_t n = s_dyn->A->size2; // State space dimension size_t m = s_dyn->B->size2; size_t sum_polytope_dim = 0; // Sum of dimension n of all polytopes in the list polytope *scaled_W_set = polytope_linear_transform(s_dyn->W_set, s_dyn->E); // multiplication: EW polytope **robust_polytope_list = malloc(sizeof(polytope)*(N+1)); for(size_t i = 0; i < N+1; i++){ //Subtract EW of polytope to make them robust against disturbances robust_polytope_list[i] = polytope_pontryagin(list_polytopes[i], scaled_W_set); sum_polytope_dim += robust_polytope_list[i]->H->size1; } /* INITIALIZE MATRICES: Lk, Mk, constraints*/ polytope *constraints = polytope_alloc(sum_polytope_dim, n*(N+1)); gsl_matrix_set_zero(constraints->H); gsl_vector_set_zero(constraints->G); /* * |G_0| * |G_1| *Mk = |G_2| dim[sum_polytope_dim x 1] * |G_3| * |G_4| * * with M = |Mk| * |Mu| * */ /* * |H_0 0 0 0 0 | * |0 H_1 0 0 0 | * constaints->H= |0 0 H_2 0 0 | dim[sum_polytope_dim x n*N] * |0 0 0 H_3 0 | * |0 0 0 0 H_4| * */ //Loop over N and polytopes in parallel size_t polytope_count = 0; for(int i = 0; i<N+1; i++){ //Set diagonal block N of constaints->H for(size_t j = 0; j<n; j++){ for(size_t k = 0; k<robust_polytope_list[i]->H->size1; k++){ gsl_matrix_set(constraints->H,polytope_count+k, j+(i*n), gsl_matrix_get(robust_polytope_list[i]->H,k,j)); } } // Build constraints->g for(size_t j = 0; j<robust_polytope_list[i]->G->size; j++){ // Set entries Mk[j+polytope_count] = G_i[j] gsl_vector_set(constraints->G,j+polytope_count,gsl_vector_get(robust_polytope_list[i]->G,j)); } polytope_count += robust_polytope_list[i]->H->size1; } /*Update L and M*/ // Lk = H_constaints->Hdiag.L_default gsl_matrix_view L_default_view = gsl_matrix_submatrix(s_dyn->aux_matrices->L_default,0,0,n*(N+1),(m*N)+n); gsl_matrix *L_full = gsl_matrix_alloc(sum_polytope_dim, (m*N)+n); gsl_vector *M_full = gsl_vector_alloc(sum_polytope_dim); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, constraints->H, &L_default_view.matrix ,0.0,L_full); //Update M such that it includes the uncertainty of noise gsl_vector_memcpy(M_full, constraints->G); // Remove first constraints on x(0) they are obviously already satisfied // L_x = L[{(polytope[0]+1),(dim_n(L))},{1,n}] gsl_matrix_view L_x = gsl_matrix_submatrix(L_full, robust_polytope_list[0]->H->size1, 0, (L_full->size1)-(robust_polytope_list[0]->H->size1), n); // L_u = L[{(polytope[0]+1),(dim_n(L))},{(n+1),(dim_m(L))}] gsl_matrix_view L_u = gsl_matrix_submatrix(L_full, robust_polytope_list[0]->H->size1, n, (L_full->size1)-(robust_polytope_list[0]->H->size1), L_full->size2 - n); // M_view = M[{(polytope[0]+1),(dim_n(M))}] gsl_vector_view M_view = gsl_vector_subvector(M_full, robust_polytope_list[0]->H->size1, M_full->size-robust_polytope_list[0]->H->size1); //M = M-(L_x.x) gsl_vector * L_x_dot_X0 = gsl_vector_alloc((L_full->size1)-(robust_polytope_list[0]->H->size1)); gsl_blas_dgemv(CblasNoTrans, 1.0, &L_x.matrix, now->x, 0.0, L_x_dot_X0); gsl_vector_sub(&M_view.vector, L_x_dot_X0); polytope * return_constraints = polytope_alloc(constraints->H->size1-robust_polytope_list[0]->H->size1, ((constraints->H->size2)-(robust_polytope_list[0]->H->size2))); gsl_matrix_memcpy(return_constraints->H, &L_u.matrix); gsl_vector_memcpy(return_constraints->G, &M_view.vector); //Clean up! polytope_free(scaled_W_set); polytope_free(constraints); for(size_t i = 0; i < N+1; i++){ polytope_free(robust_polytope_list[i]); } free(robust_polytope_list); gsl_vector_free(L_x_dot_X0); return return_constraints; };
{ "alphanum_fraction": 0.604867277, "avg_line_length": 36.4103852596, "ext": "c", "hexsha": "e159a5c488d4a27d94acf5ef227e5ff358228a9a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_line_length": 171, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/cimple_mpc_computation.c", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 6469, "size": 21737 }
#include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #ifndef gauge_config #include "config.h" #define gauge_config 1 #define sq(x) ((x)*(x)) #define cb(x) ((x)*(x)*(x)) #endif // SU(3) Matrix // only the first two rows carries useful information (Lang p.80) // note that the first two rows must be orthonormal // use su3_normalize() for this typedef struct{ gsl_complex a1; gsl_complex a2; gsl_complex a3; gsl_complex b1; gsl_complex b2; gsl_complex b3; } su3_matrix; // SU(3) matrix methods -------------------------------------- // print matrix void su3_print(const su3_matrix A){ printf("%f + i*%f \t", GSL_REAL(A.a1), GSL_IMAG(A.a1)); printf("%f + i*%f \t", GSL_REAL(A.a2), GSL_IMAG(A.a2)); printf("%f + i*%f \n", GSL_REAL(A.a3), GSL_IMAG(A.a3)); printf("%f + i*%f \t", GSL_REAL(A.b1), GSL_IMAG(A.b1)); printf("%f + i*%f \t", GSL_REAL(A.b2), GSL_IMAG(A.b2)); printf("%f + i*%f \n", GSL_REAL(A.b3), GSL_IMAG(A.b3)); } // the identity matrix su3_matrix su3_unit(){ su3_matrix u; u.a1=GSL_COMPLEX_ONE; u.a2=GSL_COMPLEX_ZERO; u.a3=GSL_COMPLEX_ZERO; u.b1=GSL_COMPLEX_ZERO; u.b2=GSL_COMPLEX_ONE; u.b3=GSL_COMPLEX_ZERO; return u; } // normalize matrix su3_matrix su3_norm(const su3_matrix A){ su3_matrix result; // normalize first row double norm = sqrt(gsl_complex_abs2(A.a1)+gsl_complex_abs2(A.a2)+gsl_complex_abs2(A.a3)); result.a1 = gsl_complex_div(A.a1,gsl_complex_rect(norm,0)); result.a2 = gsl_complex_div(A.a2,gsl_complex_rect(norm,0)); result.a3 = gsl_complex_div(A.a3,gsl_complex_rect(norm,0)); // orthogonize second row gsl_complex dprod = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,gsl_complex_conjugate(result.a1)), gsl_complex_mul(A.b2,gsl_complex_conjugate(result.a2))), gsl_complex_mul(A.b3,gsl_complex_conjugate(result.a3))); result.b1 = gsl_complex_sub(A.b1,gsl_complex_mul(result.a1,dprod)); result.b2 = gsl_complex_sub(A.b2,gsl_complex_mul(result.a2,dprod)); result.b3 = gsl_complex_sub(A.b3,gsl_complex_mul(result.a3,dprod)); // normalize second row norm = sqrt(gsl_complex_abs2(result.b1)+gsl_complex_abs2(result.b2)+gsl_complex_abs2(result.b3)); result.b1 = gsl_complex_div(result.b1,gsl_complex_rect(norm,0)); result.b2 = gsl_complex_div(result.b2,gsl_complex_rect(norm,0)); result.b3 = gsl_complex_div(result.b3,gsl_complex_rect(norm,0)); return result; } // multiply matrices su3_matrix su3_mul(const su3_matrix A, const su3_matrix B){ su3_matrix result; gsl_complex w1,w2,w3; // Third row of B as a cross product (c.f. Lang p.80) w1 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a2),gsl_complex_conjugate(B.b3)), gsl_complex_mul(gsl_complex_conjugate(B.a3),gsl_complex_conjugate(B.b2)) ); w2 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a3),gsl_complex_conjugate(B.b1)), gsl_complex_mul(gsl_complex_conjugate(B.a1),gsl_complex_conjugate(B.b3)) ); w3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(B.a1),gsl_complex_conjugate(B.b2)), gsl_complex_mul(gsl_complex_conjugate(B.a2),gsl_complex_conjugate(B.b1)) ); result.a1 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a1),gsl_complex_mul(A.a2,B.b1)), gsl_complex_mul(A.a3,w1)); result.a2 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a2),gsl_complex_mul(A.a2,B.b2)), gsl_complex_mul(A.a3,w2)); result.a3 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.a1,B.a3),gsl_complex_mul(A.a2,B.b3)), gsl_complex_mul(A.a3,w3)); result.b1 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a1),gsl_complex_mul(A.b2,B.b1)), gsl_complex_mul(A.b3,w1)); result.b2 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a2),gsl_complex_mul(A.b2,B.b2)), gsl_complex_mul(A.b3,w2)); result.b3 = gsl_complex_add(gsl_complex_add(gsl_complex_mul(A.b1,B.a3),gsl_complex_mul(A.b2,B.b3)), gsl_complex_mul(A.b3,w3)); return result; } // inverse matrix su3_matrix su3_inv(const su3_matrix A){ su3_matrix result; gsl_complex w1,w2,w3; // Third row of B as a cross product (c.f. Lang p.80) w1 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b3)), gsl_complex_mul(gsl_complex_conjugate(A.a3),gsl_complex_conjugate(A.b2)) ); w2 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a3),gsl_complex_conjugate(A.b1)), gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b3)) ); w3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b2)), gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b1)) ); result.a1 = gsl_complex_sub( gsl_complex_mul(A.b2,w3), gsl_complex_mul( A.b3,w2) ); result.a2 = gsl_complex_sub( gsl_complex_mul(A.a3,w2), gsl_complex_mul( A.a2,w3) ); result.a3 = gsl_complex_sub( gsl_complex_mul(A.a2,A.b3), gsl_complex_mul( A.a3,A.b2) ); result.b1 = gsl_complex_sub( gsl_complex_mul(A.b3,w1), gsl_complex_mul( A.b1,w3) ); result.b2 = gsl_complex_sub( gsl_complex_mul(A.a1,w3), gsl_complex_mul( A.a3,w1) ); result.b3 = gsl_complex_sub( gsl_complex_mul(A.a3,A.b1), gsl_complex_mul( A.a1,A.b3) ); return result; } // generate random matrix su3_matrix su3_rand(const gsl_rng* r){ su3_matrix result; result.a1 = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1)); result.a2 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1)); result.a3 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1)); result.b1 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1)); result.b2 = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1)); result.b3 = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1)); return su3_norm(result); } double su3_trace(const su3_matrix A){ gsl_complex c3; c3 = gsl_complex_sub( gsl_complex_mul(gsl_complex_conjugate(A.a1),gsl_complex_conjugate(A.b2)), gsl_complex_mul(gsl_complex_conjugate(A.a2),gsl_complex_conjugate(A.b1)) ); return GSL_REAL(gsl_complex_add(gsl_complex_add(A.a1,A.b2),c3)); } // end of SU(3) matrix methods ---------------------------------------------
{ "alphanum_fraction": 0.7332689833, "avg_line_length": 42.8689655172, "ext": "c", "hexsha": "000121a87303a3bf27dffca92327556cb623efe0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "uchuutamashi/lqcd", "max_forks_repo_path": "su3/su3_matrix.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "uchuutamashi/lqcd", "max_issues_repo_path": "su3/su3_matrix.c", "max_line_length": 173, "max_stars_count": null, "max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "uchuutamashi/lqcd", "max_stars_repo_path": "su3/su3_matrix.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1967, "size": 6216 }
#ifndef _MARKET_INTEGRATION_ #define _MARKET_INTEGRATION_ #include <gsl/gsl_integration.h> typedef struct{ double (*function)(double *x, size_t n, void * p); void *params; } nquad_function; typedef void (*multi_integration_type)(int n, nquad_function *f, double *lb, double *ub, double epsabs, double epsrel, size_t limit, double *result, double *abserr); void nquad(int n, nquad_function *f, double *lb, double *ub, double epsabs, double epsrel, size_t limit, double * result, double *abserr); void mcint(int n, nquad_function *f, double *lb, double *ub, double epsabs, double epsrel, size_t limit, double *result, double *abserr); #endif
{ "alphanum_fraction": 0.7012987013, "avg_line_length": 31.5, "ext": "h", "hexsha": "0563559739c1165b1b6f67557ca01d82b86e1dc8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "benjaminvatterj/multidim_integration", "max_forks_repo_path": "integration.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "benjaminvatterj/multidim_integration", "max_issues_repo_path": "integration.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "benjaminvatterj/multidim_integration", "max_stars_repo_path": "integration.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 187, "size": 693 }
// // Author // luncliff@gmail.com // #pragma once #ifndef _NDCAM_INCLUDE_H_ #define _NDCAM_INCLUDE_H_ #include <gsl/gsl> #include <android/hardware_buffer.h> #include <android/native_window.h> #include <android/native_window_jni.h> #include <media/NdkImage.h> #include <media/NdkImageReader.h> #include <camera/NdkCameraCaptureSession.h> #include <camera/NdkCameraDevice.h> #include <camera/NdkCameraError.h> #include <camera/NdkCameraManager.h> #include <camera/NdkCameraMetadata.h> #include <camera/NdkCameraMetadataTags.h> #include <camera/NdkCaptureRequest.h> using native_window_ptr = std::unique_ptr<ANativeWindow, void (*)(ANativeWindow*)>; using capture_session_output_container_ptr = std::unique_ptr<ACaptureSessionOutputContainer, void (*)(ACaptureSessionOutputContainer*)>; using capture_session_output_ptr = std::unique_ptr<ACaptureSessionOutput, void (*)(ACaptureSessionOutput*)>; using capture_request_ptr = std::unique_ptr<ACaptureRequest, void (*)(ACaptureRequest*)>; using camera_output_target_ptr = std::unique_ptr<ACameraOutputTarget, void (*)(ACameraOutputTarget*)>; /** * Library context. Supports auto releasing and facade for features * * !!! All NDK type members must be public. There will be no encapsulation !!! */ struct camera_group_t final { // without external camera, 2 is enough(back + front). // But we will use more since there might be multiple(for now, 2) external // camera... static constexpr auto max_camera_count = 4; public: // Android camera manager. After the context is initialized, this must be // non-null if this variable is null, then the context is considered as 'not // initailized' and all operation *can* be ignored ACameraManager* manager = nullptr; ACameraIdList* id_list = nullptr; // cached metadata std::array<ACameraMetadata*, max_camera_count> metadata_set{}; // // even though android system limits the number of maximum open camera // device, we will consider multiple camera are working concurrently. // // if element is nullptr, it means the device is not open. std::array<ACameraDevice*, max_camera_count> device_set{}; // if there is no session, session pointer will be null std::array<ACameraCaptureSession*, max_camera_count> session_set{}; // sequence number from capture session std::array<int, max_camera_count> seq_id_set{}; public: camera_group_t() noexcept = default; // copy-move is disabled camera_group_t(const camera_group_t&) = delete; camera_group_t(camera_group_t&&) = delete; camera_group_t& operator=(const camera_group_t&) = delete; camera_group_t& operator=(camera_group_t&&) = delete; ~camera_group_t() noexcept { this->release(); // ensure release precedure } public: void release() noexcept; public: auto open_device(uint16_t id, ACameraDevice_StateCallbacks& callbacks) noexcept -> camera_status_t; // Notice that this routine doesn't free metadata void close_device(uint16_t id) noexcept; auto start_repeat( uint16_t id, ANativeWindow* window, ACameraCaptureSession_stateCallbacks& on_session_changed, ACameraCaptureSession_captureCallbacks& on_capture_event) noexcept -> camera_status_t; void stop_repeat(uint16_t id) noexcept; auto start_capture( uint16_t id, ANativeWindow* window, ACameraCaptureSession_stateCallbacks& on_session_changed, ACameraCaptureSession_captureCallbacks& on_capture_event) noexcept -> camera_status_t; void stop_capture(uint16_t id) noexcept; // ACAMERA_LENS_FACING_FRONT // ACAMERA_LENS_FACING_BACK // ACAMERA_LENS_FACING_EXTERNAL uint16_t get_facing(uint16_t id) noexcept; }; // device callbacks void context_on_device_disconnected(camera_group_t& context, ACameraDevice* device) noexcept; void context_on_device_error(camera_group_t& context, ACameraDevice* device, int error) noexcept; // session state callbacks void context_on_session_active(camera_group_t& context, ACameraCaptureSession* session) noexcept; void context_on_session_closed(camera_group_t& context, ACameraCaptureSession* session) noexcept; void context_on_session_ready(camera_group_t& context, ACameraCaptureSession* session) noexcept; // capture callbacks void context_on_capture_started(camera_group_t& context, ACameraCaptureSession* session, const ACaptureRequest* request, uint64_t time_point) noexcept; void context_on_capture_progressed(camera_group_t& context, ACameraCaptureSession* session, ACaptureRequest* request, const ACameraMetadata* result) noexcept; void context_on_capture_completed(camera_group_t& context, ACameraCaptureSession* session, ACaptureRequest* request, const ACameraMetadata* result) noexcept; void context_on_capture_failed(camera_group_t& context, ACameraCaptureSession* session, ACaptureRequest* request, ACameraCaptureFailure* failure) noexcept; void context_on_capture_buffer_lost(camera_group_t& context, ACameraCaptureSession* session, ACaptureRequest* request, ANativeWindow* window, int64_t frame_number) noexcept; void context_on_capture_sequence_abort(camera_group_t& context, ACameraCaptureSession* session, int sequence_id) noexcept; void context_on_capture_sequence_complete(camera_group_t& context, ACameraCaptureSession* session, int sequence_id, int64_t frame_number) noexcept; // status - error code to string auto camera_error_message(camera_status_t status) noexcept -> const char*; #endif
{ "alphanum_fraction": 0.6603018171, "avg_line_length": 37.1085714286, "ext": "h", "hexsha": "e9179bd265f527da09432c6228387797af707c41", "lang": "C", "max_forks_count": 17, "max_forks_repo_forks_event_max_datetime": "2021-12-30T10:38:06.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-12T09:25:21.000Z", "max_forks_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "jerry-deng-pico/NdkCamera", "max_forks_repo_path": "include/ndk_camera.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_issues_repo_issues_event_max_datetime": "2020-01-14T06:33:15.000Z", "max_issues_repo_issues_event_min_datetime": "2019-10-17T15:58:54.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "jerry-deng-pico/NdkCamera", "max_issues_repo_path": "include/ndk_camera.h", "max_line_length": 80, "max_stars_count": 20, "max_stars_repo_head_hexsha": "85c37ef9ec061280b6aea8ecac9c1b99f2941abd", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "luncliff/NdkCamera", "max_stars_repo_path": "include/ndk_camera.h", "max_stars_repo_stars_event_max_datetime": "2021-10-01T13:25:32.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-30T06:09:53.000Z", "num_tokens": 1283, "size": 6494 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_bessel.h> int main (void) { double x = 5.0; gsl_sf_result result; double expected = -0.17759677131433830434739701; int status = gsl_sf_bessel_J0_e (x, &result); printf ("status = %s\n", gsl_strerror(status)); printf ("J0(5.0) = %.18f\n" " +/- % .18f\n", result.val, result.err); printf ("exact = %.18f\n", expected); return status; }
{ "alphanum_fraction": 0.6061946903, "avg_line_length": 20.5454545455, "ext": "c", "hexsha": "4f41f2a0c2de9a3a5cb242719a2d900ece0f16ed", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/specfun_e.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/specfun_e.c", "max_line_length": 50, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/specfun_e.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 148, "size": 452 }
// This random generator is a C++ wrapper for the GNU Scientific Library // Copyright (C) 2001 Torbjorn Vik // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #ifndef __multimin_fdfminimizer_h #define __multimin_fdfminimizer_h #include <gsl/gsl_errno.h> #include <gsl/gsl_multimin.h> #include <gslwrap/vector_double.h> namespace gsl{ //! Create an instance of this class with a user defined function /*! A template class with the function operator()(const vector& x) and derivative(const vector&, vector&), as well as a reference to an object of this class must be fournished User is responsible for deleting this reference ! */ template <class fdf_function> class multimin_fdf { public: fdf_function* fct; //! These operators can be overridden virtual double operator()(const vector& x) { return (*fct)(x); } virtual void derivative(const vector& x, vector& g) { (*fct).derivative(x, g); } //! This operator can be overridden to gain performance in calculating the value and its derivative in a scoop virtual double fval_and_derivative(const vector&x, vector& g ) { derivative(x, g); return (*this)(x); } //! This is the function gsl calls to calculate the value of f at x static double f(const gsl_vector* x, void *p) { vector_view x_view(*x); return (*(multimin_fdf *)p)(x_view); } //! This is the function gsl calls to calculate the value of g=f' at x static void df(const gsl_vector* x, void *p, gsl_vector* g) { vector_view x_view(*x); vector_view g_view(*g); (*(multimin_fdf *)p).derivative(x_view, g_view); } //! This is the function gsl calls to calculate the value of g=f' at x static void fdf(const gsl_vector* x, void *p, double* f, gsl_vector* g) { vector_view x_view(*x); vector_view g_view(*g); *f=(*(multimin_fdf *)p).fval_and_derivative(x_view, g_view); } //! Constructor (User is responsible for deleting the fdf_function object) multimin_fdf(fdf_function* _fct):fct(_fct){assert (fct!=NULL);} }; //! Class for multiminimizing one dimensional functions. /*! Usage: - Create with optional multiminimize type - Set with function object and inital bounds - Loop the iterate function until convergence or maxIterations (extra facility) - Recover multiminimum and bounds */ class multimin_fdfminimizer { public: //! /*! Choose between : - gsl_multimin_fdfminimizer_conjugate_fr - gsl_multimin_fdfminimizer_conjugate_pr - gsl_multimin_fdfminimizer_vector_bfgs - gsl_multimin_fdfminimizer_steepest_descent */ multimin_fdfminimizer(uint _dim, const gsl_multimin_fdfminimizer_type* type=gsl_multimin_fdfminimizer_conjugate_fr) : dim(_dim), isSet(false), maxIterations(100), s(NULL) { s=gsl_multimin_fdfminimizer_alloc(type, dim); nIterations=0; if (!s) { //error //cout << "ERROR Couldn't allocate memory for multiminimizer" << endl; //throw ? exit(-1); } } ~multimin_fdfminimizer(){if (s) gsl_multimin_fdfminimizer_free(s);} //! returns GSL_FAILURE if the interval does not contain a multiminimum template <class fdf_function> int set(multimin_fdf<fdf_function>& function, const vector& initial_x, double step_size, double tol) { isSet=false; f.f = &function.f; f.df = &function.df; f.fdf = &function.fdf; f.n = dim; f.params = &function; int status= gsl_multimin_fdfminimizer_set(s, &f, initial_x.gslobj(), step_size, tol); if (!status) { isSet=true; nIterations=0; } return status; } int iterate() { assert_set(); int status=gsl_multimin_fdfminimizer_iterate(s); nIterations++; if (status==GSL_FAILURE) isConverged=true; return status; } int restart(){return gsl_multimin_fdfminimizer_restart(s);} double minimum(){assert_set();return gsl_multimin_fdfminimizer_minimum(s);} vector x_value(){assert_set();return vector_view(*gsl_multimin_fdfminimizer_x(s));} vector gradient(){assert_set();return vector_view(*gsl_multimin_fdfminimizer_gradient(s));} void SetMaxIterations(int n){maxIterations=n;} int GetNIterations(){return nIterations;} bool is_converged(){if (nIterations>=maxIterations) return true; if (isConverged) return true; return false;} //string name() const; private: void assert_set(){if (!isSet)exit(-1);} // Old problem of error handling: TODO uint dim; bool isSet; bool isConverged; int nIterations; int maxIterations; gsl_multimin_fdfminimizer* s; gsl_multimin_function_fdf f; }; }; // namespace gsl #endif //__multimin_fdfminimizer_h
{ "alphanum_fraction": 0.7274134262, "avg_line_length": 30.0523255814, "ext": "h", "hexsha": "3a4718d5697bbc4eb119c9024f99e7faf7e71dc3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_line_length": 111, "max_stars_count": 4, "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_path": "src/gslwrap/multimin_fdfminimizer.h", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "num_tokens": 1423, "size": 5169 }
/* * gsl_headers.h * Pi4U * * Created by Panagiotis Hadjidoukas on 1/1/14. * Copyright 2014 ETH Zurich. All rights reserved. * */ #ifndef _GSL_HEADERS_ #define _GSL_HEADERS_ 1 #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_roots.h> /* NDL */ #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_sort_vector.h> #endif
{ "alphanum_fraction": 0.7186009539, "avg_line_length": 18.5, "ext": "h", "hexsha": "5cca42acb4be6b366c6455e71672ab6667c8e535", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-11-16T16:15:49.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-16T16:15:49.000Z", "max_forks_repo_head_hexsha": "e6c256a8339e1f59d0c648370b469b2d044fde6e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "NMDimitriou/MetaGrowth", "max_forks_repo_path": "Calibration_Continuum/TMCMC/gsl_headers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e6c256a8339e1f59d0c648370b469b2d044fde6e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "NMDimitriou/MetaGrowth", "max_issues_repo_path": "Calibration_Continuum/TMCMC/gsl_headers.h", "max_line_length": 51, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e6c256a8339e1f59d0c648370b469b2d044fde6e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "NMDimitriou/MetaGrowth", "max_stars_repo_path": "Calibration_Continuum/TMCMC/gsl_headers.h", "max_stars_repo_stars_event_max_datetime": "2021-12-17T21:33:52.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-16T16:15:31.000Z", "num_tokens": 214, "size": 629 }
// // gemv.h // Linear Algebra Template Library // // Created by Rodney James on 12/12/11. // Copyright (c) 2011 University of Colorado Denver. All rights reserved. // #ifndef _gemv_h #define _gemv_h /// @file gemv.h Computes general matrix-vector products. #include <cctype> #include "latl.h" namespace LATL { /// @brief Computes general real matrix-vector products. /// /// For a real matrix A and real scalars alpha, beta /// /// y := alpha * op(A) * x + beta * y /// /// is computed, where op(A) = A or A'. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param trans Specifies whether the transpose of A is used or not: /// /// if trans = 'N' or 'n' then op(A) = A /// if trans = 'T' or 't' then op(A) = A' /// if trans = 'C' or 'c' then op(A) = A' /// /// @param m The number of rows of the matrix A. m>=0 /// @param n The number of columns of the matrix A. n>=0 /// @param alpha Real scalar. /// @param A Pointer to real matrix m-by-n matrix A. /// @param ldA Column length of the matrix A. ldA>=m. /// @param x Pointer to real vector x. /// @param incx Increment of the vector x. /// @param beta Real scalar. /// @param y Pointer to real vector y. /// @param incy Increment of the vector y. /// @ingroup BLAS template <typename real_t> int GEMV(char trans, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *x, int_t incx, real_t beta, real_t *y, int_t incy) { trans=std::toupper(trans); const real_t one(1.0); const real_t zero(0.0); int_t kx,ky,lenx,leny,i,ix,iy,j,jx,jy; real_t temp; if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; lenx=(trans=='N')?n:m; leny=(trans=='N')?m:n; kx=(incx>0)?0:(1-lenx)*incx; ky=(incy>0)?0:(1-leny)*incy; if(beta==zero) { if(incy==1) { for(i=0;i<leny;i++) y[i]=zero; } else { iy=ky; for(i=0;i<leny;i++) { y[iy]=zero; iy+=incy; } } } else if(beta!=one) { if(incy==1) { for(i=0;i<leny;i++) y[i]*=beta; } else { iy=ky; for(i=0;i<leny;i++) { y[iy]*=beta; iy+=incy; } } } if(alpha!=zero) { if(trans=='N') { jx=kx; if(incy==1) { for(j=0;j<n;j++) { temp=alpha*x[jx]; for(i=0;i<m;i++) y[i]+=temp*A[i]; A+=ldA; jx+=incx; } } else { for(j=0;j<n;j++) { temp=alpha*x[jx]; iy=ky; for(i=0;i<m;i++) { y[iy]+=temp*A[i]; iy+=incy; } A+=ldA; jx+=incx; } } } else { jy=ky; if(incx==1) { for(j=0;j<n;j++) { temp=zero; for(i=0;i<m;i++) temp+=A[i]*x[i]; y[jy]+=alpha*temp; jy+=incy; A+=ldA; } } else { for(j=0;j<n;j++) { temp=zero; ix=kx; for(i=0;i<m;i++) { temp+=A[i]*x[ix]; ix+=incx; } y[jy]+=alpha*temp; jy+=incy; A+=ldA; } } } } return 0; } /// @brief Computes general complex matrix-vector products. /// /// For a complex matrix A and complex scalars alpha, beta /// /// y := alpha * op(A) * x + beta * y /// /// is computed, where op(A) = A or A'. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param trans Specifies whether the transpose or conjugate transpose of A, or neither is used: /// /// if trans = 'N' or 'n' then op(A) = A /// if trans = 'T' or 't' then op(A) = A.' /// if trans = 'C' or 'c' then op(A) = A' /// /// @param m The number of rows of the matrix A. m>=0 /// @param n The number of columns of the matrix A. n>=0 /// @param alpha Complex scalar. /// @param A Pointer to complex matrix m-by-n matrix A. /// @param ldA Column length of the matrix A. ldA>=m. /// @param x Pointer to complex vector x. /// @param incx Increment of the vector x. /// @param beta Complex scalar. /// @param y Pointer to complex vector y. /// @param incy Increment of the vector y. /// @ingroup BLAS template <typename real_t> int GEMV(char trans, int_t m, int_t n, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *x, int_t incx, complex<real_t> beta, complex<real_t> *y, int_t incy) { trans=std::toupper(trans); using std::conj; const complex<real_t> one(1.0,0.0); const complex<real_t> zero(0.0,0.0); int_t kx,ky,lenx,leny,i,ix,iy,j,jx,jy; complex<real_t> temp; if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; lenx=(trans=='N')?n:m; leny=(trans=='N')?m:n; kx=(incx>0)?0:(1-lenx)*incx; ky=(incy>0)?0:(1-leny)*incy; if(beta==zero) { if(incy==1) { for(i=0;i<leny;i++) y[i]=zero; } else { iy=ky; for(i=0;i<leny;i++) { y[iy]=zero; iy+=incy; } } } else if(beta!=one) { if(incy==1) { for(i=0;i<leny;i++) y[i]*=beta; } else { iy=ky; for(i=0;i<leny;i++) { y[iy]*=beta; iy+=incy; } } } if(alpha!=zero) { switch(trans) { case 'N': jx=kx; if(incy==1) for(j=0;j<n;j++) { temp=alpha*x[jx]; for(i=0;i<m;i++) y[i]+=temp*A[i]; A+=ldA; jx+=incx; } else for(j=0;j<n;j++) { temp=alpha*x[jx]; iy=ky; for(i=0;i<m;i++) { y[iy]+=temp*A[i]; iy+=incy; } A+=ldA; jx+=incx; } break; case 'T': jy=ky; if(incx==1) for(j=0;j<n;j++) { temp=zero; for(i=0;i<m;i++) temp+=A[i]*x[i]; y[jy]+=alpha*temp; jy+=incy; A+=ldA; } else for(j=0;j<n;j++) { temp=zero; ix=kx; for(i=0;i<m;i++) { temp+=A[i]*x[ix]; ix+=incx; } y[jy]+=alpha*temp; jy+=incy; A+=ldA; } break; case 'C': jy=ky; if(incx==1) for(j=0;j<n;j++) { temp=zero; for(i=0;i<m;i++) temp+=conj(A[i])*x[i]; y[jy]+=alpha*temp; jy+=incy; A+=ldA; } else for(j=0;j<n;j++) { temp=zero; ix=kx; for(i=0;i<m;i++) { temp+=conj(A[i])*x[ix]; ix+=incx; } y[jy]+=alpha*temp; jy+=incy; A+=ldA; } break; } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int GEMV<float>(char trans, int_t m, int_t n, float alpha, float *A, int_t ldA, float *x, int_t incx, float beta, float *y, int_t incy) { trans=std::toupper(trans); if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_sgemv(CblasColMajor,Trans,m,n,alpha,A,ldA,x,incx,beta,y,incy); return 0; } template <> int GEMV<double>(char trans, int_t m, int_t n, double alpha, double *A, int_t ldA, double *x, int_t incx, double beta, double *y, int_t incy) { trans=std::toupper(trans); if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_dgemv(CblasColMajor,Trans,m,n,alpha,A,ldA,x,incx,beta,y,incy); return 0; } template <> int GEMV<float>(char trans, int_t m, int_t n, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *x, int_t incx, complex<float> beta, complex<float> *y, int_t incy) { trans=std::toupper(trans); if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_cgemv(CblasColMajor,Trans,m,n,&alpha,A,ldA,x,incx,&beta,y,incy); return 0; } template <> int GEMV<double>(char trans, int_t m, int_t n, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *x, int_t incx, complex<double> beta, complex<double> *y, int_t incy) { trans=std::toupper(trans); if((trans!='N')&&(trans!='T')&&(trans!='C')) return -1; else if(m<0) return -2; else if(n<0) return -3; else if(ldA<m) return -6; else if(incx==0) return -8; else if(incy==0) return -11; else if((m==0)||(n==0)) return 0; const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans); cblas_zgemv(CblasColMajor,Trans,m,n,&alpha,A,ldA,x,incx,&beta,y,incy); return 0; } #endif } #endif
{ "alphanum_fraction": 0.3983997465, "avg_line_length": 26.8004246285, "ext": "h", "hexsha": "2e59b6c432715b73b125a72d3c01f2d60efe6427", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/gemv.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/gemv.h", "max_line_length": 201, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/gemv.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 3431, "size": 12623 }
#include <sbmf/sbmf.h> #define SBMF_UNUSED(x) \ (void)x #include <omp.h> #include <cblas.h> #include <lapacke.h> #include <arpack/arpack.h> /* #include <arpack/debug_c.h> */ /* c stdlib */ #include <stdio.h> /* sprintf, fopen, fprintf, fread */ #include <stdlib.h> /* malloc */ #include <string.h> /* memcpy,memset */ #include <stdarg.h> #include <assert.h> #include <float.h> /* isinf, isnan */ /* unix headers */ #include <signal.h> #include <time.h> /* * Getting into actual code */ #include "profile.c" #include "memory/stack_allocator.c" #include "global_state.c" #include "indices.c" #include "memory/bucketarray.c" #include "memory/prioqueue.c" #include "math/functions.c" #include "math/matrix.c" #include "math/find_eigenpairs.c" #include "math/basis.c" #include "math/hermite_integrals.c" #include "methods/quadgk.c" #include "methods/nlse_solver.c" #include "methods/grosspitaevskii.c" #include "methods/best_meanfield.c" #include "methods/perturbation_theory.c" /* * Logging definitions */ #define MAX_LOG_MSG_LEN 128 void sbmf_set_log_callback(sbmf_log_callback_func* func) { _state.log_callback = func; } static void sbmf_log(enum sbmf_log_level log_level, const char* fmt, va_list args) { if (!_state.log_callback) return; static char msg_buffer[MAX_LOG_MSG_LEN]; vsnprintf(msg_buffer, MAX_LOG_MSG_LEN, fmt, args); _state.log_callback(log_level, msg_buffer); } void sbmf_log_info(const char* fmt, ...) { va_list args; va_start(args, fmt); sbmf_log(SBMF_LOG_LEVEL_INFO, fmt, args); va_end(args); } void sbmf_log_warning(const char* fmt, ...) { va_list args; va_start(args, fmt); sbmf_log(SBMF_LOG_LEVEL_WARNING, fmt, args); va_end(args); } void sbmf_log_error(const char* fmt, ...) { va_list args; va_start(args, fmt); sbmf_log(SBMF_LOG_LEVEL_ERROR, fmt, args); va_end(args); } void sbmf_log_panic(const char* fmt, ...) { va_list args; va_start(args, fmt); sbmf_log(SBMF_LOG_LEVEL_PANIC, fmt, args); va_end(args); }
{ "alphanum_fraction": 0.7211538462, "avg_line_length": 21.4782608696, "ext": "c", "hexsha": "2cb502f182b6cc27a1e8a922aca6ab764f0ea811", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AntonJohansson/sbmf", "max_forks_repo_path": "src/sbmf/sbmf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "AntonJohansson/sbmf", "max_issues_repo_path": "src/sbmf/sbmf.c", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AntonJohansson/sbmf", "max_stars_repo_path": "src/sbmf/sbmf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 538, "size": 1976 }
#include <stdio.h> #include <gsl/gsl_multifit.h> int main (int argc, char **argv) { int i, n; double xi, yi, ei, chisq; gsl_matrix *X, *cov; gsl_vector *y, *w, *c; if (argc != 2) { fprintf (stderr,"usage: fit n < data\n"); exit (-1); } n = atoi (argv[1]); X = gsl_matrix_alloc (n, 3); y = gsl_vector_alloc (n); w = gsl_vector_alloc (n); c = gsl_vector_alloc (3); cov = gsl_matrix_alloc (3, 3); for (i = 0; i < n; i++) { int count = fscanf (stdin, "%lg %lg %lg", &xi, &yi, &ei); if (count != 3) { fprintf (stderr, "error reading file\n"); exit (-1); } printf ("%g %g +/- %g\n", xi, yi, ei); gsl_matrix_set (X, i, 0, 1.0); gsl_matrix_set (X, i, 1, xi); gsl_matrix_set (X, i, 2, xi*xi); gsl_vector_set (y, i, yi); gsl_vector_set (w, i, 1.0/(ei*ei)); } { gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, 3); gsl_multifit_wlinear (X, w, y, c, cov, &chisq, work); gsl_multifit_linear_free (work); } #define C(i) (gsl_vector_get(c,(i))) #define COV(i,j) (gsl_matrix_get(cov,(i),(j))) { printf ("# best fit: Y = %g + %g X + %g X^2\n", C(0), C(1), C(2)); printf ("# covariance matrix:\n"); printf ("[ %+.5e, %+.5e, %+.5e \n", COV(0,0), COV(0,1), COV(0,2)); printf (" %+.5e, %+.5e, %+.5e \n", COV(1,0), COV(1,1), COV(1,2)); printf (" %+.5e, %+.5e, %+.5e ]\n", COV(2,0), COV(2,1), COV(2,2)); printf ("# chisq = %g\n", chisq); } gsl_matrix_free (X); gsl_vector_free (y); gsl_vector_free (w); gsl_vector_free (c); gsl_matrix_free (cov); return 0; }
{ "alphanum_fraction": 0.4813785436, "avg_line_length": 22.2098765432, "ext": "c", "hexsha": "43f8c06706a43996e9d73dcacd08e7ae50dbea43", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting2.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting2.c", "max_line_length": 52, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/fitting2.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 659, "size": 1799 }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #ifndef GSL_GSL_H #define GSL_GSL_H #include <gsl/gsl_algorithm> // copy #include <gsl/gsl_assert> // Ensures/Expects #include <gsl/gsl_byte> // byte #include <gsl/gsl_util> // finally()/narrow()/narrow_cast()... #include <gsl/multi_span> // multi_span, strided_span... #include <gsl/pointers> // owner, not_null #include <gsl/span> // span #include <gsl/string_span> // zstring, string_span, zstring_builder... #endif // GSL_GSL_H
{ "alphanum_fraction": 0.6253021757, "avg_line_length": 41.3666666667, "ext": "h", "hexsha": "55862ebdd20bd2c9c849f1b808b0df8ec8a1787a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_path": "include/gsl/gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Redchards/CVRP", "max_issues_repo_path": "include/gsl/gsl.h", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_path": "include/gsl/gsl.h", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "num_tokens": 272, "size": 1241 }
/* C functions for running vbgmm from Cython*/ /*System includes*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <sys/stat.h> #include <float.h> /*GSL includes*/ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_statistics_double.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include <pthread.h> #include <gsl/gsl_sf_exp.h> #include <omp.h> /*User includes*/ #include "c_vbgmm_fit.h" void c_vbgmm_fit (double* adX, int nN, int nD, int nK, int seed, int* anAssign, int nThreads, int nIter) { int debug = 0; int bAssign = 0; if (nIter < 1){ nIter = DEF_MAX_ITER; } driverMP(adX, nN, nD, anAssign, nK, seed, nIter, DEF_EPSILON, debug, bAssign, nThreads); return; } int driverMP(double *adX, int nN, int nD, int *anAssign, int nKStart, unsigned long lSeed, int nMaxIter, double dEpsilon, int debug, int bAssign, int nThreads) { t_Params tParams; t_Data tData; gsl_rng *ptGSLRNG = NULL; const gsl_rng_type *ptGSLRNGType = NULL; t_VBParams tVBParams; t_Cluster *ptCluster = NULL; int i = 0, nK = nKStart, nNthreads = 0; int nT = 0; char *szCOutFile = NULL; /*initialise GSL RNG*/ gsl_rng_env_setup(); gsl_set_error_handler_off(); ptGSLRNGType = gsl_rng_default; ptGSLRNG = gsl_rng_alloc(ptGSLRNGType); /*set OMP thread number*/ nNthreads = nThreads; nT = nN / 32 + 1; printf("%d %d %d\n",nN,nT,nNthreads); if (nT < nNthreads){ nNthreads = nT; } omp_set_num_threads(nNthreads); fprintf(stderr,"Setting %d OMP threads\n",nNthreads); /*set clusters params*/ tParams.nKStart = nKStart; tParams.nMaxIter = nMaxIter; tParams.dEpsilon = dEpsilon; tParams.lSeed = lSeed; fprintf(stderr,"Generate input data\n"); fflush(stderr); generateInputData(adX, nN, nD, &tData); setVBParams(&tVBParams, &tData); if(debug>0){ szCOutFile = (char *) malloc(sizeof(char)*MAX_FILE_NAME_LENGTH); sprintf(szCOutFile,"%sr%d.csv",DEF_FILE_STUB,0); } if(bAssign > 0){ nK = 0; for(i = 0; i < nN; i++){ if(anAssign[i] > nK){ nK = anAssign[i]; } } } ptCluster = malloc(sizeof(t_Cluster)); allocateCluster(ptCluster,nN,nK,nD,&tData,lSeed,nMaxIter,dEpsilon,szCOutFile); ptCluster->bAssign = bAssign; if(bAssign > 0){ for(i = 0; i < nN; i++){ ptCluster->anMaxZ[i] = anAssign[i]; } } ptCluster->ptVBParams = &tVBParams; ptCluster->nThread = 0; fitEM_MP((void *) ptCluster); compressCluster(ptCluster); calcCovarMatrices(ptCluster,&tData); for(i = 0; i < nN; i++){ anAssign[i] = ptCluster->anMaxZ[i]; } if(debug>0){ free(szCOutFile); } /*free up memory in data object*/ destroyData(&tData); /*free up best BIC clusters*/ destroyCluster(ptCluster); free(ptCluster); gsl_rng_free(ptGSLRNG); gsl_matrix_free(tVBParams.ptInvW0); return EXIT_SUCCESS; memoryError: fprintf(stderr, "Failed allocating memory in driver\n"); fflush(stderr); exit(EXIT_FAILURE); } void generateInputData(double *adX, int nN, int nD, t_Data *ptData) { double **aadX = NULL; int i = 0, j = 0; /*allocate memory for data matrix*/ aadX = (double **) malloc(nN*sizeof(double*)); if(!aadX) goto memoryError; for(i = 0; i < nN; i++){ aadX[i] = (double *) malloc(nD*sizeof(double)); if(!aadX[i]) goto memoryError; } for(i = 0; i < nN; i++){ for(j = 0; j < nD; j++){ aadX[i][j] = adX[i*nD + j]; } } ptData->nD = nD; ptData->nN = nN; ptData->aadX = aadX; return; memoryError: fprintf(stderr, "Failed allocating memory in readInputData\n"); fflush(stderr); exit(EXIT_FAILURE); } void destroyData(t_Data *ptData) { int nN = ptData->nN; int i = 0; for(i = 0; i < nN; i++){ free(ptData->aadX[i]); } free(ptData->aadX); return; } void calcSampleVar(t_Data *ptData,double *adVar, double *adMu) { double **aadX = ptData->aadX; int i = 0, n = 0; int nD = ptData->nD, nN = ptData->nN; /*sample means*/ double dN = (double) nN; for(i = 0; i < nD; i++){ adMu[i] = 0.0; adVar[i] = 0.0; } for(i = 0; i < nD; i++){ for(n = 0; n < nN; n++){ adMu[i] += aadX[n][i]; adVar[i] += aadX[n][i]*aadX[n][i]; } adMu[i] /= dN; adVar[i] = (adVar[i] - dN*adMu[i]*adMu[i])/(dN - 1.0); } return; } void setVBParams(t_VBParams *ptVBParams, t_Data *ptData) { int i = 0, nD = ptData->nD; double adVar[nD], adMu[nD]; ptVBParams->dBeta0 = DEF_BETA0; ptVBParams->dNu0 = (double) nD; ptVBParams->ptInvW0 = gsl_matrix_alloc(nD,nD); calcSampleVar(ptData,adVar, adMu); gsl_matrix_set_zero (ptVBParams->ptInvW0); for(i = 0; i < nD; i++){ double dRD = adVar[i]*((double) nD); gsl_matrix_set(ptVBParams->ptInvW0,i,i,dRD); } ptVBParams->dLogWishartB = dLogWishartB(ptVBParams->ptInvW0, nD, ptVBParams->dNu0, TRUE); } void allocateCluster(t_Cluster *ptCluster, int nN, int nK, int nD, t_Data *ptData, long lSeed, int nMaxIter, double dEpsilon, char *szCOutFile) { int i = 0, j = 0, k = 0; ptCluster->szCOutFile = szCOutFile; ptCluster->ptVBParams = NULL; ptCluster->lSeed = lSeed; ptCluster->nMaxIter = nMaxIter; ptCluster->dEpsilon = dEpsilon; ptCluster->ptData = ptData; ptCluster->nN = nN; ptCluster->nK = nK; ptCluster->nKSize = nK; ptCluster->nD = nD; ptCluster->dVBL = 0.0; ptCluster->anMaxZ = (int *) malloc(nN*sizeof(int)); /*destroyed*/ if(!ptCluster->anMaxZ) goto memoryError; ptCluster->anW = (int *) malloc(nK*sizeof(int)); /*destroyed*/ if(!ptCluster->anW) goto memoryError; for(i = 0; i < nN; i++){ ptCluster->anMaxZ[i] = NOT_SET; } for(i = 0; i < nK; i++){ ptCluster->anW[i] = 0; } ptCluster->aadZ = (double **) malloc(nN*sizeof(double *)); /*destroyed*/ if(!ptCluster->aadZ) goto memoryError; for(i = 0; i < nN; i++){ ptCluster->aadZ[i] = (double *) malloc(nK*sizeof(double)); /*destroyed*/ if(!ptCluster->aadZ[i]) goto memoryError; for(j = 0; j < nK; j++){ ptCluster->aadZ[i][j] = 0.0; } } ptCluster->adLDet = (double *) malloc(nK*sizeof(double)); /*all*/ ptCluster->adPi = (double *) malloc(nK*sizeof(double)); ptCluster->adBeta = (double *) malloc(nK*sizeof(double)); ptCluster->adNu = (double *) malloc(nK*sizeof(double)); /*destroyed*/ if(!ptCluster->adLDet || !ptCluster->adPi) goto memoryError; if(!ptCluster->adBeta || !ptCluster->adNu) goto memoryError; for(k = 0; k < nK; k++){ ptCluster->adLDet[k] = 0.0; ptCluster->adPi[k] = 0.0; ptCluster->adBeta[k] = 0.0; ptCluster->adNu[k] = 0.0; } ptCluster->aadMu = (double **) malloc(nK*sizeof(double *)); if(!ptCluster->aadMu) goto memoryError; ptCluster->aadM = (double **) malloc(nK*sizeof(double *)); if(!ptCluster->aadM) goto memoryError; for(i = 0; i < nK; i++){ ptCluster->aadM[i] = (double*) malloc (nD*sizeof(double)); if(!ptCluster->aadM[i]) goto memoryError; ptCluster->aadMu[i] = (double*) malloc (nD*sizeof(double)); if(!ptCluster->aadMu[i]) goto memoryError; } ptCluster->aptSigma = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *)); if(!ptCluster->aptSigma) goto memoryError; for(i = 0; i < nK ; i++){ ptCluster->aptSigma[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD); } ptCluster->aptCovar = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *)); if(!ptCluster->aptCovar) goto memoryError; for(i = 0; i < nK ; i++){ ptCluster->aptCovar[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD); } return; memoryError: fprintf(stderr, "Failed allocating memory in allocateCluster\n"); fflush(stderr); exit(EXIT_FAILURE); } void destroyCluster(t_Cluster* ptCluster) { int i = 0, nN = ptCluster->nN, nKSize = ptCluster->nKSize; if(ptCluster->szCOutFile != NULL){ free(ptCluster->szCOutFile); } free(ptCluster->anMaxZ); free(ptCluster->anW); for(i = 0; i < nN; i++){ free(ptCluster->aadZ[i]); } free(ptCluster->aadZ); free(ptCluster->adLDet); free(ptCluster->adPi); free(ptCluster->adBeta); free(ptCluster->adNu); for(i = 0; i < nKSize; i++){ free(ptCluster->aadMu[i]); free(ptCluster->aadM[i]); } free(ptCluster->aadMu); free(ptCluster->aadM); for(i = 0; i < nKSize ; i++){ gsl_matrix_free(ptCluster->aptSigma[i]); gsl_matrix_free(ptCluster->aptCovar[i]); } free(ptCluster->aptSigma); free(ptCluster->aptCovar); return; } void* fitEM_MP(void *pvCluster) { t_Cluster *ptCluster = (t_Cluster *) pvCluster; gsl_rng *ptGSLRNG = NULL; const gsl_rng_type *ptGSLRNGType = NULL; int i = 0, k = 0; /*initialise GSL RNG*/ ptGSLRNGType = gsl_rng_default; ptGSLRNG = gsl_rng_alloc(ptGSLRNGType); gsl_rng_set (ptGSLRNG, ptCluster->lSeed); if(ptCluster->bAssign == FALSE){ initKMeans(ptGSLRNG, ptCluster, ptCluster->ptData); } else{ for(i = 0; i < ptCluster->nN; i++){ for(k = 0; k < ptCluster->nK; k++){ ptCluster->aadZ[i][k] = 0.0; } ptCluster->aadZ[i][ptCluster->anMaxZ[i]] = 1.0; } performMStepMP(ptCluster, ptCluster->ptData); } gmmTrainVB_MP(ptCluster, ptCluster->ptData); gsl_rng_free(ptGSLRNG); return NULL; } void compressCluster(t_Cluster *ptCluster) { int i = 0, k = 0, nNewK = 0, nN = ptCluster->nN; double **aadNewZ = NULL, dN = (double) nN; for(i = 0; i < ptCluster->nK; i++){ if(ptCluster->adPi[i] > 0.0){ nNewK++; } } aadNewZ = (double **) malloc(nN*sizeof(double *)); if(!aadNewZ) goto memoryError; for(i = 0; i < nN; i++){ aadNewZ[i] = (double *) malloc(nNewK*sizeof(double)); if(!aadNewZ[i]) goto memoryError; } for(i = 0; i < nN; i++){ int nC = 0; for(k = 0; k < ptCluster->nK; k++){ if(ptCluster->adPi[k] > 0.0){ aadNewZ[i][nC] = ptCluster->aadZ[i][k]; nC++; } } } for(i = 0; i < nN; i++){ free(ptCluster->aadZ[i]); } free(ptCluster->aadZ); /*reset Z and K*/ ptCluster->aadZ = aadNewZ; ptCluster->nK = nNewK; /*recalculate Pi*/ for(k = 0; k < ptCluster->nK; k++){ ptCluster->adPi[k] = 0.0; for(i = 0; i < nN; i++){ ptCluster->adPi[k] += ptCluster->aadZ[i][k]; } ptCluster->adPi[k] /= dN; } /*assign to best clusters*/ for(i = 0; i < nN; i++){ double dMaxZ = ptCluster->aadZ[i][0]; int nMaxK = 0; for(k = 1; k < ptCluster->nK; k++){ if(ptCluster->aadZ[i][k] > dMaxZ){ nMaxK = k; dMaxZ = ptCluster->aadZ[i][k]; } } ptCluster->anMaxZ[i] = nMaxK; } for(k = 0; k < ptCluster->nK; k++){ ptCluster->anW[k] = 0; } for(i = 0; i < nN; i++){ ptCluster->anW[ptCluster->anMaxZ[i]]++; } return; memoryError: fprintf(stderr, "Failed allocating memory in main\n"); fflush(stderr); exit(EXIT_FAILURE); } double decomposeMatrix(gsl_matrix *ptSigmaMatrix, int nD) { double dDet = 0.0; int status; int l = 0; status = gsl_linalg_cholesky_decomp(ptSigmaMatrix); if(status == GSL_EDOM){ fprintf(stderr,"Failed Cholesky decomposition in decomposeMatrix\n"); fflush(stderr); exit(EXIT_FAILURE); } else{ for(l = 0; l < nD; l++){ double dT = gsl_matrix_get(ptSigmaMatrix,l,l); dDet += 2.0*log(dT); } gsl_linalg_cholesky_invert(ptSigmaMatrix); return dDet; } } double mstep(int k, double *adMu, double* adM, int nN, int nD, double** aadZ, double** aadX, double *pdBeta, double *pdNu, double *pdLDet, t_VBParams *ptVBParams, gsl_matrix *ptCovarK, gsl_matrix *ptSigmaMatrix) { double dPi = 0.0, dBeta = 0.0, dLDet = 0.0, dNu = 0.0; int i = 0, j = 0, l = 0, m = 0; double dF = 0.0; double **aadCovar = NULL; double **aadInvWK = NULL; aadCovar = (double **) malloc(nD*sizeof(double*)); if(!aadCovar) goto memoryError; for(i = 0; i < nD; i++){ aadCovar[i] = (double *) malloc(nD*sizeof(double)); if(!aadCovar[i]) goto memoryError; } aadInvWK = (double **) malloc(nD*sizeof(double*)); if(!aadInvWK) goto memoryError; for(i = 0; i < nD; i++){ aadInvWK[i] = (double *) malloc(nD*sizeof(double)); if(!aadInvWK[i]) goto memoryError; } /*recompute mixture weights and means*/ for(j = 0; j < nD; j++){ adMu[j] = 0.0; for(l = 0; l < nD; l++){ aadCovar[j][l] = 0.0; aadInvWK[j][l] = 0.0; } } for(i = 0; i < nN; i++){ if(aadZ[i][k] > MIN_Z){ dPi += aadZ[i][k]; for(j = 0; j < nD; j++){ adMu[j] += aadZ[i][k]*aadX[i][j]; } } } /*normalise means*/ if(dPi > MIN_PI){ /*Equation 10.60*/ dBeta = ptVBParams->dBeta0 + dPi; for(j = 0; j < nD; j++){ /*Equation 10.61*/ adM[j] = adMu[j]/dBeta; adMu[j] /= dPi; } dNu = ptVBParams->dNu0 + dPi; /*calculate covariance matrices*/ for(i = 0; i < nN; i++){ if(aadZ[i][k] > MIN_Z){ double adDiff[nD]; for(j = 0; j < nD; j++){ adDiff[j] = aadX[i][j] - adMu[j]; } for(l = 0; l < nD; l++){ for(m = 0; m <=l ; m++){ aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m]; } } } } for(l = 0; l < nD; l++){ for(m = l + 1; m < nD; m++){ aadCovar[l][m] = aadCovar[m][l]; } } /*save sample covariances for later use*/ for(l = 0; l < nD; l++){ for(m = 0; m < nD; m++){ double dC = aadCovar[l][m] / dPi; gsl_matrix_set(ptCovarK,l,m,dC); } } /*Now perform equation 10.62*/ dF = (ptVBParams->dBeta0*dPi)/dBeta; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m]; } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ aadCovar[l][m] /= dPi; gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } /*Implement Equation 10.65*/ dLDet = ((double) nD)*log(2.0); for(l = 0; l < nD; l++){ double dX = 0.5*(dNu - (double) l); dLDet += gsl_sf_psi (dX); } dLDet -= decomposeMatrix(ptSigmaMatrix,nD); } else{ /*Equation 10.60*/ dPi = 0.0; dBeta = ptVBParams->dBeta0; for(j = 0; j < nD; j++){ /*Equation 10.61*/ adM[j] = 0.0; adMu[j] = 0.0; } dNu = ptVBParams->dNu0; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m); } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m); } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } /*Implement Equation 10.65*/ dLDet = ((double) nD)*log(2.0); for(l = 0; l < nD; l++){ double dX = 0.5*(dNu - (double) l); dLDet += gsl_sf_psi (dX); } dLDet -= decomposeMatrix(ptSigmaMatrix,nD); } /*free up memory*/ for(i = 0; i < nD; i++){ free(aadCovar[i]); free(aadInvWK[i]); } free(aadCovar); free(aadInvWK); (*pdBeta) = dBeta; (*pdNu) = dNu; (*pdLDet) = dLDet; return dPi; memoryError: fprintf(stderr, "Failed allocating memory in mstep\n"); fflush(stderr); exit(EXIT_FAILURE); } void performMStepMP(t_Cluster *ptCluster, t_Data *ptData){ int k = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX; double **aadCovar = NULL, **aadInvWK = NULL; t_VBParams *ptVBParams = ptCluster->ptVBParams; /*perform M step*/ #pragma omp parallel for for(int k = 0; k < nK; k++){ /*loop components*/ double dPi = 0.0, dBeta = 0.0, dNu = 0.0, dLDet = 0.0; dPi = mstep(k, ptCluster->aadMu[k],ptCluster->aadM[k], nN, nD, aadZ, aadX, &dBeta, &dNu, &dLDet, ptVBParams, ptCluster->aptCovar[k], ptCluster->aptSigma[k]); ptCluster->adPi[k] = dPi; ptCluster->adBeta[k] = dBeta; ptCluster->adNu[k] = dNu; ptCluster->adLDet[k] = dLDet; } /*Normalise pi*/ if(1){ double dNP = 0.0; for(k = 0; k < nK; k++){ dNP += ptCluster->adPi[k]; } for(k = 0; k < nK; k++){ ptCluster->adPi[k] /= dNP; } } return; memoryError: fprintf(stderr, "Failed allocating memory in performMStep\n"); fflush(stderr); exit(EXIT_FAILURE); } void initKMeans(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData) { /*very simple initialisation assign each data point to random cluster*/ int i = 0, k = 0, nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadMu = ptCluster->aadMu, **aadX = ptData->aadX; int *anMaxZ = ptCluster->anMaxZ, *anW = ptCluster->anW, nChange = nN; int nIter = 0, nMaxIter = ptCluster->nMaxIter; for(i = 0; i < nN; i++){ int nIK = gsl_rng_uniform_int (ptGSLRNG, nK); ptCluster->anMaxZ[i] = nIK; anW[nIK]++; } updateMeans(ptCluster, ptData); while(nChange > 0 && nIter < nMaxIter){ nChange = 0; /*reassign vectors*/ for(i = 0; i < nN; i++){ double dMinDist = DBL_MAX; int nMinK = NOT_SET; for(k = 0; k < nK; k++){ double dDist = calcDist(aadX[i],aadMu[k],nD); if(dDist < dMinDist){ nMinK = k; dMinDist = dDist; } } if(nMinK != anMaxZ[i]){ int nCurr = anMaxZ[i]; nChange++; anW[nCurr]--; anW[nMinK]++; anMaxZ[i] = nMinK; /*check for empty clusters*/ if(anW[nCurr] == 0){ int nRandI = gsl_rng_uniform_int (ptGSLRNG, nN); int nKI = 0; /*select at random from non empty clusters*/ while(anW[anMaxZ[nRandI]] == 1){ nRandI = gsl_rng_uniform_int (ptGSLRNG, nN); } nKI = anMaxZ[nRandI]; anW[nKI]--; anW[nCurr] = 1; anMaxZ[nRandI] = nCurr; } } } //printf("%d %d\n",nIter,nChange); nIter++; updateMeans(ptCluster, ptData); } for(i = 0; i < nN; i++){ for(k = 0; k < nK; k++){ ptCluster->aadZ[i][k] = 0.0; } ptCluster->aadZ[i][anMaxZ[i]] = 1.0; } performMStepMP(ptCluster, ptData); return; } double eqnA(int nD, gsl_matrix *ptCovarK, gsl_matrix *ptSigmaK, double *adMuK, double *adMK, double dLDetK, double dNuK, double logd2Pi, double dBetaK,double dNK) { int l = 0; gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD); gsl_vector *ptDiff = gsl_vector_alloc(nD); double dT1 = 0.0, dT2 = 0.0, dF = 0.0; gsl_vector *ptR = gsl_vector_alloc(nD); double dD = (double) nD; double dRet = 0.0; gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCovarK,ptSigmaK,0.0,ptRes); for(l = 0; l < nD; l++){ dT1 += gsl_matrix_get(ptRes,l,l); } for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,adMuK[l] - adMK[l]); } gsl_blas_dsymv (CblasLower, 1.0, ptSigmaK, ptDiff, 0.0, ptR); gsl_blas_ddot (ptDiff, ptR, &dT2); dF = dLDetK - dNuK*(dT1 + dT2) - dD*(logd2Pi + (1.0/dBetaK)); dRet = 0.5*dNK*dF; gsl_matrix_free(ptRes); gsl_vector_free(ptDiff); gsl_vector_free(ptR); return dRet; } double eqnB(int nD, gsl_matrix *ptInvW0, gsl_matrix *ptSigmaK, double* adMK, double dBeta0, double d2Pi, double dLDetK, double dBetaK, double dNuK, double dNu0) { int l = 0; double dD = (double) nD; gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD); gsl_vector *ptDiff = gsl_vector_alloc(nD); gsl_vector *ptR = gsl_vector_alloc(nD); double dT1 = 0.0, dT2 = 0.0, dF = 0.0; double dRet = 0.0; gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptInvW0,ptSigmaK,0.0,ptRes); for(l = 0; l < nD; l++){ dT1 += gsl_matrix_get(ptRes,l,l); } for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,adMK[l]); } gsl_blas_dsymv (CblasLower, 1.0, ptSigmaK, ptDiff, 0.0, ptR); gsl_blas_ddot (ptDiff, ptR, &dT2); dF = dD*log(dBeta0/d2Pi) + dLDetK - ((dD*dBeta0)/dBetaK) - dBeta0*dNuK*dT2 - dNuK*dT1; dRet = 0.5*(dF + (dNu0 - dD - 1.0)*dLDetK); gsl_matrix_free(ptRes); gsl_vector_free(ptDiff); gsl_vector_free(ptR); return dRet; } double calcVBL_MP(t_Cluster* ptCluster) { int nN = ptCluster->nN; int nK = ptCluster->nK, nD = ptCluster->nD; double dBishop1 = 0.0, dBishop2 = 0.0, dBishop3 = 0.0, dBishop4 = 0.0, dBishop5 = 0.0; /*Bishop equations 10.71...*/ double dD = (double) nD; double** aadMu = ptCluster->aadMu, **aadM = ptCluster->aadM, **aadZ = ptCluster->aadZ; double* adBeta = ptCluster->adBeta, *adNu = ptCluster->adNu, *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi; double adNK[nK], adRet[nK]; double d2Pi = 2.0*M_PI, logd2Pi = log(d2Pi), dBeta0 = ptCluster->ptVBParams->dBeta0, dNu0 = ptCluster->ptVBParams->dNu0, dRet = 0.0; double dK = 0.0; for(int k = 0; k < nK; k++){ adNK[k] = 0.0; } /*Equation 10.72*/ for(int i = 0; i < nN; i++){ for(int k = 0; k < nK; k++){ adNK[k] += aadZ[i][k]; if(adPi[k] > 0.0){ dBishop2 += aadZ[i][k]*log(adPi[k]); } } } for(int k = 0; k < nK; k++){ if(adNK[k] > 0.0){ dK++; } } /*Equation 10.71*/ #pragma omp parallel for for(int k = 0; k < nK; k++){ if(adNK[k] > 0.0){ adRet[k] = eqnA(nD, ptCluster->aptCovar[k], ptCluster->aptSigma[k], aadMu[k], aadM[k], adLDet[k], adNu[k], logd2Pi, adBeta[k],adNK[k]); } else{ adRet[k] = 0.0; } } for(int k = 0; k < nK; k++){ dBishop1 += adRet[k]; } /*Equation 10.74*/ #pragma omp parallel for for(int k = 0; k < nK; k++){ if(adNK[k] > 0.0){ adRet[k] = eqnB(nD, ptCluster->ptVBParams->ptInvW0, ptCluster->aptSigma[k], aadM[k], ptCluster->ptVBParams->dBeta0, d2Pi, adLDet[k], adBeta[k], adNu[k],ptCluster->ptVBParams->dNu0); } } for(int k = 0; k < nK; k++){ dBishop3 += adRet[k]; } dBishop3 += dK*ptCluster->ptVBParams->dLogWishartB; /*Equation 10.75*/ for(int i = 0; i < nN; i++){ for(int k = 0; k < nK; k++){ if(aadZ[i][k] > 0.0){ dBishop4 += aadZ[i][k]*log(aadZ[i][k]); } } } /*Equation 10.77*/ for(int k = 0; k < nK; k++){ if(adNK[k] > 0.0){ dBishop5 += 0.5*adLDet[k] + 0.5*dD*log(adBeta[k]/d2Pi) - 0.5*dD - dWishartExpectLogDet(ptCluster->aptSigma[k], adNu[k], nD); } } dRet = dBishop1 + dBishop2 + dBishop3 - dBishop4 - dBishop5; return dRet; } void calcZ_MP(t_Cluster* ptCluster, t_Data *ptData){ double **aadX = ptData->aadX, **aadZ = ptCluster->aadZ; int nK = ptCluster->nK, nD = ptCluster->nD, nN = ptData->nN; double dD = (double) nD; double** aadM = ptCluster->aadM, *adPi = ptCluster->adPi; #pragma omp parallel for for(int i = 0; i < nN; i++){ double dMinDist = DBL_MAX; double dTotalZ = 0.0; double dNTotalZ = 0.0; double adDist[nK]; int k = 0, l = 0; gsl_vector *ptDiff = gsl_vector_alloc(nD); gsl_vector *ptRes = gsl_vector_alloc(nD); for(k = 0; k < nK; k++){ if(adPi[k] > 0.){ /*set vector to data point*/ for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,aadX[i][l] - aadM[k][l]); } gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptRes); gsl_blas_ddot (ptDiff, ptRes, &adDist[k]); adDist[k] *= ptCluster->adNu[k]; adDist[k] -= ptCluster->adLDet[k]; adDist[k] += dD/ptCluster->adBeta[k]; if(adDist[k] < dMinDist){ dMinDist = adDist[k]; } } } for(k = 0; k < nK; k++){ if(adPi[k] > 0.){ aadZ[i][k] = adPi[k]*exp(-0.5*(adDist[k]-dMinDist)); dTotalZ += aadZ[i][k]; } else{ aadZ[i][k] = 0.0; } } for(k = 0; k < nK; k++){ double dF = aadZ[i][k] / dTotalZ; if(dF < MIN_Z){ aadZ[i][k] = 0.0; } dNTotalZ += aadZ[i][k]; } if(dNTotalZ > 0.){ for(k = 0; k < nK; k++){ aadZ[i][k] /= dNTotalZ; } } gsl_vector_free(ptRes); gsl_vector_free(ptDiff); } return; } void gmmTrainVB_MP(t_Cluster *ptCluster, t_Data *ptData) { int i = 0, k = 0,nIter = 0; int nN = ptData->nN, nK = ptCluster->nK; /*change in log-likelihood*/ double dLastVBL = 0.0, dDelta = DBL_MAX; double **aadZ = ptCluster->aadZ; int nMaxIter = ptCluster->nMaxIter; double dEpsilon = ptCluster->dEpsilon; FILE *ofp = NULL; if(ptCluster->szCOutFile){ ofp = fopen(ptCluster->szCOutFile,"w"); if(!ofp){ fprintf(stderr, "Failed to open file %s in gmmTrainVB\n",ptCluster->szCOutFile); fflush(stderr); } } /*calculate data likelihood*/ calcZ_MP(ptCluster,ptData); ptCluster->dVBL = calcVBL_MP(ptCluster); while(nIter < nMaxIter && dDelta > dEpsilon){ /*update parameter estimates*/ performMStepMP(ptCluster, ptData); /*calculate responsibilities*/ calcZ_MP(ptCluster,ptData); dLastVBL = ptCluster->dVBL; ptCluster->dVBL = calcVBL_MP(ptCluster); dDelta = fabs(ptCluster->dVBL - dLastVBL); fprintf(stderr,"%d,%f,%f\n",nIter, ptCluster->dVBL, dDelta); fflush(stderr); if(ofp){ fprintf(ofp,"%d,%f,%f,",nIter, ptCluster->dVBL, dDelta); for(k = 0; k < nK-1; k++){ fprintf(ofp,"%f,",ptCluster->adPi[k]); } fprintf(ofp,"%f\n",ptCluster->adPi[nK - 1]); fflush(ofp); } nIter++; } if(ofp){ fclose(ofp); } /*assign to best clusters*/ for(i = 0; i < nN; i++){ double dMaxZ = aadZ[i][0]; int nMaxK = 0; for(k = 1; k < nK; k++){ if(aadZ[i][k] > dMaxZ){ nMaxK = k; dMaxZ = aadZ[i][k]; } } ptCluster->anMaxZ[i] = nMaxK; } return; } void calcCovarMatrices(t_Cluster *ptCluster, t_Data *ptData) { int i = 0, j = 0, k = 0, l = 0, m = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX; double *adPi = ptCluster->adPi, **aadCovar = NULL; double dN = (double) nN; aadCovar = (double **) malloc(nD*sizeof(double*)); if(!aadCovar) goto memoryError; for(i = 0; i < nD; i++){ aadCovar[i] = (double *) malloc(nD*sizeof(double)); if(!aadCovar[i]) goto memoryError; } for(k = 0; k < nK; k++){ /*loop components*/ double* adMu = ptCluster->aadMu[k]; gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k]; /*recompute mixture weights and means*/ for(j = 0; j < nD; j++){ adMu[j] = 0.0; for(l = 0; l < nD; l++){ aadCovar[j][l] = 0.0; } /*prevents singularities*/ aadCovar[j][j] = MIN_COVAR; } /* compute weight associated with component k*/ adPi[k] = 0.0; for(i = 0; i < nN; i++){ adPi[k] += aadZ[i][k]; for(j = 0; j < nD; j++){ adMu[j] += aadZ[i][k]*aadX[i][j]; } } /*normalise means*/ for(j = 0; j < nD; j++){ adMu[j] /= adPi[k]; } /*calculate covariance matrices*/ for(i = 0; i < nN; i++){ double adDiff[nD]; for(j = 0; j < nD; j++){ adDiff[j] = aadX[i][j] - adMu[j]; } for(l = 0; l < nD; l++){ for(m = 0; m <=l ; m++){ aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m]; } } } for(l = 0; l < nD; l++){ for(m = l + 1; m < nD; m++){ aadCovar[l][m] = aadCovar[m][l]; } } for(l = 0; l < nD; l++){ for(m = 0; m < nD; m++){ aadCovar[l][m] /= adPi[k]; gsl_matrix_set(ptSigmaMatrix, l, m, aadCovar[l][m]); } } adPi[k] /= dN; /*normalise weights*/ } /*free up memory*/ for(i = 0; i < nD; i++){ free(aadCovar[i]); } //gsl_matrix_free(ptSigmaMatrix); free(aadCovar); return; memoryError: fprintf(stderr, "Failed allocating memory in performMStep\n"); fflush(stderr); exit(EXIT_FAILURE); } /*note assuming you are using inverse W matrix*/ double dLogWishartB(gsl_matrix *ptInvW, int nD, double dNu, int bInv) { int i = 0; double dRet = 0.0, dT = 0.0; double dLogDet = 0.0, dD = (double) nD; gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD); gsl_matrix_memcpy(ptTemp, ptInvW); dLogDet = decomposeMatrix(ptTemp, nD); if(bInv == TRUE){ dRet = 0.5*dNu*dLogDet; } else{ dRet = -0.5*dNu*dLogDet; } dT = 0.5*dNu*dD*log(2.0); dT += 0.25*dD*(dD - 1.0)*log(M_PI); for(i = 0; i < nD; i++){ dT += gsl_sf_lngamma(0.5*(dNu - (double) i)); } gsl_matrix_free(ptTemp); return dRet - dT; } double dWishartExpectLogDet(gsl_matrix *ptW, double dNu, int nD) { int i = 0; double dRet = 0.0, dLogDet = 0.0, dD = (double) nD; gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD); gsl_matrix_memcpy(ptTemp, ptW); dLogDet = decomposeMatrix(ptW, nD); dRet = dD*log(2.0) + dLogDet; for(i = 0; i < nD; i++){ dRet += gsl_sf_psi(0.5*(dNu - (double) i)); } gsl_matrix_free(ptTemp); return dRet; } void updateMeans(t_Cluster *ptCluster, t_Data *ptData) { int i = 0, j = 0, k = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; int *anMaxZ = ptCluster->anMaxZ; int *anW = ptCluster->anW; double **aadX = ptData->aadX, **aadMu = ptCluster->aadMu; for(k = 0; k < nK; k++){ for(j = 0; j < nD; j++){ aadMu[k][j] = 0.0; } } for(i = 0; i < nN; i++){ int nZ = anMaxZ[i]; for(j = 0; j < nD; j++){ aadMu[nZ][j] += aadX[i][j]; } } for(k = 0; k < nK; k++){ /*loop components*/ /*normalise means*/ if(anW[k] > 0){ for(j = 0; j < nD; j++){ aadMu[k][j] /= (double) anW[k]; } } else{ for(j = 0; j < nD; j++){ aadMu[k][j] = 0.0; } } } return; } double calcDist(double* adX, double *adMu, int nD) { double dDist = 0.0; int i = 0; for(i = 0; i < nD; i++){ double dV = adX[i] - adMu[i]; dDist += dV*dV; } return sqrt(dDist); }
{ "alphanum_fraction": 0.5239063164, "avg_line_length": 25.1234756098, "ext": "c", "hexsha": "0d844c60a5e5424070c3a49f18d1c3521179447f", "lang": "C", "max_forks_count": 47, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:31:46.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-03T18:30:50.000Z", "max_forks_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "merenlab/CONCOCT", "max_forks_repo_path": "c-concoct/c_vbgmm_fit.c", "max_issues_count": 156, "max_issues_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:26:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:51:10.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "merenlab/CONCOCT", "max_issues_repo_path": "c-concoct/c_vbgmm_fit.c", "max_line_length": 211, "max_stars_count": 79, "max_stars_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "merenlab/CONCOCT", "max_stars_repo_path": "c-concoct/c_vbgmm_fit.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:12:15.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-16T15:08:51.000Z", "num_tokens": 11365, "size": 32962 }
/* vector/gsl_vector_ulong.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_ULONG_H__ #define __GSL_VECTOR_ULONG_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_ulong.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; unsigned long *data; gsl_block_ulong *block; int owner; } gsl_vector_ulong; typedef struct { gsl_vector_ulong vector; } _gsl_vector_ulong_view; typedef _gsl_vector_ulong_view gsl_vector_ulong_view; typedef struct { gsl_vector_ulong vector; } _gsl_vector_ulong_const_view; typedef const _gsl_vector_ulong_const_view gsl_vector_ulong_const_view; /* Allocation */ GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc (const size_t n); GSL_FUN gsl_vector_ulong *gsl_vector_ulong_calloc (const size_t n); GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_block (gsl_block_ulong * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_ulong *gsl_vector_ulong_alloc_from_vector (gsl_vector_ulong * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_ulong_free (gsl_vector_ulong * v); /* Views */ GSL_FUN _gsl_vector_ulong_view gsl_vector_ulong_view_array (unsigned long *v, size_t n); GSL_FUN _gsl_vector_ulong_view gsl_vector_ulong_view_array_with_stride (unsigned long *base, size_t stride, size_t n); GSL_FUN _gsl_vector_ulong_const_view gsl_vector_ulong_const_view_array (const unsigned long *v, size_t n); GSL_FUN _gsl_vector_ulong_const_view gsl_vector_ulong_const_view_array_with_stride (const unsigned long *base, size_t stride, size_t n); GSL_FUN _gsl_vector_ulong_view gsl_vector_ulong_subvector (gsl_vector_ulong *v, size_t i, size_t n); GSL_FUN _gsl_vector_ulong_view gsl_vector_ulong_subvector_with_stride (gsl_vector_ulong *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_ulong_const_view gsl_vector_ulong_const_subvector (const gsl_vector_ulong *v, size_t i, size_t n); GSL_FUN _gsl_vector_ulong_const_view gsl_vector_ulong_const_subvector_with_stride (const gsl_vector_ulong *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_FUN void gsl_vector_ulong_set_zero (gsl_vector_ulong * v); GSL_FUN void gsl_vector_ulong_set_all (gsl_vector_ulong * v, unsigned long x); GSL_FUN int gsl_vector_ulong_set_basis (gsl_vector_ulong * v, size_t i); GSL_FUN int gsl_vector_ulong_fread (FILE * stream, gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_fwrite (FILE * stream, const gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_fscanf (FILE * stream, gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_fprintf (FILE * stream, const gsl_vector_ulong * v, const char *format); GSL_FUN int gsl_vector_ulong_memcpy (gsl_vector_ulong * dest, const gsl_vector_ulong * src); GSL_FUN int gsl_vector_ulong_reverse (gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_swap (gsl_vector_ulong * v, gsl_vector_ulong * w); GSL_FUN int gsl_vector_ulong_swap_elements (gsl_vector_ulong * v, const size_t i, const size_t j); GSL_FUN unsigned long gsl_vector_ulong_max (const gsl_vector_ulong * v); GSL_FUN unsigned long gsl_vector_ulong_min (const gsl_vector_ulong * v); GSL_FUN void gsl_vector_ulong_minmax (const gsl_vector_ulong * v, unsigned long * min_out, unsigned long * max_out); GSL_FUN size_t gsl_vector_ulong_max_index (const gsl_vector_ulong * v); GSL_FUN size_t gsl_vector_ulong_min_index (const gsl_vector_ulong * v); GSL_FUN void gsl_vector_ulong_minmax_index (const gsl_vector_ulong * v, size_t * imin, size_t * imax); GSL_FUN int gsl_vector_ulong_add (gsl_vector_ulong * a, const gsl_vector_ulong * b); GSL_FUN int gsl_vector_ulong_sub (gsl_vector_ulong * a, const gsl_vector_ulong * b); GSL_FUN int gsl_vector_ulong_mul (gsl_vector_ulong * a, const gsl_vector_ulong * b); GSL_FUN int gsl_vector_ulong_div (gsl_vector_ulong * a, const gsl_vector_ulong * b); GSL_FUN int gsl_vector_ulong_scale (gsl_vector_ulong * a, const unsigned long x); GSL_FUN int gsl_vector_ulong_add_constant (gsl_vector_ulong * a, const double x); GSL_FUN int gsl_vector_ulong_axpby (const unsigned long alpha, const gsl_vector_ulong * x, const unsigned long beta, gsl_vector_ulong * y); GSL_FUN unsigned long gsl_vector_ulong_sum (const gsl_vector_ulong * a); GSL_FUN int gsl_vector_ulong_equal (const gsl_vector_ulong * u, const gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_isnull (const gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_ispos (const gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_isneg (const gsl_vector_ulong * v); GSL_FUN int gsl_vector_ulong_isnonneg (const gsl_vector_ulong * v); GSL_FUN INLINE_DECL unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x); GSL_FUN INLINE_DECL unsigned long * gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i); GSL_FUN INLINE_DECL const unsigned long * gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN unsigned long gsl_vector_ulong_get (const gsl_vector_ulong * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_ulong_set (gsl_vector_ulong * v, const size_t i, unsigned long x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN unsigned long * gsl_vector_ulong_ptr (gsl_vector_ulong * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (unsigned long *) (v->data + i * v->stride); } INLINE_FUN const unsigned long * gsl_vector_ulong_const_ptr (const gsl_vector_ulong * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const unsigned long *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_ULONG_H__ */
{ "alphanum_fraction": 0.6948611931, "avg_line_length": 34.8353909465, "ext": "h", "hexsha": "216b46f9e1c94481f3c1220c4b3cd00dcfce0361", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_line_length": 139, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_ulong.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 2030, "size": 8465 }
/* specfunc/gsl_sf_bessel.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #ifndef __GSL_SF_BESSEL_H__ #define __GSL_SF_BESSEL_H__ #include <stdlib.h> #include <gsl/gsl_mode.h> #include <gsl/gsl_precision.h> #include <gsl/gsl_sf_result.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* Regular Bessel Function J_0(x) * * exceptions: none */ int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_J0(const double x); /* Regular Bessel Function J_1(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_J1(const double x); /* Regular Bessel Function J_n(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result); double gsl_sf_bessel_Jn(const int n, const double x); /* Regular Bessel Function J_n(x), nmin <= n <= nmax * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array); /* Irregular Bessel function Y_0(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_Y0(const double x); /* Irregular Bessel function Y_1(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_Y1(const double x); /* Irregular Bessel function Y_n(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result); double gsl_sf_bessel_Yn(const int n,const double x); /* Irregular Bessel function Y_n(x), nmin <= n <= nmax * * x > 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array); /* Regular modified Bessel function I_0(x) * * exceptions: GSL_EOVRFLW */ int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_I0(const double x); /* Regular modified Bessel function I_1(x) * * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_I1(const double x); /* Regular modified Bessel function I_n(x) * * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result); double gsl_sf_bessel_In(const int n, const double x); /* Regular modified Bessel function I_n(x) for n=nmin,...,nmax * * nmin >=0, nmax >= nmin * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_In_array(const int nmin, const int nmax, const double x, double * result_array); /* Scaled regular modified Bessel function * exp(-|x|) I_0(x) * * exceptions: none */ int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_I0_scaled(const double x); /* Scaled regular modified Bessel function * exp(-|x|) I_1(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_I1_scaled(const double x); /* Scaled regular modified Bessel function * exp(-|x|) I_n(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result); double gsl_sf_bessel_In_scaled(const int n, const double x); /* Scaled regular modified Bessel function * exp(-|x|) I_n(x) for n=nmin,...,nmax * * nmin >=0, nmax >= nmin * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_In_scaled_array(const int nmin, const int nmax, const double x, double * result_array); /* Irregular modified Bessel function K_0(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_K0(const double x); /* Irregular modified Bessel function K_1(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_K1(const double x); /* Irregular modified Bessel function K_n(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result); double gsl_sf_bessel_Kn(const int n, const double x); /* Irregular modified Bessel function K_n(x) for n=nmin,...,nmax * * x > 0.0, nmin >=0, nmax >= nmin * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array); /* Scaled irregular modified Bessel function * exp(x) K_0(x) * * x > 0.0 * exceptions: GSL_EDOM */ int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_K0_scaled(const double x); /* Scaled irregular modified Bessel function * exp(x) K_1(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_K1_scaled(const double x); /* Scaled irregular modified Bessel function * exp(x) K_n(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result); double gsl_sf_bessel_Kn_scaled(const int n, const double x); /* Scaled irregular modified Bessel function exp(x) K_n(x) for n=nmin,...,nmax * * x > 0.0, nmin >=0, nmax >= nmin * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array); /* Regular spherical Bessel function j_0(x) = sin(x)/x * * exceptions: none */ int gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_j0(const double x); /* Regular spherical Bessel function j_1(x) = (sin(x)/x - cos(x))/x * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_j1(const double x); /* Regular spherical Bessel function j_2(x) = ((3/x^2 - 1)sin(x) - 3cos(x)/x)/x * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_j2(const double x); /* Regular spherical Bessel function j_l(x) * * l >= 0, x >= 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result); double gsl_sf_bessel_jl(const int l, const double x); /* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_jl_array(const int lmax, const double x, double * result_array); /* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax * Uses Steed's method. * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_jl_steed_array(const int lmax, const double x, double * jl_x_array); /* Irregular spherical Bessel function y_0(x) * * exceptions: none */ int gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_y0(const double x); /* Irregular spherical Bessel function y_1(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_y1(const double x); /* Irregular spherical Bessel function y_2(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_y2(const double x); /* Irregular spherical Bessel function y_l(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result); double gsl_sf_bessel_yl(const int l, const double x); /* Irregular spherical Bessel function y_l(x) for l=0,1,...,lmax * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_yl_array(const int lmax, const double x, double * result_array); /* Regular scaled modified spherical Bessel function * * Exp[-|x|] i_0(x) * * exceptions: none */ int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_i0_scaled(const double x); /* Regular scaled modified spherical Bessel function * * Exp[-|x|] i_1(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_i1_scaled(const double x); /* Regular scaled modified spherical Bessel function * * Exp[-|x|] i_2(x) * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_i2_scaled(const double x); /* Regular scaled modified spherical Bessel functions * * Exp[-|x|] i_l(x) * * i_l(x) = Sqrt[Pi/(2x)] BesselI[l+1/2,x] * * l >= 0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result); double gsl_sf_bessel_il_scaled(const int l, const double x); /* Regular scaled modified spherical Bessel functions * * Exp[-|x|] i_l(x) * for l=0,1,...,lmax * * exceptions: GSL_EUNDRFLW */ int gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array); /* Irregular scaled modified spherical Bessel function * Exp[x] k_0(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_k0_scaled(const double x); /* Irregular modified spherical Bessel function * Exp[x] k_1(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW */ int gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_k1_scaled(const double x); /* Irregular modified spherical Bessel function * Exp[x] k_2(x) * * x > 0.0 * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW */ int gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result); double gsl_sf_bessel_k2_scaled(const double x); /* Irregular modified spherical Bessel function * Exp[x] k_l[x] * * k_l(x) = Sqrt[Pi/(2x)] BesselK[l+1/2,x] * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result); double gsl_sf_bessel_kl_scaled(const int l, const double x); /* Irregular scaled modified spherical Bessel function * Exp[x] k_l(x) * * for l=0,1,...,lmax * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_kl_scaled_array(const int lmax, const double x, double * result_array); /* Regular cylindrical Bessel function J_nu(x) * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result); double gsl_sf_bessel_Jnu(const double nu, const double x); /* Irregular cylindrical Bessel function Y_nu(x) * * exceptions: */ int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result); double gsl_sf_bessel_Ynu(const double nu, const double x); /* Regular cylindrical Bessel function J_nu(x) * evaluated at a series of x values. The array * contains the x values. They are assumed to be * strictly ordered and positive. The array is * over-written with the values of J_nu(x_i). * * exceptions: GSL_EDOM, GSL_EINVAL */ int gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v); /* Scaled modified cylindrical Bessel functions * * Exp[-|x|] BesselI[nu, x] * x >= 0, nu >= 0 * * exceptions: GSL_EDOM */ int gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result); double gsl_sf_bessel_Inu_scaled(double nu, double x); /* Modified cylindrical Bessel functions * * BesselI[nu, x] * x >= 0, nu >= 0 * * exceptions: GSL_EDOM, GSL_EOVRFLW */ int gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result); double gsl_sf_bessel_Inu(double nu, double x); /* Scaled modified cylindrical Bessel functions * * Exp[+|x|] BesselK[nu, x] * x > 0, nu >= 0 * * exceptions: GSL_EDOM */ int gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result); double gsl_sf_bessel_Knu_scaled(const double nu, const double x); /* Modified cylindrical Bessel functions * * BesselK[nu, x] * x > 0, nu >= 0 * * exceptions: GSL_EDOM, GSL_EUNDRFLW */ int gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result); double gsl_sf_bessel_Knu(const double nu, const double x); /* Logarithm of modified cylindrical Bessel functions. * * Log[BesselK[nu, x]] * x > 0, nu >= 0 * * exceptions: GSL_EDOM */ int gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result); double gsl_sf_bessel_lnKnu(const double nu, const double x); /* s'th positive zero of the Bessel function J_0(x). * * exceptions: */ int gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result); double gsl_sf_bessel_zero_J0(unsigned int s); /* s'th positive zero of the Bessel function J_1(x). * * exceptions: */ int gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result); double gsl_sf_bessel_zero_J1(unsigned int s); /* s'th positive zero of the Bessel function J_nu(x). * * exceptions: */ int gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result); double gsl_sf_bessel_zero_Jnu(double nu, unsigned int s); __END_DECLS #endif /* __GSL_SF_BESSEL_H__ */
{ "alphanum_fraction": 0.7345038385, "avg_line_length": 25.6247723133, "ext": "h", "hexsha": "cf45d55d0fe660423556018dc4dc648716cf2334", "lang": "C", "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_path": "gsl/include/gsl/gsl_sf_bessel.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/gsl_sf_bessel.h", "max_line_length": 105, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0bd5b3f1e0bc5a02516e7514b2241897337334c2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "iti-luebeck/HANSE2011", "max_stars_repo_path": "include/gsl/gsl_sf_bessel.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "num_tokens": 4194, "size": 14068 }
/* eigen/jacobi.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ /* Simple linear algebra operations, operating directly * on the gsl_vector and gsl_matrix objects. These are * meant for "generic" and "small" systems. Anyone * interested in large systems will want to use more * sophisticated methods, presumably involving native * BLAS operations, specialized data representations, * or other optimizations. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "gsl_eigen.h" #define REAL double inline static void jac_rotate(gsl_matrix * a, unsigned int i, unsigned int j, unsigned int k, unsigned int l, double * g, double * h, double s, double tau) { *g = gsl_matrix_get(a, i, j); *h = gsl_matrix_get(a, k, l); gsl_matrix_set(a, i, j, (*g) - s*((*h) + (*g)*tau)); gsl_matrix_set(a, k, l, (*h) + s*((*g) - (*h)*tau)); } int gsl_eigen_jacobi(gsl_matrix * a, gsl_vector * eval, gsl_matrix * evec, unsigned int max_rot, unsigned int * nrot) { if(a->size1 != a->size2) { GSL_ERROR ("eigenproblem requires square matrix", GSL_ENOTSQR); } else if(a->size1 != evec->size1 || a->size1 != evec->size2) { GSL_ERROR ("eigenvector matrix must match input matrix", GSL_EBADLEN); } else if(a->size1 != eval->size) { GSL_ERROR ("eigenvalue vector must match input matrix", GSL_EBADLEN); } else { const unsigned int n = a->size1; unsigned int i, j, iq, ip; double t, s; REAL * b = (REAL *) malloc(n * sizeof(REAL)); REAL * z = (REAL *) malloc(n * sizeof(REAL)); if(b == 0 || z == 0) { if(b != 0) free(b); if(z != 0) free(z); GSL_ERROR ("could not allocate memory for workspace", GSL_ENOMEM); } /* Set eigenvectors to coordinate basis. */ for(ip=0; ip<n; ip++) { for(iq=0; iq<n; iq++) { gsl_matrix_set(evec, ip, iq, 0.0); } gsl_matrix_set(evec, ip, ip, 1.0); } /* Initialize eigenvalues and workspace. */ for(ip=0; ip<n; ip++) { REAL a_ipip = gsl_matrix_get(a, ip, ip); z[ip] = 0.0; b[ip] = a_ipip; gsl_vector_set(eval, ip, a_ipip); } *nrot = 0; for(i=1; i<=max_rot; i++) { REAL thresh; REAL tau; REAL g, h, c; REAL sm = 0.0; for(ip=0; ip<n-1; ip++) { for(iq=ip+1; iq<n; iq++) { sm += fabs(gsl_matrix_get(a, ip, iq)); } } if(sm == 0.0) { free(z); free(b); return GSL_SUCCESS; } if(i < 4) thresh = 0.2*sm/(n*n); else thresh = 0.0; for(ip=0; ip<n-1; ip++) { for(iq=ip+1; iq<n; iq++) { const REAL d_ip = gsl_vector_get(eval, ip); const REAL d_iq = gsl_vector_get(eval, iq); const REAL a_ipiq = gsl_matrix_get(a, ip, iq); g = 100.0 * fabs(a_ipiq); if( i > 4 && fabs(d_ip)+g == fabs(d_ip) && fabs(d_iq)+g == fabs(d_iq) ) { gsl_matrix_set(a, ip, iq, 0.0); } else if(fabs(a_ipiq) > thresh) { h = d_iq - d_ip; if(fabs(h) + g == fabs(h)) { t = a_ipiq/h; } else { REAL theta = 0.5*h/a_ipiq; t = 1.0/(fabs(theta) + sqrt(1.0 + theta*theta)); if(theta < 0.0) t = -t; } c = 1.0/sqrt(1.0+t*t); s = t*c; tau = s/(1.0+c); h = t * a_ipiq; z[ip] -= h; z[iq] += h; gsl_vector_set(eval, ip, d_ip - h); gsl_vector_set(eval, iq, d_iq + h); gsl_matrix_set(a, ip, iq, 0.0); for(j=0; j<ip; j++){ jac_rotate(a, j, ip, j, iq, &g, &h, s, tau); } for(j=ip+1; j<iq; j++){ jac_rotate(a, ip, j, j, iq, &g, &h, s, tau); } for(j=iq+1; j<n; j++){ jac_rotate(a, ip, j, iq, j, &g, &h, s, tau); } for (j=0; j<n; j++){ jac_rotate(evec, j, ip, j, iq, &g, &h, s, tau); } ++(*nrot); } } } for (ip=0; ip<n; ip++) { b[ip] += z[ip]; z[ip] = 0.0; gsl_vector_set(eval, ip, b[ip]); } /* continue iteration */ } return GSL_EMAXITER; } } int gsl_eigen_invert_jacobi(const gsl_matrix * a, gsl_matrix * ainv, unsigned int max_rot) { if(a->size1 != a->size2 || ainv->size1 != ainv->size2) { return GSL_ENOTSQR; } else if(a->size1 != ainv->size2) { return GSL_EBADLEN; } else { const unsigned int n = a->size1; unsigned int nrot; unsigned int i,j,k,l; /* This is annoying because I do not want * the error handling in these functions. * But there are no "impl"-like versions * of these allocators... sigh. */ gsl_vector * eval = gsl_vector_alloc(n); gsl_matrix * evec = gsl_matrix_alloc(n, n); gsl_matrix * inv_diag = gsl_matrix_alloc(n, n); if(eval == 0 || evec == 0 || inv_diag == 0) { if(eval != 0) gsl_vector_free(eval); if(evec != 0) gsl_matrix_free(evec); if(inv_diag != 0) gsl_matrix_free(inv_diag); return GSL_ENOMEM; } memcpy(ainv->data, a->data, n*n*sizeof(REAL)); gsl_eigen_jacobi(ainv, eval, evec, max_rot, &nrot); for(i=0; i<n; i++) { if(fabs(gsl_vector_get(eval, i)) < 100.0 * GSL_DBL_EPSILON) { /* apparent singularity */ gsl_vector_free(eval); gsl_matrix_free(evec); gsl_matrix_free(inv_diag); return GSL_ESING; } } /* Invert the diagonalized matrix. */ for(i=0; i<n; i++) { for(j=0; j<n; j++) { gsl_matrix_set(inv_diag, i, j, 0.0); } gsl_matrix_set(inv_diag, i, i, 1.0/gsl_vector_get(eval, i)); } for(i=0; i<n; i++) { for(j=0; j<n; j++) { gsl_matrix_set(ainv, i, j, 0.0); for(k=0; k<n; k++) { for(l=0; l<n; l++) { REAL ainv_ij = gsl_matrix_get(ainv, i, j); REAL evec_il = gsl_matrix_get(evec, i, l); REAL evec_jk = gsl_matrix_get(evec, j, k); REAL inv_diag_lk = gsl_matrix_get(inv_diag, l, k); REAL delta = evec_il * inv_diag_lk * evec_jk; gsl_matrix_set(ainv, i, j, ainv_ij + delta); } } } } gsl_vector_free(eval); gsl_matrix_free(evec); gsl_matrix_free(inv_diag); return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5345272012, "avg_line_length": 28.5697674419, "ext": "c", "hexsha": "e629b81a8361c3b110f2a587bb20ff719be8a9da", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/eigen/jacobi.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/eigen/jacobi.c", "max_line_length": 75, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/eigen/jacobi.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2237, "size": 7371 }
//Gets deltas (first order differences) of X. //Only the deltas are output in Y. //I implement this just like FIR for speed and shorter code, //except non-causal and mid-sample of B is 0, //so I don't explicitly make B (e.g., B[n] just equals sc*n). //It seems that Kaldi and others use the same method for edge samples, //which is numpy.edge, so that is used here. //Comment out those lines to set out-of-range samps to 0. #include <stdio.h> #include <cblas.h> #ifdef __cplusplus namespace ov { extern "C" { #endif int get_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N); int get_deltas_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int N); int get_deltas_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int N) { const float z = 0.0f; int r, c, n; float sc = 1.0f; //Checks if (R<1) { fprintf(stderr,"error in get_deltas_s: R (nrows Y) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in get_deltas_s: C (ncols Y) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in get_deltas_s: N (delta winlength) must be positive\n"); return 1; } //Get sc (normalizer) for (n=2; n<=N; n++) { sc += n*n; } sc = 0.5f/sc; //Initialize Y cblas_scopy(R*C,&z,0,&Y[0],1); if (dim==0) { if (iscolmajor) { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[c*R],0,&Y[c*R],1); //beg edge samps cblas_saxpy(R-n,-sc*n,&X[c*R],1,&Y[c*R+n],1); //past samps cblas_saxpy(R-n,sc*n,&X[c*R+n],1,&Y[c*R],1); //future samps cblas_saxpy(n,sc*n,&X[c*R+R-1],0,&Y[c*R+R-n],1); //end edge samps } } } else { for (n=1; n<=N; n++) { cblas_saxpy(C*(R-n),-sc*n,&X[0],1,&Y[n*C],1); //past samps cblas_saxpy(C*(R-n),sc*n,&X[n*C],1,&Y[0],1); //future samps for (c=0; c<C; c++) { cblas_saxpy(n,-sc*n,&X[c],0,&Y[c],C); //beg edge samps cblas_saxpy(n,sc*n,&X[c+C*(R-1)],0,&Y[c+C*(R-n)],C); //end edge samps } } } } else if (dim==1) { if (iscolmajor) { for (n=1; n<=N; n++) { cblas_saxpy(R*(C-n),-sc*n,&X[0],1,&Y[n*R],1); //past samps cblas_saxpy(R*(C-n),sc*n,&X[n*R],1,&Y[0],1); //future samps for (r=0; r<R; r++) { cblas_saxpy(n,-sc*n,&X[r],0,&Y[r],R); //beg edge samps cblas_saxpy(n,sc*n,&X[r+R*(C-1)],0,&Y[r+R*(C-n)],R); //end edge samps } } } else { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_saxpy(n,-sc*n,&X[r*C],0,&Y[r*C],1); //beg edge samps cblas_saxpy(C-n,-sc*n,&X[r*C],1,&Y[r*C+n],1); //past samps cblas_saxpy(C-n,sc*n,&X[r*C+n],1,&Y[r*C],1); //future samps cblas_saxpy(n,sc*n,&X[r*C+C-1],0,&Y[r*C+C-n],1); //end edge samps } } } } else { fprintf(stderr,"error in get_deltas_s: dim must be 0 or 1.\n"); return 1; } return 0; } int get_deltas_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int N) { const double z = 0.0; int r, c, n; double sc = 1.0; //Checks if (R<1) { fprintf(stderr,"error in get_deltas_d: R (nrows Y) must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in get_deltas_d: C (ncols Y) must be positive\n"); return 1; } if (N<1) { fprintf(stderr,"error in get_deltas_d: N (delta winlength) must be positive\n"); return 1; } //Get sc (normalizer) for (n=2; n<=N; n++) { sc += n*n; } sc = 0.5/sc; //Initialize Y cblas_dcopy(R*C,&z,0,&Y[0],1); if (dim==0) { if (iscolmajor) { for (c=0; c<C; c++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[c*R],0,&Y[c*R],1); //beg edge samps cblas_daxpy(R-n,-sc*n,&X[c*R],1,&Y[c*R+n],1); //past samps cblas_daxpy(R-n,sc*n,&X[c*R+n],1,&Y[c*R],1); //future samps cblas_daxpy(n,sc*n,&X[c*R+R-1],0,&Y[c*R+R-n],1); //end edge samps } } } else { for (n=1; n<=N; n++) { cblas_daxpy(C*(R-n),-sc*n,&X[0],1,&Y[n*C],1); //past samps cblas_daxpy(C*(R-n),sc*n,&X[n*C],1,&Y[0],1); //future samps for (c=0; c<C; c++) { cblas_daxpy(n,-sc*n,&X[c],0,&Y[c],C); //beg edge samps cblas_daxpy(n,sc*n,&X[c+C*(R-1)],0,&Y[c+C*(R-n)],C); //end edge samps } } } } else if (dim==1) { if (iscolmajor) { for (n=1; n<=N; n++) { cblas_daxpy(R*(C-n),-sc*n,&X[0],1,&Y[n*R],1); //past samps cblas_daxpy(R*(C-n),sc*n,&X[n*R],1,&Y[0],1); //future samps for (r=0; r<R; r++) { cblas_daxpy(n,-sc*n,&X[r],0,&Y[r],R); //beg edge samps cblas_daxpy(n,sc*n,&X[r+R*(C-1)],0,&Y[r+R*(C-n)],R); //end edge samps } } } else { for (r=0; r<R; r++) { for (n=1; n<=N; n++) { cblas_daxpy(n,-sc*n,&X[r*C],0,&Y[r*C],1); //beg edge samps cblas_daxpy(C-n,-sc*n,&X[r*C],1,&Y[r*C+n],1); //past samps cblas_daxpy(C-n,sc*n,&X[r*C+n],1,&Y[r*C],1); //future samps cblas_daxpy(n,sc*n,&X[r*C+C-1],0,&Y[r*C+C-n],1); //end edge samps } } } } else { fprintf(stderr,"error in get_deltas_d: dim must be 0 or 1.\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4360706063, "avg_line_length": 32.7386934673, "ext": "c", "hexsha": "f66a58f5e856ab4ad346a53c716807bc1c9252e5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_path": "c/get_deltas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/aud", "max_issues_repo_path": "c/get_deltas.c", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_path": "c/get_deltas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2167, "size": 6515 }
#ifndef __GSL_WRAPPER_H__ #define __GSL_WRAPPER_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <iostream> #include <cassert> namespace dvrlib{ struct gsl_exception { const char* reason; const char* file; int line; int gsl_errno; }; void gsl_enable_exceptions(); class vector_view; class vector { gsl_vector* v; vector(); public: vector(int n); vector(int n, double x); vector(int n, const double* x); vector(const vector& src); ~vector(); gsl_vector* gsl_internal(); const gsl_vector* gsl_internal() const; int size() const; void set(int i, double val); double get(int i) const; double operator[](int i); vector& operator=(const vector& src); vector& operator+=(const vector& src); vector operator+(const vector& src) const; vector& operator-=(const vector& src); vector operator-(const vector& src) const; vector operator-() const; vector& operator*=(double d); vector operator*(double d) const; double norm1() const; double norm2() const; vector_view subvector(int k, int n); const vector_view subvector(int k, int n) const; friend class vector_view; friend class matrix; }; vector operator*(double d, const vector& src); std::ostream& operator<<(std::ostream& out, const vector& vec); class vector_view: public vector { gsl_vector_view vv; vector_view(gsl_vector_view vv); public: vector_view(const vector_view& src); gsl_vector_view* gsl_internal(); vector_view& operator=(const vector& src); friend class vector; friend class matrix; }; class matrix_view; class matrix { gsl_matrix* m; matrix(); public: matrix(int n1, int n2, bool id=false, const double* diag=0); matrix(int n1, int n2, const double* x); template<int n> matrix(int n1, int n2, const double (*x)[n]); matrix(const matrix& src); matrix(const gsl_matrix* src); ~matrix(); gsl_matrix* gsl_internal(); const gsl_matrix* gsl_internal() const; int size1() const; int size2() const; void set(int i, int j, double val); double get(int i, int j) const; vector_view operator[](int i); matrix& operator=(const matrix& src); matrix operator+(const matrix& src) const; matrix operator+=(const matrix& src) const; matrix operator-(const matrix& src) const; matrix operator-=(const matrix& src) const; matrix operator-() const; vector operator*(const vector& src) const; matrix operator*(const matrix& src) const; matrix operator*(double d) const; matrix operator*=(double d) const; matrix transpose() const; matrix inverse() const; vector linsolve(const vector& b) const; void svd(matrix& U, matrix& V, vector& s) const; vector svd() const; matrix_view submatrix(int k1, int k2, int n1, int n2); const matrix_view submatrix(int k1, int k2, int n1, int n2) const; friend class matrix_view; }; template<int n> matrix::matrix(int n1, int n2, const double (*x)[n]) { assert(n==n2); m = gsl_matrix_alloc(n1, n2); gsl_matrix_const_view src = gsl_matrix_const_view_array(x[0], n1, n2); gsl_matrix_memcpy(m, &src.matrix); } matrix operator*(double d, const matrix& src); std::ostream& operator<<(std::ostream& out, const matrix& vec); class matrix_view: public matrix { gsl_matrix_view mv; matrix_view(gsl_matrix_view mv); public: matrix_view(const matrix_view& src); gsl_matrix_view* gsl_internal(); matrix_view& operator=(const matrix& src); friend class matrix; }; std::ostream& operator<<(std::ostream& out, const gsl_vector& v); std::ostream& operator<<(std::ostream& out, const gsl_matrix& m); std::ostream& operator<<(std::ostream& out, const gsl_matrix_view& mv); } // namespace dvrlib #endif // __GSL_WRAPPER_H__
{ "alphanum_fraction": 0.7029435593, "avg_line_length": 23.4367088608, "ext": "h", "hexsha": "b232c3b8268f49c5825937ee60eb7d6bf7f96485", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ezander/dvrlib", "max_forks_repo_path": "src/gsl_wrapper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ezander/dvrlib", "max_issues_repo_path": "src/gsl_wrapper.h", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "3fd26d5fce9e284588c1960cf4e3f7f99d2d44c5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ezander/dvrlib", "max_stars_repo_path": "src/gsl_wrapper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 990, "size": 3703 }
#ifndef S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H #define S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H #include <gsl/gsl> namespace cv { class Mat; } namespace s3d { struct StanResults; } namespace s3d { namespace image_operation { class ImageOperation { public: bool applyOnImagesIfEnabled(cv::Mat *leftImage, cv::Mat *rightImage, StanResults* results); bool isEnabled(); void enable(); void disable(); private: virtual bool applyOnImage(cv::Mat *leftImage, cv::Mat *rightImage, StanResults* results) = 0; bool isEnabled_{true}; }; } // namespace s3d } // namespace image_operation #endif // S3D_CV_IMAGE_OPERATION_IMAGE_OPERATION_H
{ "alphanum_fraction": 0.7603053435, "avg_line_length": 18.7142857143, "ext": "h", "hexsha": "3742ff8ee84267afa4f4ea74076bb1e771c3be96", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_line_length": 95, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/core/cv/include/s3d/cv/image_operation/image_operation.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 167, "size": 655 }
// // symm.h // Linear Algebra Template Library // // Created by Rodney James on 1/2/12. // Copyright (c) 2012 University of Colorado Denver. All rights reserved. // #ifndef _symm_h #define _symm_h /// @file symm.h Performs general symmetric matrix-matrix multiplication. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs general real symmetric matrix-matrix multiplication. /// /// For real matrices B and C, symmetric matrix A, and real scalars alpha and beta, /// /// C := alpha*A*B + beta*C or C := alpha*B*A + beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param side Specifies whether the matrix A appears on the left or right side as follows: /// /// if side = 'L' or 'l' then C := alpha*A*B + beta*C, /// if side = 'R' or 'r' then C := alpha*B*A + beta*C. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix A /// is to be referenced: /// /// if uplo = 'U' or 'u' then A is upper triangular, /// if uplo = 'L' or 'l' then A is lower triangular. /// @param m Specifies the number of rows of the matrices B and C. m>=0 /// @param n Specifies the number of columns of the matrices B and C. n>=0 /// @param alpha Real scalar. /// @param A Pointer to real symmetric matrix A. If side = 'L' or 'l', then A is m-by-m; /// if side = 'R' or 'r', then A is n-by-n. /// @param ldA Column length of the matrix A. If side = 'L' or 'l', ldA>=m. If side = 'R' or 'r', ldA>=n. /// @param B Pointer to real m-by-n matrix B. /// @param ldB Column length of the matrix B. ldB>=m. /// @param beta Real scalar. /// @param C Pointer to real m-by-n matrix C. /// @param ldC Column length of the matrix C. ldC>=m. /// @ingroup BLAS template <typename real_t> int SYMM(char side, char uplo, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC) { using std::toupper; const real_t zero(0.0); const real_t one(1.0); int_t i,j,k; real_t *a,*b,*c,*at,*bt; real_t s,t; side=toupper(side); uplo=toupper(uplo); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if(m<0) return -3; else if(n<0) return -4; else if(ldA<((side=='L')?m:n)) return -7; else if(ldB<m) return -9; else if(ldC<m) return -12; else if((m==0)||(n==0)||((alpha==zero)&&(beta==one))) return 0; if(alpha==zero) { c=C; for(j=0;j<n;j++) { for(i=0;i<m;i++) c[i]*=beta; c+=ldC; } } else if(side=='L') { if(uplo=='U') { b=B; c=C; for(j=0;j<n;j++) { a=A; for(i=0;i<m;i++) { t=alpha*b[i]; s=zero; for(k=0;k<i;k++) { c[k]+=t*a[k]; s+=b[k]*a[k]; } c[i]=beta*c[i]+t*a[i]+alpha*s; a+=ldA; } b+=ldB; c+=ldC; } } else { b=B; c=C; for(j=0;j<n;j++) { a=A+m*ldA; for(i=m-1;i>=0;i--) { a-=ldA; t=alpha*b[i]; s=zero; for(k=i+1;k<m;k++) { c[k]+=t*a[k]; s+=b[k]*a[k]; } c[i]=beta*c[i]+t*a[i]+alpha*s; } b+=ldB; c+=ldC; } } } else { if(uplo=='U') { a=A; c=C; b=B; for(j=0;j<n;j++) { t=alpha*a[j]; for(i=0;i<m;i++) c[i]=c[i]*beta+t*b[i]; bt=B; for(k=0;k<j;k++) { t=alpha*a[k]; for(i=0;i<m;i++) c[i]+=bt[i]*t; bt+=ldB; } at=A+(j+1)*ldA; bt=B+(j+1)*ldB; for(k=j+1;k<n;k++) { t=alpha*at[j]; for(i=0;i<m;i++) c[i]+=t*bt[i]; at+=ldA; bt+=ldB; } a+=ldA; b+=ldB; c+=ldC; } } else { a=A; c=C; b=B; for(j=0;j<n;j++) { t=alpha*a[j]; for(i=0;i<m;i++) c[i]=c[i]*beta+t*b[i]; bt=B; at=A; for(k=0;k<j;k++) { t=alpha*at[j]; for(i=0;i<m;i++) c[i]+=bt[i]*t; at+=ldA; bt+=ldB; } bt=B+(j+1)*ldB; for(k=j+1;k<n;k++) { t=alpha*at[k]; for(i=0;i<m;i++) c[i]+=t*bt[i]; bt+=ldB; } a+=ldA; b+=ldB; c+=ldC; } } } return 0; } /// @brief Performs general complex symmetric matrix-matrix multiplication. /// /// For complex matrices B and C, symmetric matrix A, and complex scalars alpha and beta, /// /// C := alpha*A*B + beta*C or C := alpha*B*A + beta*C /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param side Specifies whether the matrix A appears on the left or right side as follows: /// /// if side = 'L' or 'l' then C := alpha*A*B + beta*C, /// if side = 'R' or 'r' then C := alpha*B*A + beta*C. /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix A /// is to be referenced: /// /// if uplo = 'U' or 'u' then A is upper triangular, /// if uplo = 'L' or 'l' then A is lower triangular. /// @param m Specifies the number of rows of the matrices B and C. m>=0 /// @param n Specifies the number of columns of the matrices B and C. n>=0 /// @param alpha Complex scalar. /// @param A Pointer to complex symmetric matrix A. If side = 'L' or 'l', then A is m-by-m; /// if side = 'R' or 'r', then A is n-by-n. /// @param ldA Column length of the matrix A. If side = 'L' or 'l', ldA>=m. If side = 'R' or 'r', ldA>=n. /// @param B Pointer to complex m-by-n matrix B. /// @param ldB Column length of the matrix B. ldB>=m. /// @param beta Complex scalar. /// @param C Pointer to complex m-by-n matrix C. /// @param ldC Column length of the matrix C. ldC>=m. /// @ingroup BLAS template <typename real_t> int SYMM(char side, char uplo, int_t m, int_t n, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB, complex<real_t> beta, complex<real_t> *C, int_t ldC) { return SYMM< complex<real_t> >(side,uplo,m,n,alpha,A,ldA,B,ldB,beta,C,ldC); } #ifdef __latl_cblas #include <cblas.h> template <> int SYMM<float>(char side, char uplo, int_t m, int_t n, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC) { using std::toupper; side=toupper(side); uplo=toupper(uplo); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if(m<0) return -3; else if(n<0) return -4; else if(ldA<((side=='L')?m:n)) return -7; else if(ldB<m) return -9; else if(ldC<m) return -12; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_ssymm(CblasColMajor,Side,Uplo,m,n,alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } template <> int SYMM<double>(char side, char uplo, int_t m, int_t n, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC) { using std::toupper; side=toupper(side); uplo=toupper(uplo); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if(m<0) return -3; else if(n<0) return -4; else if(ldA<((side=='L')?m:n)) return -7; else if(ldB<m) return -9; else if(ldC<m) return -12; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_dsymm(CblasColMajor,Side,Uplo,m,n,alpha,A,ldA,B,ldB,beta,C,ldC); return 0; } template <> int SYMM<float>(char side, char uplo, int_t m, int_t n, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB, complex<float> beta, complex<float> *C, int_t ldC) { using std::toupper; side=toupper(side); uplo=toupper(uplo); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if(m<0) return -3; else if(n<0) return -4; else if(ldA<((side=='L')?m:n)) return -7; else if(ldB<m) return -9; else if(ldC<m) return -12; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_csymm(CblasColMajor,Side,Uplo,m,n,&alpha,A,ldA,B,ldB,&beta,C,ldC); return 0; } template <> int SYMM<double>(char side, char uplo, int_t m, int_t n, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB, complex<double> beta, complex<double> *C, int_t ldC) { using std::toupper; side=toupper(side); uplo=toupper(uplo); if((side!='L')&&(side!='R')) return -1; else if((uplo!='U')&&(uplo!='L')) return -2; else if(m<0) return -3; else if(n<0) return -4; else if(ldA<((side=='L')?m:n)) return -7; else if(ldB<m) return -9; else if(ldC<m) return -12; const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_zsymm(CblasColMajor,Side,Uplo,m,n,&alpha,A,ldA,B,ldB,&beta,C,ldC); return 0; } #endif } #endif
{ "alphanum_fraction": 0.4651478167, "avg_line_length": 30.0570652174, "ext": "h", "hexsha": "9306b2bac0bc8a120e9f79c54f81f19632822a5f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/symm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/symm.h", "max_line_length": 209, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/symm.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 3232, "size": 11061 }
#include <petsc.h> #include "um.h" PetscErrorCode UMInitialize(UM *mesh) { mesh->N = 0; mesh->K = 0; mesh->P = 0; mesh->loc = NULL; mesh->e = NULL; mesh->bf = NULL; mesh->ns = NULL; return 0; } PetscErrorCode UMDestroy(UM *mesh) { PetscErrorCode ierr; ierr = VecDestroy(&(mesh->loc)); CHKERRQ(ierr); ierr = ISDestroy(&(mesh->e)); CHKERRQ(ierr); ierr = ISDestroy(&(mesh->bf)); CHKERRQ(ierr); ierr = ISDestroy(&(mesh->ns)); CHKERRQ(ierr); return 0; } PetscErrorCode UMViewASCII(UM *mesh, PetscViewer viewer) { PetscErrorCode ierr; PetscInt n, k; const Node *aloc; const PetscInt *ae, *abf, *ans; ierr = PetscViewerASCIIPushSynchronized(viewer); CHKERRQ(ierr); if (mesh->loc && (mesh->N > 0)) { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%d nodes at (x,y) coordinates:\n",mesh->N); CHKERRQ(ierr); ierr = VecGetArrayRead(mesh->loc,(const PetscReal **)&aloc); CHKERRQ(ierr); for (n = 0; n < mesh->N; n++) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %3d : (%g,%g)\n", n,aloc[n].x,aloc[n].y); CHKERRQ(ierr); } ierr = VecRestoreArrayRead(mesh->loc,(const PetscReal **)&aloc); CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"node coordinates empty or unallocated\n"); CHKERRQ(ierr); } if (mesh->e && (mesh->K > 0)) { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%d elements:\n",mesh->K); CHKERRQ(ierr); ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr); for (k = 0; k < mesh->K; k++) { ierr = PetscPrintf(PETSC_COMM_WORLD," %3d : %3d %3d %3d\n", k,ae[3*k+0],ae[3*k+1],ae[3*k+2]); CHKERRQ(ierr); } ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"element index triples empty or unallocated\n"); CHKERRQ(ierr); } if (mesh->bf && (mesh->N > 0)) { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%d boundary flags at nodes (0 = interior, 1 = boundary, 2 = Dirichlet):\n",mesh->N); CHKERRQ(ierr); ierr = ISGetIndices(mesh->bf,&abf); CHKERRQ(ierr); for (n = 0; n < mesh->N; n++) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %3d : %1d\n", n,abf[n]); CHKERRQ(ierr); } ierr = ISRestoreIndices(mesh->bf,&abf); CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"boundary flags empty or unallocated\n"); CHKERRQ(ierr); } if (mesh->ns && (mesh->P > 0)) { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"%d Neumann boundary segments:\n",mesh->P); CHKERRQ(ierr); ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr); for (n = 0; n < mesh->P; n++) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %3d : %3d %3d\n", n,ans[2*n+0],ans[2*n+1]); CHKERRQ(ierr); } ierr = ISRestoreIndices(mesh->ns,&ans); CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer,"Neumann boundary segments empty or unallocated\n"); CHKERRQ(ierr); } ierr = PetscViewerASCIIPopSynchronized(viewer); CHKERRQ(ierr); return 0; } PetscErrorCode UMViewSolutionBinary(UM *mesh, char *filename, Vec u) { PetscErrorCode ierr; PetscInt Nu; PetscViewer viewer; ierr = VecGetSize(u,&Nu); CHKERRQ(ierr); if (Nu != mesh->N) { SETERRQ2(PETSC_COMM_SELF,1, "incompatible sizes of u (=%d) and number of nodes (=%d)\n",Nu,mesh->N); } ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr); ierr = VecView(u,viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); return 0; } PetscErrorCode UMReadNodes(UM *mesh, char *filename) { PetscErrorCode ierr; PetscInt twoN; PetscViewer viewer; if (mesh->N > 0) { SETERRQ(PETSC_COMM_SELF,1,"nodes already created?\n"); } ierr = VecCreate(PETSC_COMM_WORLD,&mesh->loc); CHKERRQ(ierr); ierr = VecSetFromOptions(mesh->loc); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer); CHKERRQ(ierr); ierr = VecLoad(mesh->loc,viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); ierr = VecGetSize(mesh->loc,&twoN); CHKERRQ(ierr); if (twoN % 2 != 0) { SETERRQ1(PETSC_COMM_SELF,2,"node locations loaded from %s are not N pairs\n",filename); } mesh->N = twoN / 2; return 0; } PetscErrorCode UMCheckElements(UM *mesh) { PetscErrorCode ierr; const PetscInt *ae; PetscInt k, m; if ((mesh->K == 0) || (mesh->e == NULL)) { SETERRQ(PETSC_COMM_SELF,1, "number of elements unknown; call UMReadElements() first\n"); } if (mesh->N == 0) { SETERRQ(PETSC_COMM_SELF,2, "node size unknown so element check impossible; call UMReadNodes() first\n"); } ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr); for (k = 0; k < mesh->K; k++) { for (m = 0; m < 3; m++) { if ((ae[3*k+m] < 0) || (ae[3*k+m] >= mesh->N)) { SETERRQ3(PETSC_COMM_SELF,3, "index e[%d]=%d invalid: not between 0 and N-1=%d\n", 3*k+m,ae[3*k+m],mesh->N-1); } } // FIXME: could add check for distinct indices } ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr); return 0; } PetscErrorCode UMCheckBoundaryData(UM *mesh) { PetscErrorCode ierr; const PetscInt *ans, *abf; PetscInt n, m; if (mesh->N == 0) { SETERRQ(PETSC_COMM_SELF,2, "node size unknown so boundary flag check impossible; call UMReadNodes() first\n"); } if (mesh->bf == NULL) { SETERRQ(PETSC_COMM_SELF,1, "boundary flags at nodes not allocated; call UMReadNodes() first\n"); } if ((mesh->P > 0) && (mesh->ns == NULL)) { SETERRQ(PETSC_COMM_SELF,3, "inconsistent data for Neumann boundary segments\n"); } ierr = ISGetIndices(mesh->bf,&abf); CHKERRQ(ierr); for (n = 0; n < mesh->N; n++) { switch (abf[n]) { case 0 : case 1 : case 2 : break; default : SETERRQ2(PETSC_COMM_SELF,5, "boundary flag bf[%d]=%d invalid: not in {0,1,2}\n", n,abf[n]); } } ierr = ISRestoreIndices(mesh->bf,&abf); CHKERRQ(ierr); if (mesh->P > 0) { ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr); for (n = 0; n < mesh->P; n++) { for (m = 0; m < 2; m++) { if ((ans[2*n+m] < 0) || (ans[2*n+m] >= mesh->N)) { SETERRQ3(PETSC_COMM_SELF,6, "index ns[%d]=%d invalid: not between 0 and N-1=%d\n", 2*n+m,ans[3*n+m],mesh->N-1); } } } ierr = ISRestoreIndices(mesh->ns,&ans); CHKERRQ(ierr); } return 0; } PetscErrorCode UMReadISs(UM *mesh, char *filename) { PetscErrorCode ierr; PetscViewer viewer; PetscInt n_bf; if ((!mesh->loc) || (mesh->N == 0)) { SETERRQ(PETSC_COMM_SELF,2, "node coordinates not created ... do that first ... stopping\n"); } if ((mesh->K > 0) || (mesh->P > 0) || (mesh->e != NULL) || (mesh->bf != NULL) || (mesh->ns != NULL)) { SETERRQ(PETSC_COMM_SELF,1, "elements, boundary flags, Neumann boundary segments already created? ... stopping\n"); } ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer); CHKERRQ(ierr); // create and load e ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->e)); CHKERRQ(ierr); ierr = ISLoad(mesh->e,viewer); CHKERRQ(ierr); ierr = ISGetSize(mesh->e,&(mesh->K)); CHKERRQ(ierr); if (mesh->K % 3 != 0) { SETERRQ1(PETSC_COMM_SELF,3, "IS e loaded from %s is wrong size for list of element triples\n",filename); } mesh->K /= 3; // create and load bf ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->bf)); CHKERRQ(ierr); ierr = ISLoad(mesh->bf,viewer); CHKERRQ(ierr); ierr = ISGetSize(mesh->bf,&n_bf); CHKERRQ(ierr); if (n_bf != mesh->N) { SETERRQ1(PETSC_COMM_SELF,4, "IS bf loaded from %s is wrong size for list of boundary flags\n",filename); } // FIXME seems there is no way to tell if file is empty at this point // create and load ns last ... may *start with a negative value* in which case set P = 0 const PetscInt *ans; ierr = ISCreate(PETSC_COMM_WORLD,&(mesh->ns)); CHKERRQ(ierr); ierr = ISLoad(mesh->ns,viewer); CHKERRQ(ierr); ierr = ISGetIndices(mesh->ns,&ans); CHKERRQ(ierr); if (ans[0] < 0) { ISDestroy(&(mesh->ns)); mesh->ns = NULL; mesh->P = 0; } else { ierr = ISGetSize(mesh->ns,&(mesh->P)); CHKERRQ(ierr); if (mesh->P % 2 != 0) { SETERRQ1(PETSC_COMM_SELF,4, "IS s loaded from %s is wrong size for list of Neumann boundary segment pairs\n",filename); } mesh->P /= 2; } ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); // check that mesh is complete now ierr = UMCheckElements(mesh); CHKERRQ(ierr); ierr = UMCheckBoundaryData(mesh); CHKERRQ(ierr); return 0; } PetscErrorCode UMStats(UM *mesh, PetscReal *maxh, PetscReal *meanh, PetscReal *maxa, PetscReal *meana) { PetscErrorCode ierr; const PetscInt *ae; const Node *aloc; PetscInt k; PetscReal x[3], y[3], ax, ay, bx, by, cx, cy, h, a, Maxh = 0.0, Maxa = 0.0, Sumh = 0.0, Suma = 0.0; if ((mesh->K == 0) || (mesh->e == NULL)) { SETERRQ(PETSC_COMM_SELF,1, "number of elements unknown; call UMReadElements() first\n"); } if (mesh->N == 0) { SETERRQ(PETSC_COMM_SELF,2, "node size unknown so element check impossible; call UMReadNodes() first\n"); } ierr = UMGetNodeCoordArrayRead(mesh,&aloc); CHKERRQ(ierr); ierr = ISGetIndices(mesh->e,&ae); CHKERRQ(ierr); for (k = 0; k < mesh->K; k++) { x[0] = aloc[ae[3*k]].x; y[0] = aloc[ae[3*k]].y; x[1] = aloc[ae[3*k+1]].x; y[1] = aloc[ae[3*k+1]].y; x[2] = aloc[ae[3*k+2]].x; y[2] = aloc[ae[3*k+2]].y; ax = x[1] - x[0]; ay = y[1] - y[0]; bx = x[2] - x[0]; by = y[2] - y[0]; cx = x[1] - x[2]; cy = y[1] - y[2]; h = PetscMax(ax*ax+ay*ay, PetscMax(bx*bx+by*by, cx*cx+cy*cy)); h = sqrt(h); a = 0.5 * PetscAbs(ax*by-ay*bx); Maxh = PetscMax(Maxh,h); Sumh += h; Maxa = PetscMax(Maxa,a); Suma += a; } ierr = ISRestoreIndices(mesh->e,&ae); CHKERRQ(ierr); ierr = UMRestoreNodeCoordArrayRead(mesh,&aloc); CHKERRQ(ierr); if (maxh) *maxh = Maxh; if (maxa) *maxa = Maxa; if (meanh) *meanh = Sumh / mesh->K; if (meana) *meana = Suma / mesh->K; return 0; } PetscErrorCode UMGetNodeCoordArrayRead(UM *mesh, const Node **xy) { PetscErrorCode ierr; if ((!mesh->loc) || (mesh->N == 0)) { SETERRQ(PETSC_COMM_SELF,1,"node coordinates not created ... stopping\n"); } ierr = VecGetArrayRead(mesh->loc,(const PetscReal **)xy); CHKERRQ(ierr); return 0; } PetscErrorCode UMRestoreNodeCoordArrayRead(UM *mesh, const Node **xy) { PetscErrorCode ierr; if ((!mesh->loc) || (mesh->N == 0)) { SETERRQ(PETSC_COMM_SELF,1,"node coordinates not created ... stopping\n"); } ierr = VecRestoreArrayRead(mesh->loc,(const PetscReal **)xy); CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.5624685982, "avg_line_length": 38.0318471338, "ext": "c", "hexsha": "2727b71c06be474ef85a2ad1603069a066e67925", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch10/um.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch10/um.c", "max_line_length": 157, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch10/um.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 3590, "size": 11942 }
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdbool.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <functions.h> #define FOR(i,n) for(i=0;i<n;i++) typedef double DD, LD; typedef long LL; void quicksort_mds(double* x, long first, long last) { long pivot, j, i; double temp; if (first<last) { pivot = first; i = first; j = last; while (i<j) { while (x[i]<=x[pivot] && i<last) i++; while (x[j]>x[pivot]) j--; if (i<j) { temp = x[i]; x[i] = x[j]; x[j] = temp; } } temp = x[pivot]; x[pivot] = x[j]; x[j] = temp; quicksort(x, first, j - 1); quicksort(x, j + 1, last); } } void find_eigen(double **mat, int n, double*** res_vec, double** res_val) { int i, j; double *data = (double*)calloc(((long)(n*n)), sizeof(double)); double *eig_values = (double*)calloc(n, sizeof(double)); double** eig_vec = (double**)calloc(n, sizeof(double*)); for (i = 0; i<n; i++)eig_vec[i] = (double*)calloc(n, sizeof(double)); for (i = 0; i<n; i++) { for (j = 0; j<n; j++) { data[i*n + j] = mat[i][j]; } } gsl_matrix_view m= gsl_matrix_view_array(data, n, n); gsl_vector *eval = gsl_vector_alloc(n); gsl_matrix *evec = gsl_matrix_alloc(n, n); gsl_eigen_symmv_workspace * w =gsl_eigen_symmv_alloc(n); gsl_eigen_symmv(&m.matrix, eval, evec, w); gsl_eigen_symmv_free(w); gsl_eigen_symmv_sort(eval, evec,GSL_EIGEN_SORT_VAL_ASC); for (i = 0; i<n; i++) { eig_values[i] = gsl_vector_get(eval, i); for (j = 0; j<n; j++) { eig_vec[i][j] = gsl_matrix_get(evec, i, j); } } *res_val = eig_values; *res_vec = eig_vec; gsl_vector_free(eval); gsl_matrix_free(evec); free(data); } DD** Multiply_Matrices_mds(DD **Mat1, DD **Mat2, LL M, LL Q, LL P) { LL i, c, d, k; DD Sum = 0; DD** Temp = (DD**)calloc(M, sizeof(DD*)); FOR(i, M)Temp[i] = (DD*)calloc(Q, sizeof(DD)); FOR(c, M) { FOR(d, Q) { FOR(k, P) { Sum += (Mat1[c][k] * Mat2[k][d]); } Temp[c][d] = Sum; Sum = 0; } } return Temp; } double ** H_mat(long n) { long i, j; DD** k = (DD**)calloc(n, sizeof(DD*)); FOR(i, n) { k[i] = (DD*)calloc(n, sizeof(DD)); } FOR(i, n){ FOR(j, n){ k[i][j] = (i == j) ? (1.00 - 1.00 / n) : (-1.00 / n); } } return k; } typedef struct{ MAT Y; DD* eigen; LL number; } Output_mds; Output_mds MDS(DD** D,long rows,long columns, DD delta) { // ************** function to calculate Classical Multidimensional Scaling ************* long i, j, n; DD **H, **new_D, **K, **new_k; new_D = (DD**)calloc(rows, sizeof(DD*)); n = max(rows, columns); FOR(i, rows) { new_D[i] = (DD*)calloc(columns, sizeof(DD)); } if (delta >= 0) { H = H_mat(n); new_k = (DD**)calloc(n, sizeof(DD*)); FOR(i, rows) { new_k[i] = (DD*)calloc(n, sizeof(DD)); } FOR(i, rows) { FOR(j, columns) new_D[i][j] = -0.5*D[i][j]; } K = Multiply_Matrices_mds(Multiply_Matrices_mds(H, new_D, n, columns, n), H, columns, n, n); FOR(i,rows)free(new_D[i]);free(new_D); FOR(i,n)free(H[i]);free(H); DD* idx = (DD*)calloc(n, sizeof(DD)); DD ** temp, *val; FOR(i, n) { idx[i] = n - i; FOR(j, rows) new_k[i][j] = (K[i][j] + K[j][i]) / 2; } find_eigen(new_k, n, &temp, &val); find_eigen(new_k, n, &temp, &val); j = n - 1; for (i = 0; i < n / 2; i++) { DD temporary = val[i]; val[i] = val[j]; val[j] = temporary; j--; } LL* keep; DD max_val = val[0]; LL magn_keep = 0; FOR(i, n){ if (val[i] > max_val)max_val = val[i]; } max_val = max_val*exp(-10); FOR(i, n){ if (val[i] > max_val)magn_keep++; } keep = (LL*)calloc(magn_keep, sizeof(LL)); magn_keep = 0; FOR(i, n){ if (val[i] > max_val){ keep[magn_keep++] = i; } } DD** V = (DD**)calloc(n, sizeof(DD*)); DD** mult_V = (DD**)calloc(magn_keep, sizeof(DD*)); FOR(i, n)V[i] = (DD*)calloc(magn_keep, sizeof(DD)); FOR(i, magn_keep) { mult_V[i] = (DD*)calloc(magn_keep, sizeof(DD)); FOR(j, n) { if (j < magn_keep) { if (i != j)mult_V[i][j] = 0; else mult_V[i][j] = sqrt(val[keep[i]]); } V[j][i] = temp[j][(int)idx[keep[i]]-1]; } } V = Multiply_Matrices_mds(V, mult_V, n, magn_keep, magn_keep); MAT return_MAT; return_MAT.matrix = V; return_MAT.rows = n; return_MAT.columns = magn_keep; Output_mds t; t.Y = return_MAT; t.eigen = val; t.number=n; return t; } Output_mds t; return t; }
{ "alphanum_fraction": 0.5304054054, "avg_line_length": 22.0279069767, "ext": "c", "hexsha": "3c4eb6d323ad1492019d53b499a14fbe65e10a60", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vaibhav9518/FaceReck-", "max_forks_repo_path": "src/MDS.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "vaibhav9518/FaceReck-", "max_issues_repo_path": "src/MDS.c", "max_line_length": 95, "max_stars_count": 5, "max_stars_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vaibhav9518/FaceReck-", "max_stars_repo_path": "src/MDS.c", "max_stars_repo_stars_event_max_datetime": "2019-06-27T12:22:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-27T19:53:14.000Z", "num_tokens": 1720, "size": 4736 }
/* linalg/test_qr_band.c * * Copyright (C) 2020 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_test.h> #include <gsl/gsl_math.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_permutation.h> static int test_QR_band_decomp_eps(const size_t p, const size_t q, const gsl_matrix * A, const double eps, const char * desc) { int s = 0; const size_t M = A->size1; const size_t N = A->size2; size_t i, j; gsl_matrix * AB = gsl_matrix_alloc(N, 2*p + q + 1); gsl_vector * tau = gsl_vector_alloc(N); gsl_matrix * Q = gsl_matrix_alloc(M, M); gsl_matrix * R = gsl_matrix_alloc(M, N); gsl_matrix * B = gsl_matrix_alloc(M, N); /* convert A to packed banded format */ gen2band_matrix(p, q, A, AB); #if 0 print_octave(A, "A"); printqrb_octave(M, p, q, AB, "AB"); #endif s += gsl_linalg_QR_band_decomp_L2(M, p, q, AB, tau); s += gsl_linalg_QR_band_unpack_L2(p, q, AB, tau, Q, R); #if 0 printqrb_octave(M, p, q, AB, "QR"); printv_octave(tau, "tau"); print_octave(Q, "Q"); print_octave(R, "R"); #endif /* compute B = Q R */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, Q, R, 0.0, B); for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double aij = gsl_matrix_get(A, i, j); double bij = gsl_matrix_get(B, i, j); gsl_test_rel(bij, aij, eps, "%s (M=%3lu,N=%3lu)(p=%3lu,q=%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, p, q, i, j, aij, bij); } } gsl_matrix_free(AB); gsl_vector_free(tau); gsl_matrix_free(Q); gsl_matrix_free(R); gsl_matrix_free(B); return s; } static int test_QR_band_decomp(gsl_rng * r) { int s = 0; const size_t N_max = 20; size_t M, N, p, q; /*M = 7; N = 6; p = 2; q = 1;*/ for (M = 1; M <= N_max; ++M) { for (N = 1; N <= N_max; ++N) { gsl_matrix * A = gsl_matrix_alloc(M, N); for (p = 0; p < GSL_MIN(M, 10); ++p) { for (q = 0; q < GSL_MIN(N, 10); ++q) { create_band_matrix(p, q, A, r); s += test_QR_band_decomp_eps(p, q, A, 1.0e5 * GSL_MAX(M,N) * GSL_DBL_EPSILON, "QR_band_decomp random"); } } gsl_matrix_free(A); } } return s; } #if 0 static int test_QR_band_decomp(void) { int f; int s = 0; f = test_QR_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp m(3,5)"); s += f; f = test_QR_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp m(5,3)"); s += f; f = test_QR_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(2)"); s += f; f = test_QR_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(3)"); s += f; f = test_QR_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(4)"); s += f; f = test_QR_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(12)"); s += f; f = test_QR_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(2)"); s += f; f = test_QR_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(3)"); s += f; f = test_QR_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(4)"); s += f; f = test_QR_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */ gsl_test(f, " QR_decomp vander(12)"); s += f; return s; } #endif
{ "alphanum_fraction": 0.6112514351, "avg_line_length": 26.0778443114, "ext": "c", "hexsha": "d7f4d7a1f7daddeac25764713a414a2c8cfb6fbf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr_band.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr_band.c", "max_line_length": 121, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr_band.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1521, "size": 4355 }
#pragma once #include <nextalign/nextalign.h> #include <gsl/string_span> #include <string> #include <vector> template<typename Letter> using SequenceSpan = gsl::basic_string_span<Letter, gsl::dynamic_extent>; using NucleotideSequenceSpan = SequenceSpan<Nucleotide>; using AminoacidSequenceSpan = SequenceSpan<Aminoacid>; Nucleotide toNucleotide(char nuc); Nucleotide stringToNuc(const std::string& nuc); char nucToChar(Nucleotide nuc); std::string nucToString(Nucleotide nuc); Aminoacid charToAa(char aa); Aminoacid stringToAa(const std::string& aa); char aaToChar(Aminoacid aa); std::string aaToString(Aminoacid aa); template<typename Letter> struct LetterTag {}; template<typename Letter> inline Letter stringToLetter(const std::string& str, LetterTag<Letter>); template<> inline Nucleotide stringToLetter<Nucleotide>(const std::string& str, LetterTag<Nucleotide>) { return stringToNuc(str); } template<> inline Aminoacid stringToLetter<Aminoacid>(const std::string& str, LetterTag<Aminoacid>) { return stringToAa(str); } template<typename Letter> inline std::string letterToString(Letter letter); template<> inline std::string letterToString(Nucleotide letter) { return nucToString(letter); } template<> inline std::string letterToString(Aminoacid letter) { return aaToString(letter); } std::vector<Insertion> toInsertionsExternal(const std::vector<InsertionInternal<Nucleotide>>& insertions); std::vector<Peptide> toPeptidesExternal(const std::vector<PeptideInternal>& peptides); std::vector<RefPeptide> toRefPeptidesExternal(const std::vector<RefPeptideInternal>& peptides); inline std::ostream& operator<<(std::ostream& os, const Nucleotide& nuc) { os << "'" << nucToString(nuc) << "'"; return os; } inline std::ostream& operator<<(std::ostream& os, const NucleotideSequence& seq) { os << "\""; for (const auto& nuc : seq) { os << nucToString(nuc); } os << "\""; return os; } inline std::ostream& operator<<(std::ostream& os, const Aminoacid& aa) { os << "'" << aaToString(aa) << "'"; return os; } inline std::ostream& operator<<(std::ostream& os, const AminoacidSequence& seq) { os << "\""; for (const auto& aa : seq) { os << aaToString(aa); } os << "\""; return os; } inline std::ostream& operator<<(std::ostream& os, const Range& f) { os << "{ " << f.begin << ", " << f.end << " }"; return os; } inline std::ostream& operator<<(std::ostream& os, const FrameShiftContext& f) { os << "{ " // << "codon: " << f.codon << ", "// << "}" // ; return os; } inline std::ostream& operator<<(std::ostream& os, const FrameShiftResult& f) { os << "{ " // << "geneName: \"" << f.geneName << "\", " // << "nucRel: " << f.nucRel << ", " // << "nucAbs: " << f.nucAbs << ", " // << "codon: " << f.codon << ", " // << "gapsLeading: " << f.gapsLeading << ", " // << "gapsTrailing: " << f.gapsTrailing << ", "// << "}" // ; return os; }
{ "alphanum_fraction": 0.6239616613, "avg_line_length": 25.04, "ext": "h", "hexsha": "a98fd1945577e1c8fff6b06620dc83a08da70d7f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "neherlab/nextclade", "max_forks_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "neherlab/nextclade", "max_issues_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a76752eb9dbed0ee44592e708f3b146e8df2410", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "neherlab/nextclade", "max_stars_repo_path": "packages/nextalign/include/nextalign/private/nextalign_private.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 838, "size": 3130 }
/* specfunc/bessel_Kn.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_psi.h> #include <gsl/gsl_sf_bessel.h> #include "error.h" #include "bessel.h" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* [Abramowitz+Stegun, 9.6.11] * assumes n >= 1 */ static int bessel_Kn_scaled_small_x(const int n, const double x, gsl_sf_result * result) { int k; double y = 0.25 * x * x; double ln_x_2 = log(0.5*x); double ex = exp(x); gsl_sf_result ln_nm1_fact; double k_term; double term1, sum1, ln_pre1; double term2, sum2, pre2; gsl_sf_lnfact_e((unsigned int)(n-1), &ln_nm1_fact); ln_pre1 = -n*ln_x_2 + ln_nm1_fact.val; if(ln_pre1 > GSL_LOG_DBL_MAX - 3.0) GSL_ERROR ("error", GSL_EOVRFLW); sum1 = 1.0; k_term = 1.0; for(k=1; k<=n-1; k++) { k_term *= -y/(k * (n-k)); sum1 += k_term; } term1 = 0.5 * exp(ln_pre1) * sum1; pre2 = 0.5 * exp(n*ln_x_2); if(pre2 > 0.0) { const int KMAX = 20; gsl_sf_result psi_n; gsl_sf_result npk_fact; double yk = 1.0; double k_fact = 1.0; double psi_kp1 = -M_EULER; double psi_npkp1; gsl_sf_psi_int_e(n, &psi_n); gsl_sf_fact_e((unsigned int)n, &npk_fact); psi_npkp1 = psi_n.val + 1.0/n; sum2 = (psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/npk_fact.val; for(k=1; k<KMAX; k++) { psi_kp1 += 1.0/k; psi_npkp1 += 1.0/(n+k); k_fact *= k; npk_fact.val *= n+k; yk *= y; k_term = yk*(psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/(k_fact*npk_fact.val); sum2 += k_term; } term2 = ( GSL_IS_ODD(n) ? -1.0 : 1.0 ) * pre2 * sum2; } else { term2 = 0.0; } result->val = ex * (term1 + term2); result->err = ex * GSL_DBL_EPSILON * (fabs(ln_pre1)*fabs(term1) + fabs(term2)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result) { n = abs(n); /* K(-n, z) = K(n, z) */ /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(n == 0) { return gsl_sf_bessel_K0_scaled_e(x, result); } else if(n == 1) { return gsl_sf_bessel_K1_scaled_e(x, result); } else if(x <= 5.0) { return bessel_Kn_scaled_small_x(n, x, result); } else if(GSL_ROOT3_DBL_EPSILON * x > 0.25 * (n*n + 1)) { return gsl_sf_bessel_Knu_scaled_asympx_e((double)n, x, result); } else if(GSL_MIN(0.29/(n*n), 0.5/(n*n + x*x)) < GSL_ROOT3_DBL_EPSILON) { return gsl_sf_bessel_Knu_scaled_asymp_unif_e((double)n, x, result); } else { /* Upward recurrence. [Gradshteyn + Ryzhik, 8.471.1] */ double two_over_x = 2.0/x; gsl_sf_result r_b_jm1; gsl_sf_result r_b_j; int stat_0 = gsl_sf_bessel_K0_scaled_e(x, &r_b_jm1); int stat_1 = gsl_sf_bessel_K1_scaled_e(x, &r_b_j); double b_jm1 = r_b_jm1.val; double b_j = r_b_j.val; double b_jp1; int j; for(j=1; j<n; j++) { b_jp1 = b_jm1 + j * two_over_x * b_j; b_jm1 = b_j; b_j = b_jp1; } result->val = b_j; result->err = n * (fabs(b_j) * (fabs(r_b_jm1.err/r_b_jm1.val) + fabs(r_b_j.err/r_b_j.val))); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_0, stat_1); } } int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result) { const int status = gsl_sf_bessel_Kn_scaled_e(n, x, result); const double ex = exp(-x); result->val *= ex; result->err *= ex; result->err += x * GSL_DBL_EPSILON * fabs(result->val); return status; } int gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array) { /* CHECK_POINTER(result_array) */ if(nmin < 0 || nmax < nmin || x <= 0.0) { int j; for(j=0; j<=nmax-nmin; j++) result_array[j] = 0.0; GSL_ERROR ("domain error", GSL_EDOM); } else if(nmax == 0) { gsl_sf_result b; int stat = gsl_sf_bessel_K0_scaled_e(x, &b); result_array[0] = b.val; return stat; } else { double two_over_x = 2.0/x; gsl_sf_result r_Knm1; gsl_sf_result r_Kn; int stat_0 = gsl_sf_bessel_Kn_scaled_e(nmin, x, &r_Knm1); int stat_1 = gsl_sf_bessel_Kn_scaled_e(nmin+1, x, &r_Kn); int stat = GSL_ERROR_SELECT_2(stat_0, stat_1); double Knp1; double Kn = r_Kn.val; double Knm1 = r_Knm1.val; int n; for(n=nmin+1; n<=nmax+1; n++) { if(Knm1 < GSL_DBL_MAX) { result_array[n-1-nmin] = Knm1; Knp1 = Knm1 + n * two_over_x * Kn; Knm1 = Kn; Kn = Knp1; } else { /* Overflow. Set the rest of the elements to * zero and bug out. * FIXME: Note: this relies on the convention * that the test x < DBL_MIN fails for x not * a number. This may be only an IEEE convention, * so the portability is unclear. */ int j; for(j=n; j<=nmax+1; j++) result_array[j-1-nmin] = 0.0; GSL_ERROR ("overflow", GSL_EOVRFLW); } } return stat; } } int gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array) { int status = gsl_sf_bessel_Kn_scaled_array(nmin, nmax, x, result_array); double ex = exp(-x); int i; for(i=0; i<=nmax-nmin; i++) result_array[i] *= ex; return status; } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_Kn_scaled(const int n, const double x) { EVAL_RESULT(gsl_sf_bessel_Kn_scaled_e(n, x, &result)); } double gsl_sf_bessel_Kn(const int n, const double x) { EVAL_RESULT(gsl_sf_bessel_Kn_e(n, x, &result)); }
{ "alphanum_fraction": 0.6182094082, "avg_line_length": 27.3443983402, "ext": "c", "hexsha": "2ccf460d11a5635dd951bdfa2e67347311d51676", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Kn.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Kn.c", "max_line_length": 104, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Kn.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2307, "size": 6590 }
#include "gemm.h" #if defined(USE_BLAS) #include <cblas.h> #else // see https://github.com/pjreddie/darknet/blob/master/src/gemm.c static void gemm_nn(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i; #pragma omp parallel for for (i = 0; i < M; ++i) { int j, k; for (k = 0; k < K; ++k) { float A_PART = ALPHA * A[i * lda + k]; for (j = 0; j < N; ++j) { C[i * ldc + j] += A_PART * B[k * ldb + j]; } } } } static void gemm_nt(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i; #pragma omp parallel for for (i = 0; i < M; ++i) { int j, k; for (j = 0; j < N; ++j) { float sum = 0; for (k = 0; k < K; ++k) { sum += ALPHA * A[i * lda + k] * B[j * ldb + k]; } C[i * ldc + j] += sum; } } } static void gemm_tn(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i; #pragma omp parallel for for (i = 0; i < M; ++i) { int j, k; for (k = 0; k < K; ++k) { float A_PART = ALPHA * A[k * lda + i]; for (j = 0; j < N; ++j) { C[i * ldc + j] += A_PART * B[k * ldb + j]; } } } } static void gemm_tt(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { int i; #pragma omp parallel for for (i = 0; i < M; ++i) { int j, k; for (j = 0; j < N; ++j) { float sum = 0; for (k = 0; k < K; ++k) { sum += ALPHA * A[i + k * lda] * B[k + j * ldb]; } C[i * ldc + j] += sum; } } } #endif void gemm(int TA, int TB, int M, int N, int K, float ALPHA, data_val_t **A, int offa, int lda, data_val_t **B, int offb, int ldb, float BETA, data_val_t **C, int offc, int ldc) { #if defined(USE_BLAS) cblas_sgemm( CblasRowMajor, TA ? CblasTrans : CblasNoTrans, TB ? CblasTrans : CblasNoTrans, M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, BETA, *C + offc, ldc); #else int i, j; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { (*C + offc)[i * ldc + j] *= BETA; } } if (!TA && !TB) gemm_nn(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc); else if (TA && !TB) gemm_tn(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc); else if (!TA && TB) gemm_nt(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc); else gemm_tt(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc); #endif }
{ "alphanum_fraction": 0.3916325889, "avg_line_length": 25.432, "ext": "c", "hexsha": "709666ac616b354fa5dd876dd41a07c4e8d21926", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "yang-le/cnet", "max_forks_repo_path": "core/gemm.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_issues_repo_issues_event_max_datetime": "2018-03-01T14:52:50.000Z", "max_issues_repo_issues_event_min_datetime": "2018-02-28T14:40:42.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "yang-le/cnet", "max_issues_repo_path": "core/gemm.c", "max_line_length": 80, "max_stars_count": 4, "max_stars_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "yang-le/cnet", "max_stars_repo_path": "core/gemm.c", "max_stars_repo_stars_event_max_datetime": "2020-08-05T05:07:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-06T13:57:23.000Z", "num_tokens": 1042, "size": 3179 }
/* gsl-sprng.h Code declaring a new GSL random number type "gsl_rng_sprng20" which is a thin wrapper over the SPRNG 2.0 parallel random number generator. To use, just add the line: #include "gsl-sprng.h" immediately after the line: #include <gsl/gsl_rng.h> near the start of your code. The new type should now be available. Make sure you alloc the rng on each processor. If you wish to set a seed, you should set it to be the same on each processor. Darren Wilkinson d.j.wilkinson@ncl.ac.uk http://www.staff.ncl.ac.uk/d.j.wilkinson/ Last updated: 28/8/2002 */ #define SIMPLE_SPRNG #define USE_MPI #include "sprng.h" static void sprng_set(void * vstate,unsigned long int s) { init_sprng(DEFAULT_RNG_TYPE,s,SPRNG_DEFAULT); } static unsigned long sprng_get(void * vstate) { return( (long) isprng() ); } static double sprng_get_double(void * vstate) { return( (double) sprng()); } static const gsl_rng_type sprng_type = {"sprng20", /* name */ 0x7fffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ 0, /* size of state - not sure about this */ &sprng_set, /* initialisation */ &sprng_get, /* get integer RN */ &sprng_get_double}; /* get double RN */ const gsl_rng_type *gsl_rng_sprng20 = &sprng_type; /* eof */
{ "alphanum_fraction": 0.6787365177, "avg_line_length": 23.1785714286, "ext": "h", "hexsha": "b0a3cb1303407788e485a36bdee65e2f2dceffab", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yuanfangtardis/vscode_project", "max_forks_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "yuanfangtardis/vscode_project", "max_issues_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_line_length": 66, "max_stars_count": null, "max_stars_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yuanfangtardis/vscode_project", "max_stars_repo_path": "Externals/PolyChord/gsl-sprng.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 370, "size": 1298 }
#include <gsl/gsl_sf_hyperg.h> #define kl 2 #define ll 3 #define alpha 1 double potential(double x) { return 0.5 * pow(alpha, 2) * (kl * (kl - 1) / pow(sin(alpha * x), 2) + ll * (ll - 1) / pow(cos(alpha * x), 2)); } double ground_state_energy() { return 0.5 * pow(alpha, 2) * pow(kl + ll, 2); } double exact(double x) { return pow(cos(alpha * x), ll) * pow(sin(alpha * x), kl) / sqrt(3.0 * M_PI / 512.0); } #undef V0 #undef kl #undef ll #undef alpha
{ "alphanum_fraction": 0.5690721649, "avg_line_length": 22.0454545455, "ext": "h", "hexsha": "051556f888518cc9a20d2a8920ea7bbae1ecb6b1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "slrodini/nnDE_public", "max_forks_repo_path": "inc/sin_potential.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "slrodini/nnDE_public", "max_issues_repo_path": "inc/sin_potential.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "49d02c4c8a36993613aabc8b76b85537ebda6c82", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "slrodini/nnDE_public", "max_stars_repo_path": "inc/sin_potential.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 171, "size": 485 }
/* * Library: ransampl (random number sampling) * * File: sampling1.c * * Contents: Draw samples from a given discrete probability distribution; * specifically: draw representative inhabitants of the nine states * * Note: Any modification of this example should be copied to * the manual page source ransampl.pod and to the wiki. * * Author: Joachim Wuttke 2013 * * Licence: see ../COPYING (FreeBSD) * * Homepage: apps.jcns.fz-juelich.de/ransampl */ #include <stdio.h> #include <gsl/gsl_rng.h> #include "ransampl.h" #define RANSAMPL_SHALL_REVEAL_ITS_INTERNALS 1 int main() { const int M=1000000; int i, m; // Discrete probability distribution example: const int n = 9; // states of Austria const char* names[] = { "Wien", "Niederoesterreich", "Oberoesterreich", "Tirol", "Kaernten", "Salzburg", "Vorarlberg", "Burgenland", "Steiermark" }; // inhabitants in millions as of 2011 according to www.statistik.at double p[] = { 1.721573, 1.614661, 1.415020, .711161, .558056, .532713, .370833, .285377, .1211506 }; // Initialize random number generator: gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc( gsl_rng_default ); // Allocate workspace, and precompute tables: printf( "Precomputing tables ...\n" ); ransampl_ws* ws = ransampl_alloc( n ); ransampl_set( ws, p ); #ifdef RANSAMPL_SHALL_REVEAL_ITS_INTERNALS // Inspect tables: printf( " %-3s %-3s %-9s\n", "i", "alias", "prob" ); for ( int i=0; i<n; ++i ) printf( " %3i %3i %9.7f\n", i, ws->alias[i], ws->prob[i] ); #endif // Draw M random samples; accumulate statistic in histogram 'cumul': printf( "Drawing %i samples ...\n", M ); double cumul[n]; for ( i=0; i<n; ++i ) cumul[i] = 0; for ( m=0; m<M; ++m ) { i = ransampl_draw( ws, gsl_rng_uniform(rng), gsl_rng_uniform(rng) ); cumul[i] += 1; } // Print given probability and obtained frequency: printf( "Result (input->output):\n"); double sum = 0; for ( int i=0; i<n; ++i ) sum += p[i]; printf( " %-18s %-9s %-9s %-9s\n", "state", "N (Mio.)", "rel", "sim" ); for ( int i=0; i<n; ++i ) printf( " %-18s %9.7f %9.7f %9.7f\n", names[i], p[i], p[i]/sum, ((double)cumul[i])/M ); // Free workspace and terminate: ransampl_free( ws ); return 0; }
{ "alphanum_fraction": 0.5889070147, "avg_line_length": 30.65, "ext": "c", "hexsha": "c879bd9ab8c0f62114a0000a5d7c6f457ba8c498", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1817f4d4007c019178a966c7d66f20ed14598a82", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rmaganza/parsec-improved", "max_forks_repo_path": "ransampl-1.1/demo/sampling1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1817f4d4007c019178a966c7d66f20ed14598a82", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rmaganza/parsec-improved", "max_issues_repo_path": "ransampl-1.1/demo/sampling1.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "1817f4d4007c019178a966c7d66f20ed14598a82", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rmaganza/parsec-improved", "max_stars_repo_path": "ransampl-1.1/demo/sampling1.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 782, "size": 2452 }
#ifndef MATRIX_H_ #define MATRIX_H_ #include "matrix_funcs.h" #ifdef NUMPY_INTERFACE #include <Python.h> #include <arrayobject.h> #endif #include <limits> #include <assert.h> #include <stdio.h> #include <string.h> #ifdef USE_MKL #include <mkl.h> #include <mkl_cblas.h> #include <mkl_vsl.h> #include <mkl_vml.h> #define IS_MKL true #ifdef DOUBLE_PRECISION #define MKL_UNIFORM vdRngUniform #define MKL_NORMAL vdRngGaussian #define MKL_UNIFORM_RND_METHOD VSL_METHOD_DUNIFORM_STD_ACCURATE #define MKL_GAUSSIAN_RND_METHOD VSL_METHOD_DGAUSSIAN_BOXMULLER #define MKL_EXP vdExp #define MKL_RECIP vdInv #define MKL_SQUARE vdSqr #define MKL_TANH vdTanh #define MKL_LOG vdLn #define MKL_VECMUL vdMul #define MKL_VECDIV vdDiv #else #define MKL_UNIFORM vsRngUniform #define MKL_NORMAL vsRngGaussian #define MKL_UNIFORM_RND_METHOD VSL_METHOD_SUNIFORM_STD_ACCURATE #define MKL_GAUSSIAN_RND_METHOD VSL_METHOD_SGAUSSIAN_BOXMULLER #define MKL_EXP vsExp #define MKL_RECIP vsInv #define MKL_SQUARE vsSqr #define MKL_TANH vsTanh #define MKL_LOG vsLn #define MKL_VECMUL vsMul #define MKL_VECDIV vsDiv #endif /* DOUBLE_PRECISION */ #else #include <cblas.h> #define IS_MKL false #endif /* USE_MKL */ #ifdef DOUBLE_PRECISION #define CBLAS_GEMM cblas_dgemm #define CBLAS_SCAL cblas_dscal #define CBLAS_AXPY cblas_daxpy #else #define CBLAS_GEMM cblas_sgemm #define CBLAS_SCAL cblas_sscal #define CBLAS_AXPY cblas_saxpy #endif /* DOUBLE_PRECISION */ #define MTYPE_MAX numeric_limits<MTYPE>::max() class Matrix { private: MTYPE* _data; bool _ownsData; int _numRows, _numCols; int _numElements; int _numDataBytes; CBLAS_TRANSPOSE _trans; void _init(MTYPE* data, int numRows, int numCols, bool transpose, bool ownsData); void _tileTo2(Matrix& target) const; void _copyAllTo(Matrix& target) const; MTYPE _sum_column(int col) const; MTYPE _sum_row(int row) const; MTYPE _aggregate(MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; void _aggregate(int axis, Matrix& target, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; MTYPE _aggregateRow(int row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; MTYPE _aggregateCol(int row, MTYPE(*agg_func)(MTYPE, MTYPE), MTYPE initialValue) const; void _updateDims(int numRows, int numCols); void _applyLoop(MTYPE(*func)(MTYPE)); void _applyLoop(MTYPE (*func)(MTYPE), Matrix& target); void _applyLoop2(const Matrix& a, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const; void _applyLoop2(const Matrix& a, MTYPE (*func)(MTYPE,MTYPE, MTYPE), MTYPE scalar, Matrix& target) const; void _applyLoopScalar(const MTYPE scalar, MTYPE(*func)(MTYPE, MTYPE), Matrix& target) const; void _checkBounds(int startRow, int endRow, int startCol, int endCol) const; void _divideByVector(const Matrix& vec, Matrix& target); inline int _getNumColsBackEnd() const { return _trans == CblasNoTrans ? _numCols : _numRows; } public: enum FUNCTION { TANH, RECIPROCAL, SQUARE, ABS, EXP, LOG, ZERO, ONE, LOGISTIC1, LOGISTIC2 }; Matrix(); Matrix(int numRows, int numCols); #ifdef NUMPY_INTERFACE Matrix(const PyArrayObject *src); #endif Matrix(const Matrix &like); Matrix(MTYPE* data, int numRows, int numCols); Matrix(MTYPE* data, int numRows, int numCols, bool transpose); ~Matrix(); inline MTYPE& getCell(int i, int j) const { // assert(i >= 0 && i < _numRows); // assert(j >= 0 && j < _numCols); if (_trans == CblasTrans) { return _data[j * _numRows + i]; } return _data[i * _numCols + j]; } MTYPE& operator()(int i, int j) const { return getCell(i, j); } inline MTYPE* getData() const { return _data; } inline bool isView() const { return !_ownsData; } inline int getNumRows() const { return _numRows; } inline int getNumCols() const { return _numCols; } inline int getNumDataBytes() const { return _numDataBytes; } inline int getNumElements() const { return _numElements; } inline CBLAS_TRANSPOSE getBLASTrans() const { return _trans; } inline bool isSameDims(const Matrix& a) const { return a.getNumRows() == getNumRows() && a.getNumCols() == getNumCols(); } inline bool isTrans() const { return _trans == CblasTrans; } /* * Only use if you know what you're doing! * Does not update any dimensions. Just flips the _trans flag. * * Use transpose() if you want to get the transpose of this matrix. */ inline void setTrans(bool trans) { _trans = trans ? CblasTrans : CblasNoTrans; } void apply(FUNCTION f); void apply(Matrix::FUNCTION f, Matrix& target); void subtractFromScalar(MTYPE scalar); void subtractFromScalar(MTYPE scalar, Matrix &target) const; void biggerThanScalar(MTYPE scalar); void smallerThanScalar(MTYPE scalar); void equalsScalar(MTYPE scalar); void biggerThanScalar(MTYPE scalar, Matrix& target) const; void smallerThanScalar(MTYPE scalar, Matrix& target) const; void equalsScalar(MTYPE scalar, Matrix& target) const; void biggerThan(Matrix& a); void biggerThan(Matrix& a, Matrix& target) const; void smallerThan(Matrix& a); void smallerThan(Matrix& a, Matrix& target) const; void minWith(Matrix &a); void minWith(Matrix &a, Matrix &target) const; void maxWith(Matrix &a); void maxWith(Matrix &a, Matrix &target) const; void equals(Matrix& a); void equals(Matrix& a, Matrix& target) const; void notEquals(Matrix& a) ; void notEquals(Matrix& a, Matrix& target) const; void add(const Matrix &m); void add(const Matrix &m, MTYPE scale); void add(const Matrix &m, Matrix& target); void add(const Matrix &m, MTYPE scale, Matrix& target); void subtract(const Matrix &m); void subtract(const Matrix &m, Matrix& target); void subtract(const Matrix &m, MTYPE scale); void subtract(const Matrix &m, MTYPE scale, Matrix& target); void addVector(const Matrix& vec, MTYPE scale); void addVector(const Matrix& vec, MTYPE scale, Matrix& target); void addVector(const Matrix& vec); void addVector(const Matrix& vec, Matrix& target); void addScalar(MTYPE scalar); void addScalar(MTYPE scalar, Matrix& target) const; void maxWithScalar(MTYPE scalar); void maxWithScalar(MTYPE scalar, Matrix &target) const; void minWithScalar(MTYPE scalar); void minWithScalar(MTYPE scalar, Matrix &target) const; void eltWiseMultByVector(const Matrix& vec); void eltWiseMultByVector(const Matrix& vec, Matrix& target); void eltWiseDivideByVector(const Matrix& vec); void eltWiseDivideByVector(const Matrix& vec, Matrix& target); void resize(int newNumRows, int newNumCols); void resize(const Matrix& like); Matrix& slice(int startRow, int endRow, int startCol, int endCol) const; void slice(int startRow, int endRow, int startCol, int endCol, Matrix &target) const; Matrix& sliceRows(int startRow, int endRow) const; void sliceRows(int startRow, int endRow, Matrix& target) const; Matrix& sliceCols(int startCol, int endCol) const; void sliceCols(int startCol, int endCol, Matrix& target) const; void rightMult(const Matrix &b, MTYPE scale); void rightMult(const Matrix &b, Matrix &target) const; void rightMult(const Matrix &b); void rightMult(const Matrix &b, MTYPE scaleAB, Matrix &target) const; void addProduct(const Matrix &a, const Matrix &b, MTYPE scaleAB, MTYPE scaleThis); void addProduct(const Matrix& a, const Matrix& b); void eltWiseMult(const Matrix& a); void eltWiseMult(const Matrix& a, Matrix& target) const; void eltWiseDivide(const Matrix& a); void eltWiseDivide(const Matrix& a, Matrix &target) const; Matrix& transpose() const; Matrix& transpose(bool hard) const; Matrix& tile(int timesY, int timesX) const; void tile(int timesY, int timesX, Matrix& target) const; void copy(Matrix &dest, int srcStartRow, int srcEndRow, int srcStartCol, int srcEndCol, int destStartRow, int destStartCol) const; Matrix& copy() const; void copy(Matrix& target) const; Matrix& sum(int axis) const; void sum(int axis, Matrix &target) const; MTYPE sum() const; MTYPE max() const; Matrix& max(int axis) const; void max(int axis, Matrix& target) const; MTYPE min() const; Matrix& min(int axis) const; void min(int axis, Matrix& target) const; void scale(MTYPE scale); #ifdef USE_MKL void randomizeNormal(VSLStreamStatePtr stream, MTYPE mean, MTYPE stdev); void randomizeUniform(VSLStreamStatePtr stream); void randomizeNormal(VSLStreamStatePtr stream); #else void randomizeNormal(MTYPE mean, MTYPE stdev); void randomizeUniform(); void randomizeNormal(); #endif void print() const; void print(int startRow,int rows, int startCol,int cols) const; void print(int rows, int cols) const; }; #endif /* MATRIX_H_ */
{ "alphanum_fraction": 0.7051578137, "avg_line_length": 34.8390804598, "ext": "h", "hexsha": "20e2e5b6a06a53249056a9c1f7a75015b28b7d17", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "barapa/HF-RNN", "max_forks_repo_path": "cudamat/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "barapa/HF-RNN", "max_issues_repo_path": "cudamat/matrix.h", "max_line_length": 134, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0cd375dc2f5e7919cb3bac6f60cb088cf0333520", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "barapa/HF-RNN", "max_stars_repo_path": "cudamat/matrix.h", "max_stars_repo_stars_event_max_datetime": "2015-04-15T20:20:39.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-15T20:20:39.000Z", "num_tokens": 2480, "size": 9093 }
#ifndef Utilities_H #define Utilities_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multiroots.h> #include <gsl/gsl_multimin.h> #include <string> #include "SM_cxSM.h" #include "Phases.h" double MAX(double x[3],int Number); // For finding the critical points int CriticalF(const gsl_vector * x, void *model, gsl_vector * f); int CriticalDF(const gsl_vector * x, void *model, gsl_matrix *J); int CriticalFDF(const gsl_vector * x, void *model, gsl_vector * f, gsl_matrix * J); // int FindCriticalPointsSingle(CXSM *model, double *res, int MAXITER=1000, bool usingdf=true); int FindCriticalPoints(CXSM *model, double *res, std::string &logs, int MAXITER=1000, bool usingdf=true); int FindCriticalPointsZ2(CXSM *model, double *res,std::string &logs, int MAXITER=1000, bool usingdf=true); // For finding the minimum struct MinParam { CXSM *model; double T; }; bool CloseToEachOther(double a, double b); double MinF(const gsl_vector * x, void *param); void MinDF(const gsl_vector * x, void *param, gsl_vector *df); void MinFDF(const gsl_vector * x, void *param, double *f, gsl_vector * df); int FindPhasesSingle(CXSM *model, double T, double StartingPoints[2], double Results[2], int MAXITER, bool usingdf); int FindPhases(CXSM *model, double T, Phases *modelPhase, int MAXITER=500, bool usingdf=true); int FindPhasesZ2(CXSM *model, double T, Phases *modelPhase, int MAXITER, bool usingdf); #endif
{ "alphanum_fraction": 0.748951049, "avg_line_length": 43.3333333333, "ext": "h", "hexsha": "1bda852f80bccf9abfb06355b98972f7615165b2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d09fa5023e14a5286ae49aa951cd35ea0e2e53d2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ycwu1030/cxSMScan", "max_forks_repo_path": "cxSMThermalMassOnly/include/Utilities.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d09fa5023e14a5286ae49aa951cd35ea0e2e53d2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ycwu1030/cxSMScan", "max_issues_repo_path": "cxSMThermalMassOnly/include/Utilities.h", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "d09fa5023e14a5286ae49aa951cd35ea0e2e53d2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ycwu1030/cxSMScan", "max_stars_repo_path": "cxSMThermalMassOnly/include/Utilities.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 414, "size": 1430 }
/* itersolve.c * * Copyright (C) 2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_spblas.h> #include <gsl/gsl_splinalg.h> gsl_splinalg_itersolve * gsl_splinalg_itersolve_alloc(const gsl_splinalg_itersolve_type *T, const size_t n, const size_t m) { gsl_splinalg_itersolve *w; w = calloc(1, sizeof(gsl_splinalg_itersolve)); if (w == NULL) { GSL_ERROR_NULL("failed to allocate space for itersolve struct", GSL_ENOMEM); } w->type = T; w->normr = 0.0; w->state = w->type->alloc(n, m); if (w->state == NULL) { gsl_splinalg_itersolve_free(w); GSL_ERROR_NULL("failed to allocate space for itersolve state", GSL_ENOMEM); } return w; } /* gsl_splinalg_itersolve_alloc() */ void gsl_splinalg_itersolve_free(gsl_splinalg_itersolve *w) { RETURN_IF_NULL(w); if (w->state) w->type->free(w->state); free(w); } const char * gsl_splinalg_itersolve_name(const gsl_splinalg_itersolve *w) { return w->type->name; } int gsl_splinalg_itersolve_iterate(const gsl_spmatrix *A, const gsl_vector *b, const double tol, gsl_vector *x, gsl_splinalg_itersolve *w) { int status = w->type->iterate(A, b, tol, x, w->state); /* store current residual */ w->normr = w->type->normr(w->state); return status; } double gsl_splinalg_itersolve_normr(const gsl_splinalg_itersolve *w) { return w->normr; }
{ "alphanum_fraction": 0.6771186441, "avg_line_length": 25.9340659341, "ext": "c", "hexsha": "6cac8ac8033aeb2369a9fde62df205e049bac0f3", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/itersolve.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/itersolve.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/splinalg/itersolve.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 650, "size": 2360 }
static char help[] = "Example ablateCore Client using incompressible flow"; /** Example Argumetns -dm_plex_separate_marker -dm_refine 0 \ -vel_petscspace_degree 2 -pres_petscspace_degree 1 -temp_petscspace_degree 1 \ -dmts_check .001 -ts_max_steps 4 -ts_dt 0.1 \ -ksp_type fgmres -ksp_gmres_restart 10 -ksp_rtol 1.0e-9 -ksp_error_if_not_converged \ -pc_type fieldsplit -pc_fieldsplit_0_fields 0,2 -pc_fieldsplit_1_fields 1 -pc_fieldsplit_type schur -pc_fieldsplit_schur_factorization_type full \ -fieldsplit_0_pc_type lu \ -fieldsplit_pressure_ksp_rtol 1e-10 -fieldsplit_pressure_pc_type jacobi */ #include <petsc.h> #include "flow.h" #include "incompressibleFlow.h" #include "mesh.h" typedef PetscErrorCode (*ExactFunction)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); typedef void (*IntegrandTestFunction)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt *uOff, const PetscInt *uOff_x, const PetscScalar *u, const PetscScalar *u_t, const PetscScalar *u_x, const PetscInt *aOff, const PetscInt *aOff_x, const PetscScalar *a, const PetscScalar *a_t, const PetscScalar *a_x, PetscReal t, const PetscReal *X, PetscInt numConstants, const PetscScalar *constants, PetscScalar *f0); #define SourceFunction(FUNC) \ FUNC(PetscInt dim, \ PetscInt Nf, \ PetscInt NfAux, \ const PetscInt uOff[], \ const PetscInt uOff_x[], \ const PetscScalar u[], \ const PetscScalar u_t[], \ const PetscScalar u_x[], \ const PetscInt aOff[], \ const PetscInt aOff_x[], \ const PetscScalar a[], \ const PetscScalar a_t[], \ const PetscScalar a_x[], \ PetscReal t, \ const PetscReal X[], \ PetscInt numConstants, \ const PetscScalar constants[], \ PetscScalar f0[]) // store the pointer to the provided test function from the solver static IntegrandTestFunction f0_v_original; static IntegrandTestFunction f0_w_original; static IntegrandTestFunction f0_q_original; static PetscErrorCode SetInitialConditions(TS ts, Vec u) { DM dm; PetscReal t; PetscErrorCode ierr; PetscFunctionBegin; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = TSGetTime(ts, &t); CHKERRQ(ierr); // This function Tags the u vector as the exact solution. We need to copy the values to prevent this. Vec e; ierr = VecDuplicate(u, &e); CHKERRQ(ierr); ierr = DMComputeExactSolution(dm, t, e, NULL); CHKERRQ(ierr); ierr = VecCopy(e, u); CHKERRQ(ierr); ierr = VecDestroy(&e); CHKERRQ(ierr); // get the flow to apply the completeFlowInitialization method ierr = IncompressibleFlow_CompleteFlowInitialization(dm, u); CHKERRQ(ierr); PetscFunctionReturn(0); } static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal crtime, Vec u, void *ctx) { PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); void *ctxs[3]; DM dm; PetscDS ds; Vec v; PetscReal ferrors[3]; PetscInt f; PetscErrorCode ierr; PetscFunctionBeginUser; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = DMGetDS(dm, &ds); CHKERRQ(ierr); ierr = VecViewFromOptions(u, NULL, "-vec_view_monitor"); CHKERRABORT(PETSC_COMM_WORLD, ierr); for (f = 0; f < 3; ++f) { ierr = PetscDSGetExactSolution(ds, f, &exactFuncs[f], &ctxs[f]); CHKERRABORT(PETSC_COMM_WORLD, ierr); } ierr = DMComputeL2FieldDiff(dm, crtime, exactFuncs, ctxs, u, ferrors); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Timestep: %04d time = %-8.4g \t L_2 Error: [%2.3g, %2.3g, %2.3g]\n", (int)step, (double)crtime, (double)ferrors[0], (double)ferrors[1], (double)ferrors[2]); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMGetGlobalVector(dm, &u); CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = TSGetSolution(ts, &u);CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = PetscObjectSetName((PetscObject)u, "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMRestoreGlobalVector(dm, &u); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMGetGlobalVector(dm, &v); CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = VecSet(v, 0.0);CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMProjectFunction(dm, 0.0, exactFuncs, ctxs, INSERT_ALL_VALUES, v); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscObjectSetName((PetscObject)v, "Exact Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = VecViewFromOptions(v, NULL, "-exact_vec_view"); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMRestoreGlobalVector(dm, &v); CHKERRABORT(PETSC_COMM_WORLD, ierr); PetscFunctionReturn(0); } // helper functions for generated code static PetscReal Power(PetscReal x, PetscInt exp) { return PetscPowReal(x, exp); } static PetscReal Cos(PetscReal x) { return PetscCosReal(x); } static PetscReal Sin(PetscReal x) { return PetscSinReal(x); } /* CASE: incompressible quadratic In 2D we use exact solution: u = t + x^2 + y^2 v = t + 2x^2 - 2xy p = x + y - 1 T = t + x + y so that \nabla \cdot u = 2x - 2x = 0 see docs/content/formulations/incompressibleFlow/solutions/Incompressible_2D_Quadratic_MMS.nb */ static PetscErrorCode incompressible_quadratic_u(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = time + X[0] * X[0] + X[1] * X[1]; u[1] = time + 2.0 * X[0] * X[0] - 2.0 * X[0] * X[1]; return 0; } static PetscErrorCode incompressible_quadratic_u_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 1.0; u[1] = 1.0; return 0; } static PetscErrorCode incompressible_quadratic_p(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *p, void *ctx) { p[0] = X[0] + X[1] - 1.0; return 0; } static PetscErrorCode incompressible_quadratic_T(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) { T[0] = time + X[0] + X[1]; return 0; } static PetscErrorCode incompressible_quadratic_T_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) { T[0] = 1.0; return 0; } /* f0_v = du/dt - f */ static void SourceFunction(f0_incompressible_quadratic_v) { f0_v_original(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, a_t, a_x, t, X, numConstants, constants, f0); const PetscReal rho = 1.0; const PetscReal S = constants[STROUHAL]; const PetscReal mu = constants[MU]; const PetscReal R = constants[REYNOLDS]; const PetscReal x = X[0]; const PetscReal y = X[1]; f0[0] -= 1 - (4. * mu) / R + rho * S + 2 * rho * y * (t + 2 * Power(x, 2) - 2 * x * y) + 2 * rho * x * (t + Power(x, 2) + Power(y, 2)); f0[1] -= 1 - (4. * mu) / R + rho * S - 2 * rho * x * (t + 2 * Power(x, 2) - 2 * x * y) + rho * (4 * x - 2 * y) * (t + Power(x, 2) + Power(y, 2)); } /* f0_w = dT/dt + u.grad(T) - Q */ static void SourceFunction(f0_incompressible_quadratic_w) { f0_w_original(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, a_t, a_x, t, X, numConstants, constants, f0); const PetscReal rho = 1.0; const PetscReal S = constants[STROUHAL]; const PetscReal Cp = constants[CP]; const PetscReal x = X[0]; const PetscReal y = X[1]; f0[0] -= Cp * rho * (S + 2 * t + 3 * Power(x, 2) - 2 * x * y + Power(y, 2)); } int main(int argc, char *argv[]) { DM dm; /* problem definition */ TS ts; /* timestepper */ PetscBag parameterBag; /* constant flow parameters */ FlowData flowData; /* store some of the flow data*/ PetscReal t; PetscErrorCode ierr; // initialize petsc and mpi PetscInitialize(&argc, &argv, NULL, help); // setup the ts ierr = TSCreate(PETSC_COMM_WORLD, &ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = CreateMesh(PETSC_COMM_WORLD, &dm, PETSC_TRUE, 2); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetDM(ts, dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the flow data ierr = FlowCreate(&flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); // setup problem ierr = IncompressibleFlow_SetupDiscretization(flowData, dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); // get the flow parameters from options IncompressibleFlowParameters *flowParameters; ierr = IncompressibleFlow_ParametersFromPETScOptions(&parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscBagGetData(parameterBag, (void **)&flowParameters); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Start the problem setup PetscScalar constants[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS]; ierr = IncompressibleFlow_PackParameters(flowParameters, constants); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = IncompressibleFlow_StartProblemSetup(flowData, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS, constants); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Override problem with source terms, boundary, and set the exact solution { PetscDS prob; ierr = DMGetDS(dm, &prob); CHKERRABORT(PETSC_COMM_WORLD, ierr); // V, W Test Function IntegrandTestFunction tempFunctionPointer; ierr = PetscDSGetResidual(prob, VTEST, &f0_v_original, &tempFunctionPointer); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetResidual(prob, VTEST, f0_incompressible_quadratic_v, tempFunctionPointer); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSGetResidual(prob, WTEST, &f0_w_original, &tempFunctionPointer); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetResidual(prob, WTEST, f0_incompressible_quadratic_w, tempFunctionPointer); CHKERRABORT(PETSC_COMM_WORLD, ierr); /* Setup Boundary Conditions */ PetscInt id; id = 3; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "top wall velocity", "marker", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 1; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "bottom wall velocity", "marker", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 2; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "right wall velocity", "marker", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 4; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "left wall velocity", "marker", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 3; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "top wall temp", "marker", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 1; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "bottom wall temp", "marker", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 2; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "right wall temp", "marker", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); id = 4; ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "left wall temp", "marker", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Set the exact solution ierr = PetscDSSetExactSolution(prob, VEL, incompressible_quadratic_u, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetExactSolution(prob, PRES, incompressible_quadratic_p, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetExactSolution(prob, TEMP, incompressible_quadratic_T, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetExactSolutionTimeDerivative(prob, VEL, incompressible_quadratic_u_t, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetExactSolutionTimeDerivative(prob, PRES, NULL, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscDSSetExactSolutionTimeDerivative(prob, TEMP, incompressible_quadratic_T_t, parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); } ierr = IncompressibleFlow_CompleteProblemSetup(flowData, ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Name the flow field ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the TS ierr = TSSetFromOptions(ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Set initial conditions from the exact solution ierr = TSSetComputeInitialCondition(ts, SetInitialConditions); CHKERRABORT(PETSC_COMM_WORLD, ierr); /* Must come after SetFromOptions() */ ierr = SetInitialConditions(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSGetTime(ts, &t); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMSetOutputSequenceNumber(dm, 0, t); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMTSCheckFromOptions(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSMonitorSet(ts, MonitorError, NULL, NULL); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSSolve(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Compare the actual vs expected values ierr = DMTSCheckFromOptions(ts, flowData->flowField); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Cleanup ierr = FlowDestroy(&flowData); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = DMDestroy(&dm); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSDestroy(&ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = PetscBagDestroy(&parameterBag); CHKERRABORT(PETSC_COMM_WORLD, ierr); return PetscFinalize(); }
{ "alphanum_fraction": 0.6755775578, "avg_line_length": 43.4097421203, "ext": "c", "hexsha": "cfd4409a18b2d797b4e53b3248b5377a7a4e225b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_path": "ablateCoreClient.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_path": "ablateCoreClient.c", "max_line_length": 214, "max_stars_count": null, "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_path": "ablateCoreClient.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4508, "size": 15150 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef rendersys_5fadb7a4_2c63_4b3a_8029_14043d2405e6_h #define rendersys_5fadb7a4_2c63_4b3a_8029_14043d2405e6_h #include <ariel/config.h> #include <ariel/type.h> #include <gslib/std.h> #include <ariel/image.h> __ariel_begin__ enum shader_type { st_vertex_shader, st_pixel_shader, st_geometry_shader, st_hull_shader, st_domain_shader, st_tessellation_shader, st_compute_shader, /* more.. */ }; enum sampler_state_filter { ssf_point, ssf_linear, ssf_anisotropic, }; struct render_device_info { uint vendor_id; }; class __gs_novtable rendersys abstract { public: typedef unordered_map<string, string> configs; typedef render_vertex_buffer vertex_buffer; typedef render_index_buffer index_buffer; typedef render_constant_buffer constant_buffer; typedef render_texture1d texture1d; typedef render_texture2d texture2d; typedef render_texture3d texture3d; typedef render_sampler_state sampler_state; typedef unordered_map<void*, rendersys*> rsys_map; config_select_type(select_render_platform, vertex_format_desc); public: rendersys(); virtual ~rendersys() {} virtual bool setup(uint hwnd, const configs& cfg) = 0; virtual void destroy() = 0; virtual void setup_pipeline_state() = 0; virtual render_blob* compile_shader_from_file(const gchar* file, const gchar* entry, const gchar* sm, render_include* inc) = 0; virtual render_blob* compile_shader_from_memory(const char* src, int len, const gchar* name, const gchar* entry, const gchar* sm, render_include* inc) = 0; virtual vertex_shader* create_vertex_shader(const void* ptr, size_t len) = 0; virtual pixel_shader* create_pixel_shader(const void* ptr, size_t len) = 0; virtual compute_shader* create_compute_shader(const void* ptr, size_t len) = 0; virtual geometry_shader* create_geometry_shader(const void* ptr, size_t len) = 0; virtual hull_shader* create_hull_shader(const void* ptr, size_t len) = 0; virtual domain_shader* create_domain_shader(const void* ptr, size_t len) = 0; virtual vertex_format* create_vertex_format(const void* ptr, size_t len, vertex_format_desc desc[], uint n) = 0; virtual vertex_buffer* create_vertex_buffer(uint stride, uint count, bool read, bool write, uint usage, const void* ptr = 0) = 0; virtual index_buffer* create_index_buffer(uint count, bool read, bool write, uint usage, const void* ptr = 0) = 0; virtual constant_buffer* create_constant_buffer(uint stride, bool read, bool write, const void* ptr = 0) = 0; virtual shader_resource_view* create_shader_resource_view(render_resource* res) = 0; /* texture view in GL */ virtual depth_stencil_view* create_depth_stencil_view(render_resource* res) = 0; virtual unordered_access_view* create_unordered_access_view(render_resource* res) = 0; virtual sampler_state* create_sampler_state(sampler_state_filter filter) = 0; virtual texture2d* create_texture2d(const image& img, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) = 0; virtual texture2d* create_texture2d(int width, int height, uint format, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) = 0; virtual void load_with_mips(texture2d* tex, const image& img) = 0; virtual void update_buffer(void* buf, int size, const void* ptr) = 0; virtual void set_vertex_format(vertex_format* vfmt) = 0; virtual void set_vertex_buffer(vertex_buffer* vb, uint stride, uint offset) = 0; virtual void set_index_buffer(index_buffer* ib, uint offset) = 0; virtual void begin_render() = 0; virtual void end_render() = 0; virtual void set_render_option(render_option opt, uint val) = 0; virtual void set_vertex_shader(vertex_shader* vs) = 0; virtual void set_pixel_shader(pixel_shader* ps) = 0; virtual void set_geometry_shader(geometry_shader* gs) = 0; virtual void set_viewport(const viewport& vp) = 0; virtual void set_constant_buffer(uint slot, constant_buffer* cb, shader_type st) = 0; virtual void set_sampler_state(uint slot, sampler_state* sstate, shader_type st) = 0; virtual void set_shader_resource(uint slot, shader_resource_view* srv, shader_type st) = 0; virtual void draw(uint count, uint start) = 0; virtual void draw_indexed(uint count, uint start, int base = 0) = 0; virtual void capture_screen(image& img, const rectf& rc, int buff_id) = 0; /* before present, buff_id = 0; after present, buff_id = 1 */ virtual void enable_alpha_blend(bool b) = 0; virtual void enable_depth(bool b) = 0; public: static bool is_vsync_enabled(const configs& cfg); static bool is_full_screen(const configs& cfg); static bool is_MSAA_enabled(const configs& cfg); static uint get_MSAA_sampler_count(const configs& cfg); static void register_dev_index_service(void* dev, rendersys* rsys); static void unregister_dev_index_service(void* dev); static rendersys* find_by_dev(void* dev); /* we could usually find the rendersys by its device ptr */ protected: render_device_info _device_info; float _bkcr[4]; public: const render_device_info& get_device_info() const { return _device_info; } void set_background_color(const color& cr); private: static rsys_map _dev_indexing; }; extern void release_vertex_buffer(render_vertex_buffer* buf); extern void release_index_buffer(render_index_buffer* buf); extern void release_constant_buffer(render_constant_buffer* buf); extern void release_texture2d(render_texture2d* tex); template<class res_class> render_resource* convert_to_resource(res_class*); template<class _pack> inline uint pack_cb_size() { uint s = sizeof(_pack); uint m = s % 16; return !m ? s : s + (16 - m); } __ariel_end__ #endif
{ "alphanum_fraction": 0.7303867403, "avg_line_length": 44.9689440994, "ext": "h", "hexsha": "8339f23d7f55f27aa7f60c78e349ea2a6379ba30", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/rendersys.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/rendersys.h", "max_line_length": 160, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/rendersys.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 1752, "size": 7240 }
/* poly/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_poly.h> int main (void) { const double eps = 100.0 * GSL_DBL_EPSILON; gsl_ieee_env_setup (); { double x, y; double c[3] = { 1.0, 0.5, 0.3 }; x = 0.5; y = gsl_poly_eval (c, 3, x); gsl_test_rel (y, 1 + 0.5 * x + 0.3 * x * x, eps, "gsl_poly_eval({1, 0.5, 0.3}, 0.5)"); } { double x, y; double d[11] = { 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1 }; x = 1.0; y = gsl_poly_eval (d, 11, x); gsl_test_rel (y, 1.0, eps, "gsl_poly_eval({1,-1, 1, -1, 1, -1, 1, -1, 1, -1, 1}, 1.0)"); } /* Quadratic */ { double x0, x1; int n = gsl_poly_solve_quadratic (4.0, -20.0, 26.0, &x0, &x1); gsl_test (n != 0, "gsl_poly_solve_quadratic, no roots, (2x - 5)^2 = -1"); } { double x0, x1; int n = gsl_poly_solve_quadratic (4.0, -20.0, 25.0, &x0, &x1); gsl_test (n != 2, "gsl_poly_solve_quadratic, one root, (2x - 5)^2 = 0"); gsl_test_rel (x0, 2.5, 1e-9, "x0, (2x - 5)^2 = 0"); gsl_test_rel (x1, 2.5, 1e-9, "x1, (2x - 5)^2 = 0"); gsl_test (x0 != x1, "x0 == x1, (2x - 5)^2 = 0"); } { double x0, x1; int n = gsl_poly_solve_quadratic (4.0, -20.0, 21.0, &x0, &x1); gsl_test (n != 2, "gsl_poly_solve_quadratic, two roots, (2x - 5)^2 = 4"); gsl_test_rel (x0, 1.5, 1e-9, "x0, (2x - 5)^2 = 4"); gsl_test_rel (x1, 3.5, 1e-9, "x1, (2x - 5)^2 = 4"); } { double x0, x1; int n = gsl_poly_solve_quadratic (4.0, 7.0, 0.0, &x0, &x1); gsl_test (n != 2, "gsl_poly_solve_quadratic, two roots, x(4x + 7) = 0"); gsl_test_rel (x0, -1.75, 1e-9, "x0, x(4x + 7) = 0"); gsl_test_rel (x1, 0.0, 1e-9, "x1, x(4x + 7) = 0"); } { double x0, x1; int n = gsl_poly_solve_quadratic (5.0, 0.0, -20.0, &x0, &x1); gsl_test (n != 2, "gsl_poly_solve_quadratic, two roots b = 0, 5 x^2 = 20"); gsl_test_rel (x0, -2.0, 1e-9, "x0, 5 x^2 = 20"); gsl_test_rel (x1, 2.0, 1e-9, "x1, 5 x^2 = 20"); } { double x0, x1; int n = gsl_poly_solve_quadratic (0.0, 3.0, -21.0, &x0, &x1); gsl_test (n != 1, "gsl_poly_solve_quadratic, one root (linear) 3 x - 21 = 0"); gsl_test_rel (x0, 7.0, 1e-9, "x0, 3x - 21 = 0"); } { double x0, x1; int n = gsl_poly_solve_quadratic (0.0, 0.0, 1.0, &x0, &x1); gsl_test (n != 0, "gsl_poly_solve_quadratic, no roots 1 = 0"); } /* Cubic */ { double x0, x1, x2; int n = gsl_poly_solve_cubic (0.0, 0.0, -27.0, &x0, &x1, &x2); gsl_test (n != 1, "gsl_poly_solve_cubic, one root, x^3 = 27"); gsl_test_rel (x0, 3.0, 1e-9, "x0, x^3 = 27"); } { double x0, x1, x2; int n = gsl_poly_solve_cubic (-51.0, 867.0, -4913.0, &x0, &x1, &x2); gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x-17)^3=0"); gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)^3=0"); gsl_test_rel (x1, 17.0, 1e-9, "x1, (x-17)^3=0"); gsl_test_rel (x2, 17.0, 1e-9, "x2, (x-17)^3=0"); } { double x0, x1, x2; int n = gsl_poly_solve_cubic (-57.0, 1071.0, -6647.0, &x0, &x1, &x2); gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x-17)(x-17)(x-23)=0"); gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)(x-17)(x-23)=0"); gsl_test_rel (x1, 17.0, 1e-9, "x1, (x-17)(x-17)(x-23)=0"); gsl_test_rel (x2, 23.0, 1e-9, "x2, (x-17)(x-17)(x-23)=0"); } { double x0, x1, x2; int n = gsl_poly_solve_cubic (-11.0, -493.0, +6647.0, &x0, &x1, &x2); gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x+23)(x-17)(x-17)=0"); gsl_test_rel (x0, -23.0, 1e-9, "x0, (x+23)(x-17)(x-17)=0"); gsl_test_rel (x1, 17.0, 1e-9, "x1, (x+23)(x-17)(x-17)=0"); gsl_test_rel (x2, 17.0, 1e-9, "x2, (x+23)(x-17)(x-17)=0"); } { double x0, x1, x2; int n = gsl_poly_solve_cubic (-143.0, 5087.0, -50065.0, &x0, &x1, &x2); gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x-17)(x-31)(x-95)=0"); gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)(x-31)(x-95)=0"); gsl_test_rel (x1, 31.0, 1e-9, "x1, (x-17)(x-31)(x-95)=0"); gsl_test_rel (x2, 95.0, 1e-9, "x2, (x-17)(x-31)(x-95)=0"); } { double x0, x1, x2; int n = gsl_poly_solve_cubic (-109.0, 803.0, 50065.0, &x0, &x1, &x2); gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x+17)(x-31)(x-95)=0"); gsl_test_rel (x0, -17.0, 1e-9, "x0, (x+17)(x-31)(x-95)=0"); gsl_test_rel (x1, 31.0, 1e-9, "x1, (x+17)(x-31)(x-95)=0"); gsl_test_rel (x2, 95.0, 1e-9, "x2, (x+17)(x-31)(x-95)=0"); } /* Quadratic with complex roots */ { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 26.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, 2 roots (2x - 5)^2 = -1"); gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, "z0.real, (2x - 5)^2 = -1"); gsl_test_rel (GSL_IMAG (z0), -0.5, 1e-9, "z0.imag, (2x - 5)^2 = -1"); gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, "z1.real, (2x - 5)^2 = -1"); gsl_test_rel (GSL_IMAG (z1), 0.5, 1e-9, "z1.imag, (2x - 5)^2 = -1"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 25.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, one root, (2x - 5)^2 = 0"); gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, "z0.real, (2x - 5)^2 = 0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag (2x - 5)^2 = 0"); gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, "z1.real, (2x - 5)^2 = 0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag (2x - 5)^2 = 0"); gsl_test (GSL_REAL (z0) != GSL_REAL (z1), "z0.real == z1.real, (2x - 5)^2 = 0"); gsl_test (GSL_IMAG (z0) != GSL_IMAG (z1), "z0.imag == z1.imag, (2x - 5)^2 = 0"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 21.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, two roots, (2x - 5)^2 = 4"); gsl_test_rel (GSL_REAL (z0), 1.5, 1e-9, "z0.real, (2x - 5)^2 = 4"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (2x - 5)^2 = 4"); gsl_test_rel (GSL_REAL (z1), 3.5, 1e-9, "z1.real, (2x - 5)^2 = 4"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (2x - 5)^2 = 4"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (4.0, 7.0, 0.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, two roots, x(4x + 7) = 0"); gsl_test_rel (GSL_REAL (z0), -1.75, 1e-9, "z0.real, x(4x + 7) = 0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, x(4x + 7) = 0"); gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, "z1.real, x(4x + 7) = 0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, x(4x + 7) = 0"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, -20.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = 20"); gsl_test_rel (GSL_REAL (z0), -2.0, 1e-9, "z0.real, 5 x^2 = 20"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, 5 x^2 = 20"); gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, "z1.real, 5 x^2 = 20"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, 5 x^2 = 20"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, 20.0, &z0, &z1); gsl_test (n != 2, "gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = -20"); gsl_test_rel (GSL_REAL (z0), 0.0, 1e-9, "z0.real, 5 x^2 = -20"); gsl_test_rel (GSL_IMAG (z0), -2.0, 1e-9, "z0.imag, 5 x^2 = -20"); gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, "z1.real, 5 x^2 = -20"); gsl_test_rel (GSL_IMAG (z1), 2.0, 1e-9, "z1.imag, 5 x^2 = -20"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (0.0, 3.0, -21.0, &z0, &z1); gsl_test (n != 1, "gsl_poly_complex_solve_quadratic, one root (linear) 3 x - 21 = 0"); gsl_test_rel (GSL_REAL (z0), 7.0, 1e-9, "z0.real, 3x - 21 = 0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, 3x - 21 = 0"); } { gsl_complex z0, z1; int n = gsl_poly_complex_solve_quadratic (0.0, 0.0, 1.0, &z0, &z1); gsl_test (n != 0, "gsl_poly_complex_solve_quadratic, no roots 1 = 0"); } /* Cubic with complex roots */ { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (0.0, 0.0, -27.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three root, x^3 = 27"); gsl_test_rel (GSL_REAL (z0), -1.5, 1e-9, "z0.real, x^3 = 27"); gsl_test_rel (GSL_IMAG (z0), -1.5 * sqrt (3.0), 1e-9, "z0.imag, x^3 = 27"); gsl_test_rel (GSL_REAL (z1), -1.5, 1e-9, "z1.real, x^3 = 27"); gsl_test_rel (GSL_IMAG (z1), 1.5 * sqrt (3.0), 1e-9, "z1.imag, x^3 = 27"); gsl_test_rel (GSL_REAL (z2), 3.0, 1e-9, "z2.real, x^3 = 27"); gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, x^3 = 27"); } { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (-1.0, 1.0, 39.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three root, (x+3)(x^2-4x+13) = 0"); gsl_test_rel (GSL_REAL (z0), -3.0, 1e-9, "z0.real, (x+3)(x^2+1) = 0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x+3)(x^2+1) = 0"); gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, "z1.real, (x+3)(x^2+1) = 0"); gsl_test_rel (GSL_IMAG (z1), -3.0, 1e-9, "z1.imag, (x+3)(x^2+1) = 0"); gsl_test_rel (GSL_REAL (z2), 2.0, 1e-9, "z2.real, (x+3)(x^2+1) = 0"); gsl_test_rel (GSL_IMAG (z2), 3.0, 1e-9, "z2.imag, (x+3)(x^2+1) = 0"); } { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (-51.0, 867.0, -4913.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three roots, (x-17)^3=0"); gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)^3=0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)^3=0"); gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x-17)^3=0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)^3=0"); gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, "z2.real, (x-17)^3=0"); gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)^3=0"); } { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (-57.0, 1071.0, -6647.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three roots, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_REAL (z2), 23.0, 1e-9, "z2.real, (x-17)(x-17)(x-23)=0"); gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)(x-17)(x-23)=0"); } { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (-11.0, -493.0, +6647.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three roots, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_REAL (z0), -23.0, 1e-9, "z0.real, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, "z2.real, (x+23)(x-17)(x-17)=0"); gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x+23)(x-17)(x-17)=0"); } { gsl_complex z0, z1, z2; int n = gsl_poly_complex_solve_cubic (-143.0, 5087.0, -50065.0, &z0, &z1, &z2); gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three roots, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_REAL (z1), 31.0, 1e-9, "z1.real, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_REAL (z2), 95.0, 1e-9, "z2.real, (x-17)(x-31)(x-95)=0"); gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)(x-31)(x-95)=0"); } { /* Wilkinson polynomial: y = (x-1)(x-2)(x-3)(x-4)(x-5) */ double a[6] = { -120, 274, -225, 85, -15, 1 }; double z[6*2]; gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (6); int status = gsl_poly_complex_solve (a, 6, w, z); gsl_poly_complex_workspace_free (w); gsl_test (status, "gsl_poly_complex_solve, 5th-order Wilkinson polynomial"); gsl_test_rel (z[0], 1.0, 1e-9, "z0.real, 5th-order polynomial"); gsl_test_rel (z[1], 0.0, 1e-9, "z0.imag, 5th-order polynomial"); gsl_test_rel (z[2], 2.0, 1e-9, "z1.real, 5th-order polynomial"); gsl_test_rel (z[3], 0.0, 1e-9, "z1.imag, 5th-order polynomial"); gsl_test_rel (z[4], 3.0, 1e-9, "z2.real, 5th-order polynomial"); gsl_test_rel (z[5], 0.0, 1e-9, "z2.imag, 5th-order polynomial"); gsl_test_rel (z[6], 4.0, 1e-9, "z3.real, 5th-order polynomial"); gsl_test_rel (z[7], 0.0, 1e-9, "z3.imag, 5th-order polynomial"); gsl_test_rel (z[8], 5.0, 1e-9, "z4.real, 5th-order polynomial"); gsl_test_rel (z[9], 0.0, 1e-9, "z4.imag, 5th-order polynomial"); } { /* : 8-th order polynomial y = x^8 + x^4 + 1 */ double a[9] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; double z[8*2]; double C = 0.5; double S = sqrt (3.0) / 2.0; gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (9); int status = gsl_poly_complex_solve (a, 9, w, z); gsl_poly_complex_workspace_free (w); gsl_test (status, "gsl_poly_complex_solve, 8th-order polynomial"); gsl_test_rel (z[0], -S, 1e-9, "z0.real, 8th-order polynomial"); gsl_test_rel (z[1], C, 1e-9, "z0.imag, 8th-order polynomial"); gsl_test_rel (z[2], -S, 1e-9, "z1.real, 8th-order polynomial"); gsl_test_rel (z[3], -C, 1e-9, "z1.imag, 8th-order polynomial"); gsl_test_rel (z[4], -C, 1e-9, "z2.real, 8th-order polynomial"); gsl_test_rel (z[5], S, 1e-9, "z2.imag, 8th-order polynomial"); gsl_test_rel (z[6], -C, 1e-9, "z3.real, 8th-order polynomial"); gsl_test_rel (z[7], -S, 1e-9, "z3.imag, 8th-order polynomial"); gsl_test_rel (z[8], C, 1e-9, "z4.real, 8th-order polynomial"); gsl_test_rel (z[9], S, 1e-9, "z4.imag, 8th-order polynomial"); gsl_test_rel (z[10], C, 1e-9, "z5.real, 8th-order polynomial"); gsl_test_rel (z[11], -S, 1e-9, "z5.imag, 8th-order polynomial"); gsl_test_rel (z[12], S, 1e-9, "z6.real, 8th-order polynomial"); gsl_test_rel (z[13], C, 1e-9, "z6.imag, 8th-order polynomial"); gsl_test_rel (z[14], S, 1e-9, "z7.real, 8th-order polynomial"); gsl_test_rel (z[15], -C, 1e-9, "z7.imag, 8th-order polynomial"); } { int i; double xa[7] = {0.16, 0.97, 1.94, 2.74, 3.58, 3.73, 4.70 }; double ya[7] = {0.73, 1.11, 1.49, 1.84, 2.30, 2.41, 3.07 }; double dd_expected[7] = { 7.30000000000000e-01, 4.69135802469136e-01, -4.34737219941284e-02, 2.68681098870099e-02, -3.22937056934996e-03, 6.12763259971375e-03, -6.45402453527083e-03 }; double dd[7], coeff[7], work[7]; gsl_poly_dd_init (dd, xa, ya, 7); for (i = 0; i < 7; i++) { gsl_test_rel (dd[i], dd_expected[i], 1e-10, "divided difference dd[%d]", i); } for (i = 0; i < 7; i++) { double y = gsl_poly_dd_eval(dd, xa, 7, xa[i]); gsl_test_rel (y, ya[i], 1e-10, "divided difference y[%d]", i); } gsl_poly_dd_taylor (coeff, 1.5, dd, xa, 7, work); for (i = 0; i < 7; i++) { double y = gsl_poly_eval(coeff, 7, xa[i] - 1.5); gsl_test_rel (y, ya[i], 1e-10, "taylor expansion about 1.5 y[%d]", i); } } /* now summarize the results */ exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.5498337902, "avg_line_length": 33.6876227898, "ext": "c", "hexsha": "bd0e141b3195333d3f956df9b1867c49cee46181", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/poly/test.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/poly/test.c", "max_line_length": 84, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/poly/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 7772, "size": 17147 }
static char help[] = "Stiff ODE system. Compare odejac.c.\n\n"; #include <petsc.h> /* PYTHON: import numpy as np from scipy.linalg import expm B = np.array([[0, 1, 0], [-1, 0, 0.1], [0, 0, -101]]) y = np.dot(expm(10*B),np.array([1.0,1.0,1.0]).transpose()) print y RESULT: [-1.383623 -0.29588643 0. ] */ extern PetscErrorCode FormRHSFunction(TS, double, Vec, Vec, void*); PetscErrorCode FormRHSJacobian(TS, double, Vec, Mat, Mat, void*); int main(int argc,char **argv) { PetscErrorCode ierr; const int N = 3; int steps; Vec y; Mat J; TS ts; PetscInitialize(&argc,&argv,(char*)0,help); ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr); ierr = VecSetSizes(y,PETSC_DECIDE,N); CHKERRQ(ierr); ierr = VecSetFromOptions(y); CHKERRQ(ierr); ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr); ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,N,N); CHKERRQ(ierr); ierr = MatSetFromOptions(J); CHKERRQ(ierr); ierr = MatSetUp(J); CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr); ierr = TSSetRHSJacobian(ts,J,J,FormRHSJacobian,NULL); CHKERRQ(ierr); ierr = TSSetType(ts,TSRK); CHKERRQ(ierr); ierr = TSSetTime(ts,0.0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,10.0); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,1.0); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetFromOptions(ts); CHKERRQ(ierr); // can override defaults ierr = VecSet(y,1.0); CHKERRQ(ierr); ierr = TSSolve(ts,y); CHKERRQ(ierr); ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "total steps = %d\n",steps); CHKERRQ(ierr); VecDestroy(&y); TSDestroy(&ts); MatDestroy(&J); PetscFinalize(); return 0; } PetscErrorCode FormRHSFunction(TS ts, double t, Vec y, Vec g, void *ptr) { const double *ay; double *ag; VecGetArrayRead(y,&ay); VecGetArray(g,&ag); ag[0] = ay[1]; ag[1] = - ay[0] + 0.1 * ay[2]; ag[2] = - 101.0 * ay[2]; VecRestoreArrayRead(y,&ay); VecRestoreArray(g,&ag); return 0; } PetscErrorCode FormRHSJacobian(TS ts, double t, Vec y, Mat J, Mat P, void *ptr) { PetscErrorCode ierr; int j[3] = {0, 1, 2}; double v[9] = { 0.0, 1.0, 0.0, -1.0, 0.0, 0.1, 0.0, 0.0, -101.0}; ierr = MatSetValues(P,3,j,3,j,v,INSERT_VALUES); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; }
{ "alphanum_fraction": 0.6371322286, "avg_line_length": 32.4945054945, "ext": "c", "hexsha": "bbc8093c6fb2b27eb3355b1837d18f4df6603404", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch5/solns/stiff.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch5/solns/stiff.c", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch5/solns/stiff.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 989, "size": 2957 }
/*************************************************************************** Copyright (c) 2014, The OpenBLAS Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the OpenBLAS project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ //#include "bench.h" #include <cblas.h> #include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> // mlir-clang dot.c -I .. -I /home/lchelini/scratch/polygeist/llvm-project/llvm/../clang/lib/Headers -o dot --emit-llvm int main(int argc, char *argv[]) { float *x, *y; float r; int inc_x = 1, inc_y = 1; int size = 500; x = (float *)malloc(sizeof(float) * size); y = (float *)malloc(sizeof(float) * size); for (int i = 0; i < size; i++) { x[i] = ((float)rand() / (float)RAND_MAX) - 0.5; } for (int i = 0; i < size; i++) { y[i] = ((float)rand() / (float)RAND_MAX) - 0.5; } #pragma plugin(sdot_, "linalg", "r += x(i) * y(i)") r = sdot_(&size, x, &inc_x, y, &inc_y); fprintf(stderr, "%.6f\n", result); return 0; }
{ "alphanum_fraction": 0.6828865979, "avg_line_length": 38.4920634921, "ext": "c", "hexsha": "f3c8d1db53be4a13a551fbaa25481017e1433c6f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "chelini/openBlas", "max_forks_repo_path": "benchmark/dot.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "chelini/openBlas", "max_issues_repo_path": "benchmark/dot.c", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "chelini/openBlas", "max_stars_repo_path": "benchmark/dot.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 586, "size": 2425 }
#ifndef UBLAS_LIB_ATLAS_H #define UBLAS_LIB_ATLAS_H #include <stdio.h> #include <ublas_types.h> #include <cblas.h> int ubf_init(void **ctx); int ubf_gemm(void *ctx, ublas_matrix *a, ublas_matrix *b, ublas_matrix *c, double alpha, double beta); int ubf_free(void *ctx); #endif
{ "alphanum_fraction": 0.7553956835, "avg_line_length": 23.1666666667, "ext": "h", "hexsha": "97f74e5f1487d00bf3d3130eb3b78bf598740dfd", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "brgmnn/uob-ublas", "max_forks_repo_path": "src/drivers/atlas/atlas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "brgmnn/uob-ublas", "max_issues_repo_path": "src/drivers/atlas/atlas.h", "max_line_length": 102, "max_stars_count": 1, "max_stars_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "brgmnn/uob-ublas", "max_stars_repo_path": "src/drivers/atlas/atlas.h", "max_stars_repo_stars_event_max_datetime": "2021-01-13T03:13:08.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T03:13:08.000Z", "num_tokens": 86, "size": 278 }
/* linalg/trimult.c * * Copyright (C) 2019 Patrick Alken * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This source is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This module contains code to compute L^T L where L is a lower triangular matrix */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "recurse.h" static int triangular_multsymm_L2(CBLAS_UPLO_t Uplo, gsl_matrix * T); static int triangular_multsymm_L3(CBLAS_UPLO_t Uplo, gsl_matrix * T); static int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix * A); static int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix * A); int gsl_linalg_tri_LTL(gsl_matrix * L) { return triangular_multsymm_L3(CblasLower, L); } int gsl_linalg_tri_UL(gsl_matrix * LU) { return triangular_mult_L3(CblasUpper, LU); } /* triangular_multsymm_L2() Compute L^T L or U U^T Inputs: Uplo - CblasUpper or CblasLower T - on output the upper (or lower) part of T is replaced by L^T L or U U^T Return: success/error Notes: 1) Based on LAPACK routine DLAUU2 using Level 2 BLAS */ static int triangular_multsymm_L2(CBLAS_UPLO_t Uplo, gsl_matrix * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { gsl_vector_view v1, v2; size_t i; if (Uplo == CblasUpper) { } else { for (i = 0; i < N; ++i) { double Tii = gsl_matrix_get(T, i, i); if (i < N - 1) { double tmp; v1 = gsl_matrix_subcolumn(T, i, i, N - i); gsl_blas_ddot(&v1.vector, &v1.vector, &tmp); gsl_matrix_set(T, i, i, tmp); if (i > 0) { gsl_matrix_view m = gsl_matrix_submatrix(T, i + 1, 0, N - i - 1, i); v1 = gsl_matrix_subcolumn(T, i, i + 1, N - i - 1); v2 = gsl_matrix_subrow(T, i, 0, i); gsl_blas_dgemv(CblasTrans, 1.0, &m.matrix, &v1.vector, Tii, &v2.vector); } } else { v1 = gsl_matrix_row(T, N - 1); gsl_blas_dscal(Tii, &v1.vector); } } } return GSL_SUCCESS; } } /* triangular_multsymm_L3() Compute L^T L or U U^T Inputs: Uplo - CblasUpper or CblasLower T - on output the upper (or lower) part of T is replaced by L^T L or U U^T Return: success/error Notes: 1) Based on ReLAPACK routine DLAUUM using Level 3 BLAS */ static int triangular_multsymm_L3(CBLAS_UPLO_t Uplo, gsl_matrix * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_TRIMULT) { return triangular_multsymm_L2(Uplo, T); } else { /* partition matrix: * * T11 T12 * T21 T22 * * where T11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT(N); const size_t N2 = N - N1; gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1); gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2); gsl_matrix_view T21 = gsl_matrix_submatrix(T, N1, 0, N2, N1); gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2); /* recursion on T11 */ status = triangular_multsymm_L3(Uplo, &T11.matrix); if (status) return status; if (Uplo == CblasLower) { /* T11 += T21^T T21 */ gsl_blas_dsyrk(Uplo, CblasTrans, 1.0, &T21.matrix, 1.0, &T11.matrix); /* T21 = T22^T * T21 */ gsl_blas_dtrmm(CblasLeft, Uplo, CblasTrans, CblasNonUnit, 1.0, &T22.matrix, &T21.matrix); } else { /* T11 += T12 T12^T */ gsl_blas_dsyrk(Uplo, CblasNoTrans, 1.0, &T12.matrix, 1.0, &T11.matrix); /* T12 = T12 * T22^T */ gsl_blas_dtrmm(CblasRight, Uplo, CblasTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); } /* recursion on T22 */ status = triangular_multsymm_L3(Uplo, &T22.matrix); if (status) return status; return GSL_SUCCESS; } } /* triangular_mult_L2() Compute U L or L U Inputs: Uplo - CblasUpper or CblasLower (for the first triangular factor) A - on input, matrix in LU format; on output, U L or L U Return: success/error */ static int triangular_mult_L2(CBLAS_UPLO_t Uplo, gsl_matrix * A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { size_t i; /* quick return */ if (N == 1) return GSL_SUCCESS; if (Uplo == CblasUpper) { /* compute U * L and store in A */ for (i = 0; i < N; ++i) { double * Aii = gsl_matrix_ptr(A, i, i); double Uii = *Aii; if (i < N - 1) { gsl_vector_view lb = gsl_matrix_subcolumn(A, i, i + 1, N - i - 1); gsl_vector_view ur = gsl_matrix_subrow(A, i, i + 1, N - i - 1); double tmp; gsl_blas_ddot(&lb.vector, &ur.vector, &tmp); *Aii += tmp; if (i > 0) { gsl_matrix_view U_TR = gsl_matrix_submatrix(A, 0, i + 1, i, N - i - 1); gsl_matrix_view L_BL = gsl_matrix_submatrix(A, i + 1, 0, N - i - 1, i); gsl_vector_view ut = gsl_matrix_subcolumn(A, i, 0, i); gsl_vector_view ll = gsl_matrix_subrow(A, i, 0, i); gsl_blas_dgemv(CblasTrans, 1.0, &L_BL.matrix, &ur.vector, Uii, &ll.vector); gsl_blas_dgemv(CblasNoTrans, 1.0, &U_TR.matrix, &lb.vector, 1.0, &ut.vector); } } else { gsl_vector_view v = gsl_matrix_subrow(A, N - 1, 0, N - 1); gsl_blas_dscal(Uii, &v.vector); } } } else { } return GSL_SUCCESS; } } /* triangular_mult_L3() Compute U L or L U Inputs: Uplo - CblasUpper or CblasLower (for the first triangular factor) A - on input, matrix in LU format; on output, U L or L U Return: success/error */ static int triangular_mult_L3(CBLAS_UPLO_t Uplo, gsl_matrix * A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_TRIMULT) { return triangular_mult_L2(Uplo, A); } else { /* partition matrix: * * A11 A12 * A21 A22 * * where A11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT(N); const size_t N2 = N - N1; gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1); gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2); gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1); gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2); /* recursion on A11 */ status = triangular_mult_L3(Uplo, &A11.matrix); if (status) return status; if (Uplo == CblasLower) { } else { /* form U * L */ /* A11 += A12 A21 */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &A12.matrix, &A21.matrix, 1.0, &A11.matrix); /* A12 = A12 * L22 */ gsl_blas_dtrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A22.matrix, &A12.matrix); /* A21 = U22 * A21 */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &A22.matrix, &A21.matrix); } /* recursion on A22 */ status = triangular_mult_L3(Uplo, &A22.matrix); if (status) return status; return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5540112994, "avg_line_length": 26.4179104478, "ext": "c", "hexsha": "006429728d59f4d2c76f654752c826be2460fcfc", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/trimult.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/trimult.c", "max_line_length": 107, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/trimult.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 2645, "size": 8850 }
#pragma once #include <functional> #include <vector> #include <map> #include <gsl/string_span> class TabFileColumn { friend class TabFileRecord; public: bool IsEmpty() const { return mValue.size() == 0; } operator bool() const { return !IsEmpty(); } operator gsl::cstring_span<>() const { return mValue; } std::string AsString() const { return std::string(mValue.begin(), mValue.end()); } bool EqualsIgnoreCase(const char *text) const { return !_strnicmp(mValue.data(), text, mValue.size()); } bool TryGetFloat(float &value) const { if (mValue.size() == 0) { return false; } return _snscanf_s(mValue.data(), mValue.size(), "%f", &value) == 1; } template<typename T> bool TryGetEnum(const std::map<std::string, T> &mapping, T& value) { for (auto it = mapping.begin(); it != mapping.end(); ++it) { if (!_strnicmp(it->first.c_str(), mValue.data(), mValue.size())) { value = it->second; return true; } } return false; } private: explicit TabFileColumn(gsl::cstring_span<> value) : mValue(value) { } gsl::cstring_span<> mValue; }; class TabFileRecord { friend class TabFile; public: int GetLineNumber() const { return mLineNumber; } size_t GetColumnCount() const { return mColumns.size(); } TabFileColumn operator[](size_t i) const { if (i >= mColumns.size()) { return TabFileColumn(mMissingColumn); } return TabFileColumn(mColumns[i]); } private: static std::string mMissingColumn; int mLineNumber = 0; std::vector<gsl::cstring_span<>> mColumns; }; class TabFile { public: typedef std::function<void(const TabFileRecord&)> Callback; static void ParseFile( const std::string &filename, const Callback &callback ); static void ParseString( const std::string &content, const Callback &callback ); };
{ "alphanum_fraction": 0.6718232044, "avg_line_length": 18.2828282828, "ext": "h", "hexsha": "eb9c09be62c5afcaf6d78c76a5ab4c6c8fcc014f", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_issues_count": 457, "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_line_length": 69, "max_stars_count": 69, "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_path": "Infrastructure/include/infrastructure/tabparser.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "num_tokens": 489, "size": 1810 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2004-2020 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #include "ObitUVDesc.h" #include "ObitUVUtil.h" #include "ObitTableSUUtil.h" #include "ObitTableNXUtil.h" #include "ObitTablePSUtil.h" #include "ObitTableFQUtil.h" #include "ObitTableANUtil.h" #include "ObitTableFG.h" #include "ObitPrecess.h" #include "ObitUVWCalc.h" #include "ObitUVSortBuffer.h" #if HAVE_GSL==1 /* GSL stuff */ #include <gsl/gsl_randist.h> #endif /* HAVE_GSL */ /*----------------Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitUVUtil.c * ObitUVUtil module function definitions. */ /*---------------Private function prototypes----------------*/ /** Modify output descriptor from effects of frequency averaging */ static ofloat AvgFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChAvg, olong *ChanSel, gboolean doAvgAll, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ObitErr *err); /** Modify output descriptor from effects of frequency bloating */ static ofloat BloatFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat, ObitErr *err); /** Average visibility in frequency */ static void AvgFAver (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChAvg, olong *ChanSel, gboolean doAvgAll, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err); /** Smooth visibility in frequency */ static void SmooF (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChSmo, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err); /** Hann visibility in frequency */ static void Hann (ObitUVDesc *inDesc, ObitUVDesc *outDesc, gboolean doDescm, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err); /** Duplicate channels */ static void Bloat (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat, gboolean unHann, ofloat *inBuffer, ofloat *outBuffer, ObitErr *err); /** Copy selected channels */ static void FreqSel (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong BChan, olong EChan, olong chinc, olong BIF, olong EIF, ofloat *inBuffer, ofloat *outBuffer); /** Update FQ table for averaging */ static void FQSel (ObitUV *inUV, olong chAvg, olong fqid, ObitErr *err); /** Low accuracy inverse Sinc function */ static ofloat InvSinc(ofloat arg); /*----------------------Public functions---------------------------*/ /** * Find maximum baseline length and W in a data set. * Imaging parameters are on the inUV info member as arrays for a number * of fields. * \param inUV Input uv data. * \param MaxBL Output maximum baseline length (sqrt(u*u+v*v)) * \param MaxW Output Max abs(w) in data. * \param err Error stack, returns if not empty. */ void ObitUVUtilUVWExtrema (ObitUV *inUV, ofloat *MaxBL, ofloat *MaxW, ObitErr *err) { ObitIOCode retCode=OBIT_IO_SpecErr; olong i; ofloat bl, maxbl, maxw, *u, *v, *w; gchar *routine = "ObitUVUtilUVWExtrema"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV)); /* See if values are already in the descriptor */ if ((inUV->myDesc->maxBL>0.0) && (inUV->myDesc->maxW>0.0)) { *MaxBL = inUV->myDesc->maxBL; *MaxW = inUV->myDesc->maxW; return; } /* Open uv data if not already open */ if (inUV->myStatus==OBIT_Inactive) { retCode = ObitUVOpen (inUV, OBIT_IO_ReadOnly, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); } /* Loop through data */ maxbl = maxw = 0.0; while (retCode==OBIT_IO_OK) { /* read buffer full */ retCode = ObitUVRead (inUV, NULL, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* initialize data pointers */ u = inUV->buffer+inUV->myDesc->ilocu; v = inUV->buffer+inUV->myDesc->ilocv; w = inUV->buffer+inUV->myDesc->ilocw; for (i=0; i<inUV->myDesc->numVisBuff; i++) { /* loop over buffer */ /* Get statistics */ bl = sqrt ((*u)*(*u) + (*v)*(*v)); maxbl = MAX (maxbl, bl); maxw = MAX (fabs(*w), maxw); /* update data pointers */ u += inUV->myDesc->lrec; v += inUV->myDesc->lrec; w += inUV->myDesc->lrec; } /* end loop over buffer */ } /* end loop over file */ /* Close */ retCode = ObitUVClose (inUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Save values in the descriptor */ inUV->myDesc->maxBL = maxbl; inUV->myDesc->maxW = maxw; *MaxBL = maxbl; *MaxW = maxw; } /* end ObitUVUtilUVWExtrema */ /** * Make copy of ObitUV with the visibilities zeroed and weights 1. * \param inUV Input uv data to copy. * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the zeroed ObitUV. */ ObitUV* ObitUVUtilCopyZero (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; gchar *routine = "ObitUVUtilCopyZero"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); ObitUVClone (inUV, outUV, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* Selection of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_val (err, routine, outUV->name, outUV); } /* iretCode = ObitUVClose (inUV, err); DEBUG */ /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_val (err, routine, inUV->name, outUV); } /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) Obit_traceback_val (err, routine,inUV->name, outUV); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine,inUV->name, outUV); iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine,inUV->name, outUV); outUV->buffer = inUV->buffer; /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* we're in business, copy, zero data, set weight to 1 */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ indx = i*inDesc->lrec + inDesc->nrparm; for (j=0; j<inDesc->ncorr; j++) { /* loop over correlations */ inUV->buffer[indx] = 0.0; inUV->buffer[indx+1] = 0.0; inUV->buffer[indx+2] = 1.0; indx += inDesc->inaxes[0]; } /* end loop over correlations */ } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV->buffer, err); } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine,inUV->name, outUV); /* unset input buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* close files */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, inUV->name, outUV); oretCode = ObitUVClose (outUV, err); if ((oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilCopyZero */ /** * Divide the visibilities in one ObitUV by those in another * outUV = inUV1 / inUV2 * \param inUV1 Input uv data numerator, no calibration/selection * \param inUV2 Input uv data denominator, no calibration/selection * inUV2 should have the same structure, no. vis etc * as inUV1. * \param outUV Previously defined output, may be the same as inUV1 * \param err Error stack, returns if not empty. */ void ObitUVUtilVisDivide (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, firstVis; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong NPIO; ofloat work[3]; gboolean incompatible, same, btemp; ObitUVDesc *in1Desc, *in2Desc, *outDesc; gchar *today=NULL; gchar *routine = "ObitUVUtilVisDivide"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV1)); g_assert (ObitUVIsA(inUV2)); g_assert (ObitUVIsA(outUV)); /* Are input1 and output the same file? */ same = ObitUVSame(inUV1, outUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output. If multiple passes are made the input files will be closed which deallocates the buffer, use output buffer. so free input buffer */ if (!same) { /* use same data buffer on input 1 and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; } /* Copy number of records per IO to second input */ ObitInfoListGet (inUV1->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListPut (inUV2->info, "nVisPIO", type, dim, (gpointer)&NPIO, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* Open second input */ iretCode = ObitUVOpen (inUV2, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV2->name); /* Get input descriptors */ in1Desc = inUV1->myDesc; in2Desc = inUV2->myDesc; /* Check compatability between inUV1, inUV2 */ incompatible = in1Desc->nvis!=in2Desc->nvis; incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr); incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs); incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf); incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif); incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb); if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible structures", routine); return ; } /* Look at all data */ btemp = TRUE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* Copy tables before data if in1 and out are not the same */ if (!ObitUVSame (inUV1, outUV, err)) { iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV1->name); } } if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* reset to beginning of uv data */ iretCode = ObitUVIOSet (inUV1, err); oretCode = ObitUVIOSet (outUV, err); if (err->error) Obit_traceback_msg (err, routine,inUV1->name); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV1, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); outUV->buffer = inUV1->buffer; outDesc = outUV->myDesc; /* Get output descriptor */ /* we're in business, divide */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { /* Read first input */ iretCode = ObitUVRead (inUV1, inUV1->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* Read second input */ iretCode = ObitUVRead (inUV2, inUV2->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = in1Desc->numVisBuff; firstVis = in1Desc->firstVis; /* compatability check */ incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff; if (incompatible) break; /* Modify data */ for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */ /* compatability check - check time and baseline or antenna code */ indx = i*in1Desc->lrec ; incompatible = inUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[indx+in2Desc->iloct]; if (in1Desc->ilocb>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[indx+in2Desc->ilocb]; } if (in1Desc->iloca1>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[indx+in2Desc->iloca1] || inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[indx+in2Desc->iloca2]; } if (incompatible) break; indx += in1Desc->nrparm; for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */ /* Divide */ ObitUVWtCpxDivide ((&inUV1->buffer[indx]), (&inUV2->buffer[indx]), (&inUV1->buffer[indx]), work); indx += in1Desc->inaxes[0]; } /* end loop over correlations */ if (incompatible) break; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV1->buffer, err); if (same) { outUV->myDesc->firstVis = firstVis; ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis; } } /* end loop processing data */ /* Check for incompatibility */ if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible contents", routine); return; } /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* close files */ iretCode = ObitUVClose (inUV1, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); iretCode = ObitUVClose (inUV2, err); if (err->error) Obit_traceback_msg (err, routine, inUV2->name); oretCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); /* In case */ outUV->buffer = NULL; outUV->bufferSize = 0; /* Reset passAll */ btemp = FALSE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); } /* end ObitUVUtilVisDivide */ /** * Divide the cross pol visibilities in one ObitUV by I pol (avg parallel pol) * \param inUV Input uv data, if info member KeepSou TRUE, copy SU table. * \param outUV Previously defined output, may be the same as inUV * \param err Error stack, returns if not empty. */ void ObitUVUtilXPolDivide (ObitUV *inUV, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, indx, jndx, firstVis; olong iif, nif, ichan, nchan, istok, nstok, incs, incf, incif; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat work[3], Ivis[3], wt, Ireal, Iimag, Iwt; gboolean KeepSou, same; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; gchar *routine = "ObitUVUtilXPolDivide"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV)); g_assert (ObitUVIsA(outUV)); /* Are input1 and output the same file? */ same = ObitUVSame(inUV, outUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Keep source table? */ KeepSou = FALSE; ObitInfoListGetTest(inUV->info, "KeepSou", &type, (gint32*)dim, &KeepSou); /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine, inUV->name); /* Get input descriptor */ inDesc = inUV->myDesc; /* Set up for parsing data */ nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; /* get increments */ incs = inDesc->incs; incf = inDesc->incf; incif = inDesc->incif; /* Make sure at least 4 Stokes correlations */ Obit_return_if_fail ((nstok>=4), err, "%s: MUST have at least 4 Stokes, have %d", routine, nstok); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output. If multiple passes are made the input files will be closed which deallocates the buffer, use output buffer. so free input buffer */ if (!same) { /* use same data buffer on input 1 and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; } /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* Copy tables before data if in1 and out are not the same */ if (!ObitUVSame (inUV, outUV, err)) { iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out or KeepSou == TRUE */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources) || KeepSou) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } } if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* reset to beginning of uv data */ iretCode = ObitUVIOSet (inUV, err); oretCode = ObitUVIOSet (outUV, err); if (err->error) Obit_traceback_msg (err, routine,inUV->name); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV->name); iretCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV->name); outUV->buffer = inUV->buffer; outDesc = outUV->myDesc; /* Get output descriptor */ /* we're in business, divide */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { /* Read input */ iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; firstVis = inDesc->firstVis; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ indx = inDesc->nrparm + i*inDesc->lrec; /* loop over IF */ for (iif=0; iif<nif; iif++) { /* Loop over frequency channel */ for (ichan=0; ichan<nchan; ichan++) { /* loop 60 */ jndx = indx + iif*incif + ichan*incf; /* Get Stokes I - average parallel hands */ wt = inUV->buffer[jndx+2]; if (wt>0.0) { Ireal = wt*inUV->buffer[jndx]; Iimag = wt*inUV->buffer[jndx+1]; Iwt = wt; } else { Ireal = Iimag = Iwt = 0.0; } wt = inUV->buffer[jndx+5]; if (wt>0.0) { Ireal += wt*inUV->buffer[jndx+3]; Iimag += wt*inUV->buffer[jndx+4]; Iwt += wt; } if (Iwt > 0.0) { Ivis[0] = Ireal/Iwt; Ivis[1] = Iimag/Iwt; Ivis[2] = Iwt; } else { Ivis[0] = Ivis[1] = Ivis[2] = 0.0; } /* Loop over cross polarization */ for (istok=2; istok<nstok; istok++) { jndx = indx + iif*incif + ichan*incf + istok*incs; /* Divide */ ObitUVWtCpxDivide ((&inUV->buffer[jndx]), Ivis, (&inUV->buffer[jndx]), work); } /* end loop over Stokes */ } /* end loop over channels */ } /* end loop over IFs */ } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV->buffer, err); if (same) { outUV->myDesc->firstVis = firstVis; ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis; } } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV->name); /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* close files */ iretCode = ObitUVClose (inUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); oretCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); /* In case */ outUV->buffer = NULL; outUV->bufferSize = 0; } /* end ObitUVUtilXPolDivide */ /** * Subtract the visibilities in one ObitUV from those in another * outUV = inUV1 - inUV2 * \param inUV1 First input uv data, no calibration/selection * \param inUV2 Second input uv data, calibration/selection allowed * inUV2 should have the same structure, no. vis etc * as inUV1. * \param outUV Previously defined output, may be the same as inUV1 * \param err Error stack, returns on error */ void ObitUVUtilVisSub (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, firstVis; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong NPIO; gboolean incompatible, same, doCalSelect, btemp; ObitUVDesc *in1Desc, *in2Desc, *outDesc; ObitIOAccess access; gchar *today=NULL; gchar *routine = "ObitUVUtilVisSub"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV1)); g_assert (ObitUVIsA(inUV2)); g_assert (ObitUVIsA(outUV)); /* Are input1 and output the same file? */ same = ObitUVSame(inUV1, outUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output. If multiple passes are made the input files will be closed which deallocates the buffer, use output buffer. so free input buffer */ if (!same) { /* use same data buffer on input 1 and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; } /* Copy number of records per IO to second input */ ObitInfoListGet (inUV1->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListPut (inUV2->info, "nVisPIO", type, dim, (gpointer)&NPIO, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* Selection of second input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV2->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* Open second input */ iretCode = ObitUVOpen (inUV2, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV2->name); /* Get input descriptors */ in1Desc = inUV1->myDesc; in2Desc = inUV2->myDesc; /* Check compatability between inUV1, inUV2 */ incompatible = in1Desc->nvis!=in2Desc->nvis; incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr); incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs); incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf); incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif); incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb); if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible structures", routine); return ; } /* Look at all data */ btemp = TRUE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* Copy tables before data if in1 and out are not the same */ if (!ObitUVSame (inUV1, outUV, err)) { iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV1->name); } } if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* reset to beginning of uv data */ iretCode = ObitUVIOSet (inUV1, err); oretCode = ObitUVIOSet (outUV, err); if (err->error) Obit_traceback_msg (err, routine,inUV1->name); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV1, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); outUV->buffer = inUV1->buffer; outDesc = outUV->myDesc; /* Get output descriptor */ /* we're in business, subtract */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { /* Read first input */ iretCode = ObitUVRead (inUV1, inUV1->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* Read second input */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV2, inUV2->buffer, err); else iretCode = ObitUVRead (inUV2, inUV2->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = in1Desc->numVisBuff; firstVis = in1Desc->firstVis; /* compatability check */ incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff; if (incompatible) break; /* Modify data */ for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */ /* compatability check - check time and baseline or antenna code */ indx = i*in1Desc->lrec ; incompatible = inUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[indx+in2Desc->iloct]; if (in1Desc->ilocb>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[indx+in2Desc->ilocb]; } if (in1Desc->iloca1>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[indx+in2Desc->iloca1] || inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[indx+in2Desc->iloca2]; } if (incompatible) break; indx += in1Desc->nrparm; for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */ /* subtract */ if ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[indx+2]>0.0)) { inUV1->buffer[indx] -= inUV2->buffer[indx]; inUV1->buffer[indx+1] -= inUV2->buffer[indx+1]; /* this blanks poln data } else { inUV1->buffer[indx] = 0.0; inUV1->buffer[indx+1] = 0.0; inUV1->buffer[indx+2] = 0.0;*/ } indx += in1Desc->inaxes[0]; } /* end loop over correlations */ if (incompatible) break; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV1->buffer, err); /* suppress vis number update if rewriting the same file */ if (same) { outUV->myDesc->firstVis = firstVis; ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis; } } /* end loop processing data */ /* Check for incompatibility */ if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible contents", routine); return; } /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* Reset passAll */ btemp = FALSE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); /* close files */ iretCode = ObitUVClose (inUV1, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); iretCode = ObitUVClose (inUV2, err); if (err->error) Obit_traceback_msg (err, routine, inUV2->name); oretCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); } /* end ObitUVUtilVisSub */ /** * Subtract the 1st visibility in one ObitUV from those in another * outUV = inUV1[*] - inUV2[0] * \param inUV1 First input uv data, no calibration/selection * \param inUV2 Second input uv data, calibration/selection allowed * inUV2 should have the same structure, only the 1st * visibility used and subtracted from all in inUV1 * \param outUV Previously defined output, may be the same as inUV1 * \param err Error stack, returns on error */ void ObitUVUtilVisSub1 (ObitUV *inUV1, ObitUV *inUV2, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, kndx, firstVis; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong NPIO; gboolean incompatible, same, doCalSelect, btemp; ObitUVDesc *in1Desc, *in2Desc, *outDesc; ObitIOAccess access; gchar *today=NULL; gchar *routine = "ObitUVUtilVisSub1"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV1)); g_assert (ObitUVIsA(inUV2)); g_assert (ObitUVIsA(outUV)); /* Are input1 and output the same file? */ same = ObitUVSame(inUV1, outUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV1->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output. If multiple passes are made the input files will be closed which deallocates the buffer, use output buffer. so free input buffer */ if (!same) { /* use same data buffer on input 1 and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; } /* Copy number of records per IO to second input */ ObitInfoListGet (inUV1->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListPut (inUV2->info, "nVisPIO", type, dim, (gpointer)&NPIO, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* Selection of second input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV2->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* Open second input */ iretCode = ObitUVOpen (inUV2, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV2->name); /* Get input descriptors */ in1Desc = inUV1->myDesc; in2Desc = inUV2->myDesc; /* Check compatability between inUV1, inUV2 */ incompatible = (in1Desc->ncorr!=in2Desc->ncorr); incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs); incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf); incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif); incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb); if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible structures", routine); return ; } /* Look at all data */ btemp = TRUE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* Copy tables before data if in1 and out are not the same */ if (!ObitUVSame (inUV1, outUV, err)) { iretCode = ObitUVCopyTables (inUV1, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV1->mySel->numberSourcesList>1) || (!inUV1->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV1, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV1->name); } } if (err->error) Obit_traceback_msg (err, routine, inUV1->name); /* reset to beginning of uv data */ iretCode = ObitUVIOSet (inUV1, err); oretCode = ObitUVIOSet (outUV, err); if (err->error) Obit_traceback_msg (err, routine,inUV1->name); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV1, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV1->name); outUV->buffer = inUV1->buffer; outDesc = outUV->myDesc; /* Get output descriptor */ /* Read vis from second input */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV2, inUV2->buffer, err); else iretCode = ObitUVRead (inUV2, inUV2->buffer, err); if (err->error) Obit_traceback_msg (err, routine,inUV2->name); /* we're in business, subtract */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { /* Read first input */ iretCode = ObitUVRead (inUV1, inUV1->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = in1Desc->numVisBuff; firstVis = in1Desc->firstVis; /* Modify data */ for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */ indx = i*in1Desc->lrec+ in1Desc->nrparm; kndx = in2Desc->nrparm; for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */ /* subtract */ if ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[kndx+2]>0.0)) { inUV1->buffer[indx] -= inUV2->buffer[kndx]; inUV1->buffer[indx+1] -= inUV2->buffer[kndx+1]; /* this blanks poln data } else { inUV1->buffer[indx] = 0.0; inUV1->buffer[indx+1] = 0.0; inUV1->buffer[indx+2] = 0.0;*/ } indx += in1Desc->inaxes[0]; kndx += in2Desc->inaxes[0]; } /* end loop over correlations */ if (incompatible) break; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV1->buffer, err); /* suppress vis number update if rewriting the same file */ if (same) { outUV->myDesc->firstVis = firstVis; ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis; } } /* end loop processing data */ /* Check for incompatibility */ if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible contents", routine); return; } /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV1->name); /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* Reset passAll */ btemp = FALSE; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(inUV1->info, "passAll", OBIT_bool, dim, &btemp); ObitInfoListAlwaysPut(inUV2->info, "passAll", OBIT_bool, dim, &btemp); /* close files */ iretCode = ObitUVClose (inUV1, err); if (err->error) Obit_traceback_msg (err, routine, inUV1->name); iretCode = ObitUVClose (inUV2, err); if (err->error) Obit_traceback_msg (err, routine, inUV2->name); oretCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); } /* end ObitUVUtilVisSub1 */ /** * Compare the visibilities in one ObitUV with those in another. * Return the RMS of the real and imaginary differences * divided by the amplitude of inUV2. * Only valid visibilities compared, zero amplitudes ignored. * \param inUV1 Input uv data numerator, no calibration/selection * Control parameter on info * \li printRat OBIT_float (1) If given and >0.0 then tell about entries * with a real or imaginary ratio > printRat * \param inUV2 Input uv data denominator, no calibration/selection * inUV2 should have the same structure, no. vis etc * as inUV1. * \param err Error stack, returns if not empty. * \return RMS of the real and imaginary differences /amplitude, * -1 => no data compared or other error. */ ofloat ObitUVUtilVisCompare (ObitUV *inUV1, ObitUV *inUV2, ObitErr *err) { ObitIOCode iretCode; olong i, j, indx, jndx, vscnt; ollong count, vNo; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; olong NPIO; ofloat amp, rms = -1.0, rrat, irat, printRat=-1.0; odouble sum; gboolean incompatible; ObitUVDesc *in1Desc, *in2Desc; gchar *routine = "ObitUVUtilVisCompare"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return rms; g_assert (ObitUVIsA(inUV1)); g_assert (ObitUVIsA(inUV2)); /* Diagnostics? */ ObitInfoListGetTest(inUV1->info, "printRat", &type, dim, &printRat); /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV1, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine,inUV1->name, rms); /* Copy number of records per IO to second input */ ObitInfoListGet (inUV1->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListPut (inUV2->info, "nVisPIO", type, dim, (gpointer)&NPIO, err); if (err->error) Obit_traceback_val (err, routine, inUV1->name, rms); /* Open second input */ iretCode = ObitUVOpen (inUV2, OBIT_IO_ReadWrite, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine,inUV2->name, rms); /* Get input descriptors */ in1Desc = inUV1->myDesc; in2Desc = inUV2->myDesc; /* Check compatability between inUV1, inUV2 */ incompatible = in1Desc->nvis!=in2Desc->nvis; incompatible = incompatible || (in1Desc->ncorr!=in2Desc->ncorr); incompatible = incompatible || (in1Desc->jlocs!=in2Desc->jlocs); incompatible = incompatible || (in1Desc->jlocf!=in2Desc->jlocf); incompatible = incompatible || (in1Desc->jlocif!=in2Desc->jlocif); incompatible = incompatible || (in1Desc->ilocb!=in2Desc->ilocb); if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible structures", routine); return rms; } /* we're in business, loop comparing */ count = 0; vscnt = 0; sum = 0.0; while (iretCode==OBIT_IO_OK) { /* Read first input */ iretCode = ObitUVRead (inUV1, inUV1->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* Read second input */ iretCode = ObitUVRead (inUV2, inUV2->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* compatability check */ incompatible = in1Desc->numVisBuff!=in2Desc->numVisBuff; if (incompatible) break; /* Compare data */ for (i=0; i<in1Desc->numVisBuff; i++) { /* loop over visibilities */ vscnt++; /* compatability check - check time and baseline or antenna code */ indx = i*in1Desc->lrec ; jndx = i*in2Desc->lrec ; incompatible = inUV1->buffer[indx+in1Desc->iloct] !=inUV2->buffer[jndx+in2Desc->iloct]; if (in1Desc->ilocb>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->ilocb] !=inUV2->buffer[jndx+in2Desc->ilocb]; } if (in1Desc->iloca1>=0) { incompatible = incompatible || inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[jndx+in2Desc->iloca1] || inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[jndx+in2Desc->iloca2]; } if (incompatible) { vNo = indx+in1Desc->firstVis + i; /* Which visibility */ if (inUV1->buffer[indx+in1Desc->iloct]!=inUV2->buffer[jndx+in2Desc->iloct]) Obit_log_error(err, OBIT_Error, "Incompatible Times %f != %f @ vis %ld", inUV1->buffer[indx+in1Desc->iloct], inUV2->buffer[jndx+in2Desc->iloct], vNo); if ((in1Desc->ilocb>=0) && (inUV1->buffer[indx+in1Desc->ilocb]!=inUV2->buffer[jndx+in2Desc->ilocb])) Obit_log_error(err, OBIT_Error, "Incompatible Baselines %f != %f @ vis %ld", inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo); if ((in1Desc->iloca2>=0) && (inUV1->buffer[indx+in1Desc->iloca1]!=inUV2->buffer[jndx+in2Desc->iloca1])) Obit_log_error(err, OBIT_Error, "Incompatible Antenna 1 %f != %f @ vis %ld", inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo); if ((in1Desc->iloca2>=0) && (inUV1->buffer[indx+in1Desc->iloca2]!=inUV2->buffer[jndx+in2Desc->iloca2])) Obit_log_error(err, OBIT_Error, "Incompatible Antenna 2 %f != %f @ vis %ld", inUV1->buffer[indx+in1Desc->ilocb], inUV2->buffer[jndx+in2Desc->ilocb], vNo); break; } indx += in1Desc->nrparm; jndx += in2Desc->nrparm; for (j=0; j<in1Desc->ncorr; j++) { /* loop over correlations */ /* Statistics */ amp = inUV2->buffer[jndx]*inUV2->buffer[jndx] + inUV2->buffer[jndx+1]*inUV2->buffer[jndx+1]; if ((inUV1->buffer[indx+2]>0.0) && (inUV2->buffer[indx+2]>0.0) && (amp>0.0)) { amp = sqrt(amp); rrat = ((inUV1->buffer[indx] - inUV2->buffer[jndx]) * (inUV1->buffer[indx] - inUV2->buffer[jndx])) / amp; irat = ((inUV1->buffer[indx+1] - inUV2->buffer[jndx+1]) * (inUV1->buffer[indx+1] - inUV2->buffer[jndx+1])) / amp; sum += rrat + irat; count += 2; /* Diagnostics */ if ((printRat>0.0) && ((rrat>printRat) || (irat>printRat))) { Obit_log_error(err, OBIT_InfoWarn, "High ratio vis %d corr %d ratio %f %f amp %f vis %f %f - %f %f", vscnt, j+1, rrat, irat, amp, inUV1->buffer[indx], inUV1->buffer[indx+1], inUV2->buffer[jndx], inUV2->buffer[jndx+1]); } } indx += in1Desc->inaxes[0]; jndx += in2Desc->inaxes[0]; } /* end loop over correlations */ if (incompatible) break; } /* end loop over visibilities */ } /* end loop processing data */ /* Check for incompatibility */ if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV1 and inUV2 have incompatible contents", routine); return rms; } /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (err->error)) Obit_traceback_val (err, routine,inUV1->name, rms); /* close files */ iretCode = ObitUVClose (inUV1, err); if (err->error) Obit_traceback_val (err, routine, inUV1->name, rms); iretCode = ObitUVClose (inUV2, err); if (err->error) Obit_traceback_val (err, routine, inUV2->name, rms); /* Get RMS to return */ if (count>0) rms = sqrt(sum / count); else rms = -1.0; return rms; } /* end ObitUVUtilVisCompare */ /** * Reads the UV and rewrites its Index (AIPS NX) table * \param inUV Input UV data. * Control parameters are on the info member. * \li "maxScan" OBIT_float (1,1,1) max. scan time, min. [def LARGE] * \li "maxGap" OBIT_float (1,1,1) max. time gap in scan, min. [def LARGE] * \param err Error stack, returns if not empty. */ void ObitUVUtilIndex (ObitUV *inUV, ObitErr *err) { ObitIOCode retCode; ObitTableNX* table; ObitTableNXRow* row=NULL; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitInfoType type; olong num, i, iRow, ver, startVis=1, curVis, itemp, jtemp; olong suba, lastSubA=0, source, lastSource=0, fqid, lastFQID=0; ofloat maxScan, maxGap, *vis; odouble startTime=0.0, endTime=0.0, lastTime = -1.0e20; gchar *routine = "ObitUVUtilIndex"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV)); /* Get maximum scan length */ maxScan = 1.0e20; ObitInfoListGetTest(inUV->info, "maxScan", &type, dim, &maxScan); maxScan /= 1440.0; /* to days */ /* Get maximum scan gap */ maxGap = 1.0e20; ObitInfoListGetTest(inUV->info, "maxGap", &type, dim, &maxGap); maxGap /= 1440.0; /* to days */ /* Open UV */ inUV->bufferSize = MAX (0, inUV->bufferSize); /* Need buffer */ retCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inUV->name); lastSubA = -1000; /* initialize subarray number */ lastFQID = -1000; /* initialize FQ Id */ lastSource = -1000; /* initialize source number */ curVis = 0; /* visibility counter */ /* create Index table object */ ver = 1; table = newObitTableNXValue ("Index table", (ObitData*)inUV, &ver, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Clear existing rows */ ObitTableClearRows ((ObitTable*)table, err); if (err->error) goto cleanup; /* Open Index table */ if ((ObitTableNXOpen (table, OBIT_IO_WriteOnly, err) != OBIT_IO_OK) || (err->error)) goto cleanup; /* Create Index Row */ row = newObitTableNXRow (table); /* initialize row */ row->SourID = 0; row->SubA = 0; row->Time = 0.0; row->TimeI = 0.0; row->StartVis = -1; row->EndVis = -1; row->FreqID = 0; fqid = 1; source = 1; /* attach to table buffer */ ObitTableNXSetRow (table, row, err); if (err->error) goto cleanup; /* Write at beginning of UVIndex Table */ iRow = 0; table->myDesc->nrow = 0; /* ignore any previous entries */ /* Loop over UV */ while (retCode==OBIT_IO_OK) { retCode = ObitUVRead (inUV, inUV->buffer, err); /*if (retCode!=OBIT_IO_OK) fprintf(stderr, "retcode=%d\n", retCode);*/ /* EOF is OK */ if (retCode==OBIT_IO_EOF) ObitErrClear(err); if (retCode!=OBIT_IO_OK) break; if (err->error) goto cleanup; /* How many */ num = inUV->myDesc->numVisBuff; /* Visibility pointer */ vis = inUV->buffer; /* initialize on first visibility */ if (curVis<=0) { startVis = 1; startTime = vis[inUV->myDesc->iloct]; lastTime = vis[inUV->myDesc->iloct]; } /* Loop over buffer */ for (i=0; i<num; i++) { curVis++; /* Current UV visibility number */ /* require some time change for further checks */ if (vis[inUV->myDesc->iloct]==lastTime) goto endloop; /* Subarray number */ ObitUVDescGetAnts(inUV->myDesc, vis, &itemp, &jtemp, &suba); if (inUV->myDesc->ilocfq>=0) fqid = vis[inUV->myDesc->ilocfq] + 0.5; /* Which FQ Id */ if (inUV->myDesc->ilocsu>=0) source = vis[inUV->myDesc->ilocsu] + 0.5; /* Source number */ /* Initialize? */ if (lastFQID<=0) lastFQID = fqid; if (lastSubA<=0) lastSubA = suba; if (lastSource<=0) lastSource = source; /* New scan - change of source, fqid, or reach time limit */ if (((suba!=lastSubA) && (lastSubA>0)) || ((source!=lastSource) && (lastSource>0)) || ((fqid!=lastFQID) && (lastFQID>0)) || ((vis[inUV->myDesc->iloct]-lastTime) > maxGap) || ((vis[inUV->myDesc->iloct]-startTime)>maxScan)) { /* Write index */ /* Fill index record */ if (lastSource>0) row->SourID = lastSource; if (lastFQID>0) row->FreqID = lastFQID; if (lastSubA>0) row->SubA = lastSubA; row->Time = 0.5 * (startTime + endTime); row->TimeI = (endTime - startTime); row->StartVis = startVis; row->EndVis = curVis-1; /* Write Index table */ iRow++; if ((ObitTableNXWriteRow (table, iRow, row, err) != OBIT_IO_OK) || (err->error>0)) goto cleanup; /* Initialize next suba */ lastSubA = suba; lastFQID = fqid; lastSource = source; startVis = curVis; startTime = vis[inUV->myDesc->iloct]; endTime = vis[inUV->myDesc->iloct]; } /* end of if new scan */ endloop: endTime = vis[inUV->myDesc->iloct]; /* potential end time */ lastTime = vis[inUV->myDesc->iloct]; /* time of last vis */ vis += inUV->myDesc->lrec; /* Update data visibility pointer */ } /* end loop over buffer */ } /* End loop over UV */ /* Last Scan */ if (lastSource>0) row->SourID = lastSource; if (lastFQID>0) row->FreqID = lastFQID; if (lastSubA>0) row->SubA = lastSubA; row->Time = 0.5 * (startTime + endTime); row->TimeI = (endTime - startTime); row->StartVis = startVis; row->EndVis = curVis; /* Write Index table */ iRow++; if ((ObitTableNXWriteRow (table, iRow, row, err) != OBIT_IO_OK) || (err->error>0)) goto cleanup; /* Close Index table */ cleanup: if ((ObitTableNXClose (table, err) != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, table->name); /* Cleanup */ row = ObitTableNXRowUnref(row); table = ObitTableNXUnref(table); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Close UV */ retCode = ObitUVClose (inUV, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inUV->name); } /* end ObitUVUtilIndex */ /** * Return a SourceList containing selected sources * Uses following criteria: * \li initially select all source in SU table * If no SU table, a single entry is returned. * \li Any explicit selection in Sources parameter in UV data selector * \li selection by CalCode * \li selection to exclude any entries marked done in the PS table * if Infolist item 'doPS' is True. * \li if time range given and an NX table exists, only select * sources with data in this timerange. * \param inUV UV data with all selection criteria, other controls: * \li "doPS" OBIT_bool (1,1,1) If true and PS 1 exists, exclude [def False] * \li "souCode" OBIT_string (4,1,1) Source Cal code desired, ' ' => any code selected * '* ' => any non blank code (calibrators only) * '-CAL' => blank codes only (no calibrators) * def = ' ' * any sources marked done in PS table 1. * \param *err ObitErr error stack. * \return requested ObitSourceList */ ObitSourceList* ObitUVUtilWhichSources (ObitUV *inUV, ObitErr *err) { olong iver, i, j, count; ObitTableSU *SUTable=NULL; ObitTableNX *NXTable=NULL; ObitTablePS *PSTable=NULL; ObitSourceList *out=NULL, *tsList=NULL; ObitInfoType type; olong theRow; gint32 dim[MAXINFOELEMDIM]; gboolean want, allCal, allNCal, doTime, doPS, *good=NULL; gchar souCode[5]; gchar *routine = "ObitUVUtilWhichSources"; /* Full Source list */ iver = 1; SUTable = newObitTableSUValue (inUV->name, (ObitData*)inUV, &iver, OBIT_IO_ReadOnly, 0, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, out); if (SUTable) { tsList = ObitTableSUGetList (SUTable, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, out); } else { /* Use position /name from header */ out = ObitSourceListCreate ("SList", 1); strncpy (out->SUlist[0]->SourceName, inUV->myDesc->object, MIN(20,UVLEN_VALUE)); out->SUlist[0]->equinox = inUV->myDesc->equinox; out->SUlist[0]->RAMean = inUV->myDesc->crval[inUV->myDesc->jlocr]; out->SUlist[0]->DecMean = inUV->myDesc->crval[inUV->myDesc->jlocd]; /* Compute apparent position */ ObitPrecessUVJPrecessApp (inUV->myDesc, out->SUlist[0]); return out; } SUTable = ObitTableSUUnref(SUTable); /* Done with table */ /* check selection and calcode */ souCode[0] = souCode[1] = souCode[2] = souCode[3] = ' ';souCode[4] = 0; ObitInfoListGetTest(inUV->info, "souCode", &type, dim, souCode); doPS = FALSE; ObitInfoListGetTest(inUV->info, "doPS", &type, dim, &doPS); allCal = !strncmp (souCode, "-CAL", 4); /* all calibrators */ allNCal = !strncmp (souCode, "* ", 4); /* All non calibrators */ /* Need other tables? */ if (doPS) { iver = 1; PSTable = newObitTablePSValue (inUV->name, (ObitData*)inUV, &iver, OBIT_IO_ReadOnly, err); if (!PSTable) doPS = FALSE; if (doPS) ObitTablePSOpen (PSTable, OBIT_IO_ReadOnly, err); } doTime = TRUE; if (doTime) { iver = 1; NXTable = newObitTableNXValue (inUV->name, (ObitData*)inUV, &iver, OBIT_IO_ReadOnly, err); if (!NXTable) doTime = FALSE; if (doTime) ObitTableNXOpen (NXTable, OBIT_IO_ReadOnly, err); } /* Keep track of the good ones */ good = g_malloc0(tsList->number*sizeof(gboolean)); for (i=0; i<tsList->number; i++) good[i] = TRUE; /* Loop over list */ for (i=0; i<tsList->number; i++) { /* Explicitly stated */ want = ObitUVSelWantSour(inUV->mySel, tsList->SUlist[i]->SourID); if (allCal || allNCal) { /* Calibrator/non calibrator */ want = want && ((allCal && !strncmp(tsList->SUlist[i]->CalCode, " ", 4)) || (allNCal && strncmp(tsList->SUlist[i]->CalCode, " ", 4))); } /* Timerange */ if (doTime) { want = want && ObitTableNXWantSour (NXTable, tsList->SUlist[i]->SourID, inUV->mySel->timeRange, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, out); /* Already done in PS table? */ if (doPS) { want = want && ObitTablePSWantSour (PSTable, tsList->SUlist[i]->SourceName, &theRow, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, out); /* Want this one? */ if (!want) good[i] = FALSE; } /* End loop over list */ /* Close tables */ if (doPS) ObitTablePSClose (PSTable, err); if (doTime) ObitTableNXClose (NXTable, err); if (NXTable) NXTable = ObitTableNXUnref(NXTable); /* Done with table */ if (PSTable) PSTable = ObitTablePSUnref(PSTable); /* Done with table */ /* create output with only valid entries Count valid */ count = 0; for (i=0; i<tsList->number; i++) if (good[i]) count++; out = ObitSourceListCreate ("Desired source list", count); /* Copy */ j = 0; for (i=0; i<tsList->number; i++) { if (good[i]) { out->SUlist[j] = ObitSourceCopy(tsList->SUlist[i], out->SUlist[j], err); j++; } } tsList = ObitSourceListUnref (tsList); /* free old */ if (good) g_free(good); return out; } /* end ObitUVUtilWhichSources */ /** * Hanning smooth the data inObitUV. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameters are on the info member. * \li "doDescm" OBIT_bool (1,1,1) Descimate data after Hanning [def TRUE] * * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilHann (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect, doDescm; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong NumChAvg, i, j, indx, jndx; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; ofloat *work=NULL, scale; gchar *routine = "ObitUVUtilHann"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); /*ObitUVClone (inUV, outUV, err);*/ } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Descimate output? */ doDescm = TRUE; ObitInfoListGetTest(inUV->info, "doDescm", &type, dim, &doDescm); /* Effectively averaging 2 channels if doDescm */ if (doDescm) NumChAvg = 2; else NumChAvg = 1; dim[0] = dim[1] = dim[2] = dim[3] = dim[4] = 1; ObitInfoListAlwaysPut(inUV->info, "NumChAvg", OBIT_long, dim, &NumChAvg); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work array for averaging */ work = g_malloc(2*inDesc->lrec*sizeof(ofloat)); /* Modify descriptor for affects of averaging, get u,v,w scaling */ ObitUVGetFreq (inUV, err); /* Make sure frequencies updated */ if (err->error) goto cleanup; /* Update output Descriptor */ if (doDescm) {/* No descimate - basically moving up one (input) channel */ outDesc->crpix[outDesc->jlocf] = 0.5+inDesc->crpix[inDesc->jlocf]/2.0; outDesc->cdelt[outDesc->jlocf] = inDesc->cdelt[inDesc->jlocf]*2; outDesc->inaxes[outDesc->jlocf] = inDesc->inaxes[inDesc->jlocf]/2; } else { /* No descimate */ outDesc->crpix[outDesc->jlocf] = inDesc->crpix[inDesc->jlocf]; } scale = 1.0; /* Haven't really changed the frequency */ /* If descimating, last channel incomplete - drop */ if (doDescm) outDesc->inaxes[outDesc->jlocf]--; /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); /* FQ table selection */ iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err); /* Correct FQ table for averaging FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */ if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ /* Copy random parameters */ indx = i*inDesc->lrec; jndx = i*outDesc->lrec; for (j=0; j<inDesc->nrparm; j++) outUV->buffer[jndx+j] = inUV->buffer[indx+j]; /* Scale u,v,w for new reference frequency */ outUV->buffer[jndx+outDesc->ilocu] *= scale; outUV->buffer[jndx+outDesc->ilocv] *= scale; outUV->buffer[jndx+outDesc->ilocw] *= scale; /* Smooth data */ indx += inDesc->nrparm; jndx += outDesc->nrparm; /* Average data */ Hann (inUV->myDesc, outUV->myDesc, doDescm, &inUV->buffer[indx], &outUV->buffer[jndx], work, err); if (err->error) goto cleanup; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, outUV->buffer, err); if (err->error) goto cleanup; } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: if (work) g_free(work); work = NULL; /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilHann */ /** * Duplicate channels in input to output. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameters are on the info member. * \li "unHann" OBIT_bool (1,1,1) Undo previous Hanning? [def FALSE] * \li "nBloat" OBIT_int (1,1,1) Number of duplicates of each channel [def 2] * * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilBloat (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect, unHann; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, jndx; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; olong nBloat=2; ofloat scale; gchar *routine = "ObitUVUtilBloat"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); /*ObitUVClone (inUV, outUV, err);*/ } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* How much bloat output? */ nBloat = 2; ObitInfoListGetTest(inUV->info, "nBloat", &type, dim, &nBloat); unHann = FALSE; ObitInfoListGetTest(inUV->info, "unHann", &type, dim, &unHann); if (unHann) nBloat = 2; /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Modify descriptor for affects of averaging, get u,v,w scaling */ ObitUVGetFreq (inUV, err); /* Make sure frequencies updated */ scale = BloatFSetDesc (inDesc, outDesc, nBloat, err); if (err->error) goto cleanup; /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); /* FQ table selection */ iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err); /* Correct FQ table for averaging FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */ if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ /* Copy random parameters */ indx = i*inDesc->lrec; jndx = i*outDesc->lrec; for (j=0; j<inDesc->nrparm; j++) outUV->buffer[jndx+j] = inUV->buffer[indx+j]; /* Scale u,v,w for new reference frequency */ outUV->buffer[jndx+outDesc->ilocu] *= scale; outUV->buffer[jndx+outDesc->ilocv] *= scale; outUV->buffer[jndx+outDesc->ilocw] *= scale; /* Smooth data */ indx += inDesc->nrparm; jndx += outDesc->nrparm; /* duplicate channels */ Bloat (inUV->myDesc, outUV->myDesc, nBloat, unHann, &inUV->buffer[indx], &outUV->buffer[jndx], err); if (err->error) goto cleanup; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, outUV->buffer, err); if (err->error) goto cleanup; } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilBloat */ /** * Spectrally average the data inObitUV. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameters on info element of inUV: * \li "NumChAvg" OBIT_long scalar Number of channels to average, [def. = all] * \li "doAvgAll" OBIT_bool Scalar, if TRUE then average all channels and * IF. default = FALSE * \li "ChanSel" OBIT_int (4,*) Groups of channels to consider (relative to * channels & IFs selected by BChan, EChan, BIF, EIF) * (start, end, increment, IF) where start and end at the * beginning and ending channel numbers (1-rel) of the group * to be included, increment is the increment between * selected channels and IF is the IF number (1-rel) * default increment is 1, IF=0 means all IF. * The list of groups is terminated by a start <=0 * Default is all channels in each IF. * \li "noScale" OBIT_bool Scalar, if TRUE then do NOT scale u,v,w for new * frequency. Used for holography data. def FALSE * * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilAvgF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, jndx; olong *corChan=NULL, *corIF=NULL, *corStok=NULL; gboolean *corMask=NULL; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; ofloat *work=NULL, scale; olong NumChAvg, *ChanSel=NULL; gboolean doAvgAll, noScale; olong defSel[] = {1,-10,1,0, 0,0,0,0}; gchar *routine = "ObitUVUtilAvgF"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Get Parameters */ NumChAvg = -1; ObitInfoListGetTest(inUV->info, "NumChAvg", &type, dim, &NumChAvg); doAvgAll = FALSE; ObitInfoListGetTest(inUV->info, "doAvgAll", &type, dim, &doAvgAll); noScale = FALSE; ObitInfoListGetTest(inUV->info, "noScale", &type, dim, &noScale); ChanSel = NULL; if (!ObitInfoListGetP(inUV->info, "ChanSel", &type, dim, (gpointer)&ChanSel)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* ChanSel all zero? => default */ if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); /*ObitUVClone (inUV, outUV, err);*/ } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Default frequency group selection? Average all */ if (ChanSel == defSel) defSel[1] = inUV->myDesc->inaxes[inUV->myDesc->jlocf]; /* Default number of channels to average = all */ if ((NumChAvg<=0) || doAvgAll) NumChAvg = inUV->myDesc->inaxes[inUV->myDesc->jlocf]; NumChAvg = MIN (NumChAvg, inUV->myDesc->inaxes[inUV->myDesc->jlocf]); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work array for averaging */ work = g_malloc(2*inDesc->lrec*sizeof(ofloat)); /* Work arrays defining data */ corChan = g_malloc(inDesc->ncorr*sizeof(olong)); corIF = g_malloc(inDesc->ncorr*sizeof(olong)); corStok = g_malloc(inDesc->ncorr*sizeof(olong)); corMask = g_malloc(inDesc->ncorr*sizeof(gboolean)); /* Modify descriptor for affects of averaging, get u,v,w scaling */ ObitUVGetFreq (inUV, err); /* Make sure frequencies updated */ scale = AvgFSetDesc (inDesc, outDesc, NumChAvg, ChanSel, doAvgAll, corChan, corIF, corStok, corMask, err); if (err->error) goto cleanup; /* Scale u,v,w? */ if (noScale) scale = 1.0; /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); /* FQ table selection */ iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err); /* Correct FQ table for averaging FQSel (outUV, NumChAvg, 1, err); done in FQSelect(?) */ if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ /* Copy random parameters */ indx = i*inDesc->lrec; jndx = i*outDesc->lrec; for (j=0; j<inDesc->nrparm; j++) outUV->buffer[jndx+j] = inUV->buffer[indx+j]; /* Scale u,v,w for new reference frequency */ outUV->buffer[jndx+outDesc->ilocu] *= scale; outUV->buffer[jndx+outDesc->ilocv] *= scale; outUV->buffer[jndx+outDesc->ilocw] *= scale; /* Average data */ indx += inDesc->nrparm; jndx += outDesc->nrparm; /* Average data */ AvgFAver (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, corChan, corIF, corStok, corMask, &inUV->buffer[indx], &outUV->buffer[jndx], work, err); if (err->error) goto cleanup; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, outUV->buffer, err); if (err->error) goto cleanup; } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: if (work) g_free(work); work = NULL; if (corChan) g_free(corChan); corChan = NULL; if (corIF) g_free(corIF); corIF = NULL; if (corStok) g_free(corStok); corStok = NULL; if (corMask) g_free(corMask); corMask = NULL; /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilAvgF */ /** * Temporally average the data inObitUV. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameter on info element of inUV: * \li "timeAvg" OBIT_float (1,1,1) Time interval over which to average * (min) [def = 1 min.] * NB: this should be at least 2 integrations. * * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilAvgT (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; olong ncorr, nrparm, numAnt, jtemp; ollong lltmp, i, j, numBL, jndx, indx, blindx, iindx=0, nvis; ollong *blLookup=NULL; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; ObitUVSortBuffer *outBuffer=NULL; olong suba, lastSourceID, curSourceID, lastSubA; gchar *today=NULL; ofloat timeAvg, curTime, startTime, endTime; ofloat *accVis=NULL, *accRP=NULL, *ttVis=NULL; ofloat *inBuffer; olong ant1, ant2; olong ivis=0, NPIO; gboolean done, gotOne; gchar *routine = "ObitUVUtilAvgT"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Get Parameter - Time interval */ timeAvg = 1.0; /* default 1 min */ ObitInfoListGetTest(inUV->info, "timeAvg", &type, dim, &timeAvg); if (timeAvg<=(0.01/60.0)) timeAvg = 1.0; timeAvg /= 1440.0; /* convert to days */ /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ ObitUVClone (inUV, outUV, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); inBuffer = inUV->buffer; /* Local copy of buffer pointer */ /* Output creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Set number of output vis per read to twice number of baselines */ suba = 1; numAnt = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */ /* Better be some */ Obit_retval_if_fail ((numAnt>1), err, outUV, "%s Number of antennas NOT in descriptor", routine); numBL = (((ollong)numAnt)*(numAnt+1))/2; /* Include auto correlations */ NPIO = 1; ObitInfoListGetTest(inUV->info, "nVisPIO", &type, dim, &NPIO); jtemp = (olong)(2 * numBL); /* Might cause trouble if numBL VERY large */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(outUV->info, "nVisPIO", OBIT_long, dim, &jtemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work arrays for averaging */ ncorr = inUV->myDesc->ncorr; nrparm = inUV->myDesc->nrparm; lltmp = 4*numBL*ncorr*sizeof(ofloat); accVis = g_malloc0(lltmp); /* Vis */ lltmp = numBL*(nrparm+1)*sizeof(ofloat); accRP = g_malloc0(lltmp); /* Rand. parm */ ttVis = g_malloc0(( inUV->myDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */ /* Baseline lookup table */ blLookup = g_malloc0 (numAnt* sizeof(ollong)); blLookup[0] = 0; /* Include autocorr */ for (i=1; i<numAnt; i++) blLookup[i] = blLookup[i-1] + numAnt-i+1; /* Create sort buffer */ /* Make sort buffer big enough for four copies of each baseline */ nvis = 4 * numBL; nvis = MIN (nvis, inUV->myDesc->nvis); outBuffer = ObitUVSortBufferCreate ("Buffer", outUV, nvis, err); if (err->error) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Initialize things */ startTime = -1.0e20; endTime = 1.0e20; lastSourceID = -1; curSourceID = 0; outDesc->numVisBuff = 0; inBuffer = inUV->buffer; /* Local copy of buffer pointer */ /* Loop over intervals */ done = FALSE; gotOne = FALSE; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (err->error) goto cleanup; } /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done && (startTime>0.0)) goto process; /* Final? */ /* Make sure valid data found */ if (inUV->myDesc->numVisBuff<=0) continue; /* loop over visibilities */ for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { /* Copy random parameters */ iindx = ivis*inDesc->lrec; gotOne = FALSE; curTime = inBuffer[iindx+inDesc->iloct]; /* Time */ if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu]; if (startTime < -1000.0) { /* Set time window etc. if needed */ startTime = curTime; endTime = startTime + timeAvg; lastSourceID = curSourceID; } /* Still in current interval/source? */ if ((curTime<endTime) && (curSourceID == lastSourceID) && (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) { /* accumulate */ ObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA); /* Check antenna number */ Obit_retval_if_fail ((ant2<=numAnt), err, outUV, "%s Antenna 2=%d > max %d", routine, ant2, numAnt); /* Baseline index this assumes a1<=a2 always */ blindx = blLookup[ant1-1] + ant2-ant1; /* Accumulate RP (1,*) = count (2...,*) = Random parameters, sum u, v, w, time, int. */ jndx = blindx*(1+nrparm); accRP[jndx]++; for (i=0; i<nrparm; i++) { /* Sum known parameters to average */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct) || (i==inDesc->ilocit)) { accRP[jndx+i+1] += inBuffer[iindx+i]; } else { /* merely keep the rest */ accRP[jndx+i+1] = inBuffer[iindx+i]; } } /* end loop over parameters */ /* Accumulate Vis (1,*) = count (2,*) = sum Real (3,*) = sum Imag (4,*) = Sum Wt */ indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) { jndx = i*4 + blindx*4*ncorr; accVis[jndx] += 1.0; accVis[jndx+1] += inBuffer[indx]; accVis[jndx+2] += inBuffer[indx+1]; accVis[jndx+3] += inBuffer[indx+2]; } indx += 3; } /* end loop over correlations */; } else { /* process interval */ process: /* Now may have the next record in the IO Buffer */ if ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE; /* Loop over baselines writing average */ for (blindx=0; blindx<numBL; blindx++) { /* Anything this baseline? */ jndx = blindx*(1+nrparm); if (accRP[jndx]>0.0) { /* Average u, v, w, time random parameters */ indx = 0; for (i=0; i<nrparm; i++) { /* Average known parameters */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct)) accRP[jndx+i+1] /= accRP[jndx]; /* Copy to output buffer */ ttVis[indx++] = accRP[jndx+i+1]; } /* End random parameter loop */ /* Average vis data */ for (j=0; j<ncorr; j++) { jndx = j*4 + blindx*4*ncorr; if (accVis[jndx]>0.0) { accVis[jndx+1] /= accVis[jndx]; accVis[jndx+2] /= accVis[jndx]; } /* Copy to output buffer */ ttVis[indx++] = accVis[jndx+1]; ttVis[indx++] = accVis[jndx+2]; ttVis[indx++] = accVis[jndx+3]; } /* end loop over correlators */ /* Copy to Sort Buffer (Sorts and writes when full) */ ObitUVSortBufferAddVis(outBuffer, ttVis, endTime, err); if (err->error) goto cleanup; /* Write output one vis at a time outDesc->numVisBuff = 1; oretCode = ObitUVWrite (outUV, outBuffer, err); if (err->error) goto cleanup; */ } /* End any data this baseline */ } /* end loop over baselines */ /* Flush Sort Buffer */ ObitUVSortBufferFlush (outBuffer, err); if (err->error) Obit_traceback_val (err, routine, outUV->name, outUV); /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done) goto done; /* Reinitialize things */ startTime = -1.0e20; endTime = 1.0e20; for (i=0; i<4*ncorr*numBL; i++) accVis[i] = 0.0; for (i=0; i<(nrparm+1)*numBL; i++) accRP[i] = 0.0; /* Now accumulate this visibility */ ObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA); /* Baseline index this assumes a1<=a2 always */ /* Check antenna number */ Obit_retval_if_fail ((ant2<=numAnt), err, outUV, "%s Antenna 2=%d > max %d", routine, ant2, numAnt); blindx = blLookup[ant1-1] + ant2-ant1; /* Accumulate RP (1,*) = count (2...,*) = Random parameters, sum u, v, w, time, int. */ jndx = blindx*(1+nrparm); accRP[jndx]++; for (i=0; i<nrparm; i++) { /* Sum known parameters to average */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct) || (i==inDesc->ilocit)) { accRP[jndx+i+1] += inBuffer[iindx+i]; } else { /* merely keep the rest */ accRP[jndx+i+1] = inBuffer[iindx+i]; } } /* end loop over parameters */ /* Accumulate Vis (1,*) = count (2,*) = sum Real (3,*) = sum Imag (4,*) = Sum Wt */ indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) { jndx = i*4 + blindx*4*ncorr; accVis[jndx] += 1.0; accVis[jndx+1] += inBuffer[indx]; accVis[jndx+2] += inBuffer[indx+1]; accVis[jndx+3] += inBuffer[indx+2]; } indx += 3; } /* end loop over correlations */; } /* end process interval */ } /* end loop processing buffer of input data */ } /* End loop over input file */ /* End of processing */ done: /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Restore no vis per read in output */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (outUV->info, "nVisPIO", OBIT_long, dim, &NPIO); /* Cleanup */ cleanup: if (accVis) g_free(accVis); accVis = NULL; if (ttVis) g_free(ttVis); ttVis = NULL; if (accRP) g_free(accRP); accRP = NULL; if (blLookup) g_free(blLookup); blLookup = NULL; outBuffer = ObitUVSortBufferUnref(outBuffer); /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilAvgT */ /** * Average all visibilities in inUV, write single vis to outUV. * For single source data single vis, for multisource data, one vis per scan. * Data labeled as baseline 1-2 * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilAvg2One (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; olong ncorr, nrparm, numAnt, jtemp; ollong lltmp, i, j, numBL, jndx, indx, blindx, iindx=0; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; olong suba, lastSourceID, curSourceID; gchar *today=NULL; ofloat curTime, startTime, endTime; ofloat *accVis=NULL, *accRP=NULL, *ttVis=NULL; ofloat *inBuffer; olong ivis=0, NPIO; gboolean done, gotOne; gchar *routine = "ObitUVUtilAvgT"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ ObitUVClone (inUV, outUV, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); inBuffer = inUV->buffer; /* Local copy of buffer pointer */ /* Output creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Set number of output vis per read to twice number of baselines */ suba = 1; numAnt = inUV->myDesc->numAnt[suba-1];/* actually highest antenna number */ /* Better be some */ Obit_retval_if_fail ((numAnt>1), err, outUV, "%s Number of antennas NOT in descriptor", routine); numBL = 1; /* Single output visibility */ NPIO = 1; ObitInfoListGetTest(inUV->info, "nVisPIO", &type, dim, &NPIO); jtemp = (olong)(numBL); dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(outUV->info, "nVisPIO", OBIT_long, dim, &jtemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work arrays for averaging */ ncorr = inUV->myDesc->ncorr; nrparm = inUV->myDesc->nrparm; lltmp = 4*numBL*ncorr*sizeof(ofloat); accVis = g_malloc0(lltmp); /* Vis */ lltmp = numBL*(nrparm+1)*sizeof(ofloat); accRP = g_malloc0(lltmp); /* Rand. parm */ ttVis = g_malloc0(( inUV->myDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */ /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Initialize things */ startTime = -1.0e20; endTime = 1.0e20; lastSourceID = -1; curSourceID = 0; outDesc->numVisBuff = 0; inBuffer = inUV->buffer; /* Local copy of buffer pointer */ /* Loop over intervals */ done = FALSE; gotOne = FALSE; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); } /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done && (startTime>0.0)) goto process; /* Final? */ /* Make sure valid data found */ if (inUV->myDesc->numVisBuff<=0) continue; /* loop over visibilities */ for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { /* Copy random parameters */ iindx = ivis*inDesc->lrec; gotOne = FALSE; curTime = inBuffer[iindx+inDesc->iloct]; /* Time */ if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu]; if (startTime < -1000.0) { /* Set time window etc. if needed */ startTime = curTime; endTime = startTime + 1000.0; lastSourceID = curSourceID; } /* Still in current interval/source? */ if ((curTime<endTime) && (curSourceID == lastSourceID) && (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) { /* accumulate all to one vis */ blindx = 0; /* Accumulate RP (1,*) = count (2...,*) = Random parameters, sum u, v, w, time, int. */ jndx = blindx*(1+nrparm); accRP[jndx]++; for (i=0; i<nrparm; i++) { /* zero u,v,w */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw)) inBuffer[iindx+i] = 0.0; /* Sum known parameters to average */ if ((i==inDesc->iloct) || (i==inDesc->ilocit)) { accRP[jndx+i+1] += inBuffer[iindx+i]; } else { /* merely keep the rest */ accRP[jndx+i+1] = inBuffer[iindx+i]; } } /* end loop over parameters */ /* Accumulate Vis (1,*) = count (2,*) = sum Real*wt (3,*) = sum Imag*wt (4,*) = Sum Wt */ indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) { jndx = i*4 + blindx*4*ncorr; accVis[jndx] += 1.0; accVis[jndx+1] += inBuffer[indx]*inBuffer[indx+2]; accVis[jndx+2] += inBuffer[indx+1]*inBuffer[indx+2]; accVis[jndx+3] += inBuffer[indx+2]; } indx += 3; } /* end loop over correlations */; } else { /* process interval */ process: /* Now may have the next record in the IO Buffer */ if ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE; /* Loop over baselines writing average */ for (blindx=0; blindx<numBL; blindx++) { /* Anything this baseline? */ jndx = blindx*(1+nrparm); if (accRP[jndx]>0.0) { /* Average u, v, w, time random parameters */ indx = 0; for (i=0; i<nrparm; i++) { /* Average known parameters */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct)) accRP[jndx+i+1] /= accRP[jndx]; /* Copy to output buffer */ ttVis[indx++] = accRP[jndx+i+1]; } /* End random parameter loop */ /* Set baseline to 1-2 */ ObitUVDescSetAnts(outDesc, ttVis, 1, 2, 1); /* Average vis data */ for (j=0; j<ncorr; j++) { jndx = j*4 + blindx*4*ncorr; if (accVis[jndx]>0.0) { accVis[jndx+1] /= accVis[jndx+3]; accVis[jndx+2] /= accVis[jndx+3]; } /* Copy to output buffer */ ttVis[indx++] = accVis[jndx+1]; ttVis[indx++] = accVis[jndx+2]; ttVis[indx++] = accVis[jndx+3]; } /* end loop over correlators */ /* Write output one vis at a time */ outDesc->numVisBuff = 1; oretCode = ObitUVWrite (outUV, ttVis, err); if (err->error) goto cleanup; } /* End any data this baseline */ } /* end loop over baselines */ /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done) goto done; /* Reinitialize things */ startTime = -1.0e20; endTime = 1.0e20; for (i=0; i<4*ncorr*numBL; i++) accVis[i] = 0.0; for (i=0; i<(nrparm+1)*numBL; i++) accRP[i] = 0.0; /* Now accumulate this visibility */ blindx = 0; /* Accumulate RP (1,*) = count (2...,*) = Random parameters, sum u, v, w, time, int. */ jndx = blindx*(1+nrparm); accRP[jndx]++; for (i=0; i<nrparm; i++) { /* Sum known parameters to average */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct) || (i==inDesc->ilocit)) { accRP[jndx+i+1] += inBuffer[iindx+i]; } else { /* merely keep the rest */ accRP[jndx+i+1] = inBuffer[iindx+i]; } } /* end loop over parameters */ /* Accumulate Vis (1,*) = count (2,*) = sum Real (3,*) = sum Imag (4,*) = Sum Wt */ indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) { jndx = i*4 + blindx*4*ncorr; accVis[jndx] += 1.0; accVis[jndx+1] += inBuffer[indx]*inBuffer[indx+2]; accVis[jndx+2] += inBuffer[indx+1]*inBuffer[indx+2]; accVis[jndx+3] += inBuffer[indx+2]; } indx += 3; } /* end loop over correlations */; } /* end process interval */ } /* end loop processing buffer of input data */ } /* End loop over input file */ /* End of processing */ done: /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Restore no vis per read in output */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (outUV->info, "nVisPIO", OBIT_long, dim, &NPIO); /* Cleanup */ cleanup: if (accVis) g_free(accVis); accVis = NULL; if (ttVis) g_free(ttVis); ttVis = NULL; if (accRP) g_free(accRP); accRP = NULL; /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilAvg2One */ /** * Spectrally smooth the data in ObitUV. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameters on info element of inUV: * \li "NumChSmo" OBIT_long scalar Number of channels to average, [def. = 3] * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilSmoF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong i, j, indx, jndx; olong *corChan=NULL, *corIF=NULL, *corStok=NULL; gboolean *corMask=NULL; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; ofloat *work=NULL; olong NumChSmo; gchar *routine = "ObitUVUtilSmoF"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Get Parameters */ NumChSmo = 3; ObitInfoListGetTest(inUV->info, "NumChSmo", &type, dim, &NumChSmo); /* Make sure odd */ Obit_retval_if_fail (((1+2*(NumChSmo/2))==NumChSmo), err, outUV, "%s NumChSmo MUST be odd not %d", routine,NumChSmo); /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Create scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); /*ObitUVClone (inUV, outUV, err);*/ } if (err->error) Obit_traceback_val (err, routine, inUV->name, inUV); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Don't smooth more channels than exist */ NumChSmo = MIN (NumChSmo, inUV->myDesc->inaxes[inUV->myDesc->jlocf]); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work array for smoothing */ work = g_malloc(2*inDesc->lrec*sizeof(ofloat)); /* Work arrays defining data */ corChan = g_malloc(inDesc->ncorr*sizeof(olong)); corIF = g_malloc(inDesc->ncorr*sizeof(olong)); corStok = g_malloc(inDesc->ncorr*sizeof(olong)); corMask = g_malloc(inDesc->ncorr*sizeof(gboolean)); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); /* FQ table selection */ iretCode = ObitTableFQSelect (inUV, outUV, NULL, 0.0, err); if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ /* Copy random parameters */ indx = i*inDesc->lrec; jndx = i*outDesc->lrec; for (j=0; j<inDesc->nrparm; j++) outUV->buffer[jndx+j] = inUV->buffer[indx+j]; /* Average data */ indx += inDesc->nrparm; jndx += outDesc->nrparm; /* Average data */ SmooF (inDesc, outDesc, NumChSmo, corChan, corIF, corStok, corMask, &inUV->buffer[indx], &outUV->buffer[jndx], work, err); if (err->error) goto cleanup; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, outUV->buffer, err); if (err->error) goto cleanup; } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: if (work) g_free(work); work = NULL; if (corChan) g_free(corChan); corChan = NULL; if (corIF) g_free(corIF); corIF = NULL; if (corStok) g_free(corStok); corStok = NULL; if (corMask) g_free(corMask); corMask = NULL; /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); return outUV; } /* end ObitUVUtilSmoF */ /** * Temporally average in a baseline dependent fashion the data in a ObitUV. * Also optionally average in frequency. * Time average UV data with averaging times depending * on time and baseline. The averaging time is the greater of * maxInt and the time it takes for time smearing to reduce the * visibility amplitude by maxFact. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * Control parameters on info element of inUV: * \li "FOV" OBIT_float (1,1,1) Field of view (radius, deg) * \li "maxInt" OBIT_float (1,1,1) Maximum integration (min) * \li "maxFact" OBIT_float (1,1,1) Maximum time smearing factor * \li "NumChAvg" OBIT_long scalar Number of channels to average, [def. = all] * \li "doAvgAll" OBIT_bool Scalar, if TRUE then average all channels and * IF. default = FALSE * \li "ChanSel" OBIT_int (4,*) Groups of channels to consider (relative to * channels & IFs selected by BChan, EChan, BIF, EIF) * (start, end, increment, IF) where start and end at the * beginning and ending channel numbers (1-rel) of the group * to be included, increment is the increment between * selected channels and IF is the IF number (1-rel) * default increment is 1, IF=0 means all IF. * The list of groups is terminated by a start <=0 * Default is all channels in each IF. * * \param scratch True if scratch file desired, will be same type as inUV. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. * \return the frequency averaged ObitUV. */ ObitUV* ObitUVUtilBlAvgTF (ObitUV *inUV, gboolean scratch, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; olong ncorr, nrparm, numAnt; ollong lltmp, numBL, i, j, jndx, indx, blLo, blHi, nvis, ivis=0, iindx=0; ollong blindx=0, *blLookup=NULL; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; olong suba, lastSourceID, curSourceID, lastSubA; gchar *today=NULL; ofloat curTime=-1.0e20, startTime; ofloat *accVis=NULL, *accRP=NULL, *lsBlTime=NULL, *stBlTime=NULL, *stBlU=NULL, *stBlV=NULL; ofloat *tVis=NULL, *ttVis=NULL; ofloat *inBuffer; ObitUVSortBuffer *outBuffer=NULL; ofloat FOV, maxTime, maxInt, maxFact, UVDist2, maxUVDist2; olong ant1=1, ant2=2; olong NPIO, itemp, count=0; gboolean done, gotOne, doAllBl, sameInteg; ofloat *work=NULL, scale=1.0; olong NumChAvg, *ChanSel=NULL; gboolean doAvgAll, doAvgFreq; olong defSel[] = {1,1000000000,1,0, 0,0,0,0}; olong *corChan=NULL, *corIF=NULL, *corStok=NULL; gboolean *corMask=NULL; gchar *routine = "ObitUVUtilAvgTF"; /* error checks */ if (err->error) return outUV; g_assert (ObitUVIsA(inUV)); if (!scratch && (outUV==NULL)) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined for non scratch files", routine); return outUV; } /* Give report */ Obit_log_error(err, OBIT_InfoErr, "Doing baseline dependent time averaging"); ObitErrLog(err); /* Get Parameters - radius of field of view */ FOV = 20.0/60.0; /* default 20 amin */ ObitInfoListGetTest(inUV->info, "FOV", &type, dim, &FOV); /* to radians */ FOV = MAX(FOV,1.0e-4) * DG2RAD; /* max. integration default 1 min */ maxInt = 1.0; ObitInfoListGetTest(inUV->info, "maxInt", &type, dim, &maxInt); if (maxInt<=(1.0e-2/60.0)) maxInt = 1.0; maxInt /= 1440.0; /* convert to days */ /* max amplitude loss default 1.01 */ maxFact = 1.01; ObitInfoListGetTest(inUV->info, "maxFact", &type, dim, &maxFact); if (maxFact<0.99) maxFact = 1.01; maxFact = MIN(MAX(maxFact,1.0), 10.0); /* Maximum UV distance squared to allow */ maxUVDist2 = (InvSinc(1.0/maxFact) / FOV); maxUVDist2 = maxUVDist2*maxUVDist2; /* Square */ /* Get Frequency Parameters */ NumChAvg = 0; ObitInfoListGetTest(inUV->info, "NumChAvg", &type, dim, &NumChAvg); NumChAvg = MAX(1, NumChAvg); doAvgAll = FALSE; ObitInfoListGetTest(inUV->info, "doAvgAll", &type, dim, &doAvgAll); ChanSel = NULL; if (!ObitInfoListGetP(inUV->info, "ChanSel", &type, dim, (gpointer)&ChanSel)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* ChanSel all zero? => default */ if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* Averaging in frequency? */ doAvgFreq = (NumChAvg>1) || doAvgAll; /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Is scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); ObitUVClone (inUV, outUV, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, outUV); inDesc = inUV->myDesc; /* Create work array for frequency averaging */ if (doAvgFreq) { work = g_malloc(2*inDesc->lrec*sizeof(ofloat)); /* Work arrays defining data */ corChan = g_malloc(inDesc->ncorr*sizeof(olong)); corIF = g_malloc(inDesc->ncorr*sizeof(olong)); corStok = g_malloc(inDesc->ncorr*sizeof(olong)); corMask = g_malloc(inDesc->ncorr*sizeof(gboolean)); /* Modify descriptor for affects of frequency averaging, get u,v,w scaling */ ObitUVGetFreq (inUV, err); /* Make sure frequencies updated */ scale = AvgFSetDesc (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, corChan, corIF, corStok, corMask, err); if (err->error) goto cleanup; } else { /* Only time averaging */ /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); } /* Get Parameters - radius of field of view */ FOV = 20.0/60.0; /* default 20 amin */ ObitInfoListGetTest(inUV->info, "FOV", &type, dim, &FOV); /* to radians */ FOV = MAX(FOV,1.0e-4) * DG2RAD; /* max. integration default 1 min */ maxInt = 1.0; ObitInfoListGetTest(inUV->info, "maxInt", &type, dim, &maxInt); if (maxInt<=(1.0e-2/60.0)) maxInt = 1.0; maxInt /= 1440.0; /* convert to days */ /* max amplitude loss default 1.01 */ maxFact = 1.01; ObitInfoListGetTest(inUV->info, "maxFact", &type, dim, &maxFact); if (maxFact<0.99) maxFact = 1.01; maxFact = MIN(MAX(maxFact,1.0), 10.0); /* Maximum UV distance squared to allow */ maxUVDist2 = (InvSinc(1.0/maxFact) / FOV); maxUVDist2 = maxUVDist2*maxUVDist2; /* Square */ /* Get Frequency Parameters */ NumChAvg = 0; ObitInfoListGetTest(inUV->info, "NumChAvg", &type, dim, &NumChAvg); NumChAvg = MAX(1, NumChAvg); doAvgAll = FALSE; ObitInfoListGetTest(inUV->info, "doAvgAll", &type, dim, &doAvgAll); ChanSel = NULL; if (!ObitInfoListGetP(inUV->info, "ChanSel", &type, dim, (gpointer)&ChanSel)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* ChanSel all zero? => default */ if ((ChanSel[0]<=0) && (ChanSel[1]<=0) && (ChanSel[2]<=0) && (ChanSel[3]<=0)) { ChanSel = defSel; /* Use default = channels 1 => n */ } /* Averaging in frequency? */ doAvgFreq = (NumChAvg>1) || doAvgAll; /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outUV); /* Is scratch? */ if (scratch) { if (outUV) outUV = ObitUVUnref(outUV); outUV = newObitUVScratch (inUV, err); } else { /* non scratch output must exist - clone from inUV */ outUV->myDesc = ObitUVDescCopy (inUV->myDesc, outUV->myDesc, err); ObitUVClone (inUV, outUV, err); } if (err->error) Obit_traceback_val (err, routine, inUV->name, outUV); inDesc = inUV->myDesc; /* Create work array for frequency averaging */ if (doAvgFreq) { work = g_malloc(2*inDesc->lrec*sizeof(ofloat)); /* Work arrays defining data */ corChan = g_malloc(inDesc->ncorr*sizeof(olong)); corIF = g_malloc(inDesc->ncorr*sizeof(olong)); corStok = g_malloc(inDesc->ncorr*sizeof(olong)); corMask = g_malloc(inDesc->ncorr*sizeof(gboolean)); /* Modify descriptor for affects of frequency averaging, get u,v,w scaling */ ObitUVGetFreq (inUV, err); /* Make sure frequencies updated */ scale = AvgFSetDesc (inUV->myDesc, outUV->myDesc, NumChAvg, ChanSel, doAvgAll, corChan, corIF, corStok, corMask, err); if (err->error) goto cleanup; } else { /* Only time averaging */ /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); } /* Add integration time if not present */ if (outUV->myDesc->ilocit<0) { strncpy (outUV->myDesc->ptype[outUV->myDesc->nrparm], "INTTIM", UVLEN_KEYWORD-1); outUV->myDesc->ilocit = outUV->myDesc->nrparm; outUV->myDesc->nrparm++; } /* Output creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Set number of output vis per write */ NPIO = 1; ObitInfoListGetTest(inUV->info, "nVisPIO", &type, dim, &NPIO); itemp = 1000; /* Internal IO buffer */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut(outUV->info, "nVisPIO", OBIT_long, dim, &itemp); /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Create sort buffer - Size depends on OS */ if (sizeof(olong*)==4) { /* 32 bit OS */ /* Make sort buffer big ~ 0.5 Gbyte */ nvis = 500000000 / (outUV->myDesc->lrec*sizeof(ofloat)); } else if (sizeof(olong*)==8) { /* 64 bit OS */ /* Make sort buffer big ~ 4 Gbyte */ nvis = 4000000000 / (outUV->myDesc->lrec*sizeof(ofloat)); } else nvis = 2000000000 / (outUV->myDesc->lrec*sizeof(ofloat)); nvis = MIN (nvis, inUV->myDesc->nvis); outBuffer = ObitUVSortBufferCreate ("Buffer", outUV, nvis, err); if (err->error) goto cleanup; /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Create work arrays for time averaging */ suba = 1; numAnt = inDesc->numAnt[suba-1]; /* actually highest antenna number */ /* Better be some */ Obit_retval_if_fail ((numAnt>1), err, outUV, "%s Number of antennas NOT in descriptor", routine); numBL = (((ollong)numAnt)*(numAnt+1))/2; /* Include auto correlations */ ncorr = inDesc->ncorr; nrparm = inDesc->nrparm; lltmp = 4*numBL*ncorr*sizeof(ofloat); accVis = g_malloc0(lltmp); /* Vis accumulator */ tVis = g_malloc0((inDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */ ttVis = g_malloc0((inDesc->lrec+5)*sizeof(ofloat)); /* Temp Vis */ lltmp = numBL*(nrparm+1)*sizeof(ofloat); accRP = g_malloc0(lltmp); /* Rand. parm */ lltmp = numBL*sizeof(ofloat); stBlTime= g_malloc0(lltmp); /* Baseline start time */ lsBlTime= g_malloc0(lltmp); /* Baseline last time */ stBlU = g_malloc0(lltmp); /* Baseline start U */ stBlV = g_malloc0(lltmp); /* Baseline start V */ /* Baseline lookup table */ blLookup = g_malloc0 (numAnt* sizeof(ollong)); blLookup[0] = 0; /* Include autocorr */ for (i=1; i<numAnt; i++) blLookup[i] = blLookup[i-1] + numAnt-i+1; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Initialize things */ startTime = -1.0e20; lastSourceID = -1; curSourceID = 0; outDesc->numVisBuff = 0; inBuffer = inUV->buffer; /* Local copy of buffer pointer */ /* Loop over intervals */ done = FALSE; gotOne = FALSE; /* we're in business, average data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if ((!gotOne) || (inUV->myDesc->numVisBuff<=0)) { /* need to read new record? */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); } /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done && (startTime>0.0)) {doAllBl=TRUE; goto process;} /* Final? */ /* Make sure valid data found */ if (inUV->myDesc->numVisBuff<=0) continue; /* loop over visibilities */ for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { gotOne = FALSE; /* Which data is this? */ iindx = ivis*inDesc->lrec; ObitUVDescGetAnts(inUV->myDesc, &inBuffer[iindx], &ant1, &ant2, &lastSubA); /* Check antenna number */ Obit_retval_if_fail ((ant2<=numAnt), err, outUV, "%s Antenna 2=%d > max %d", routine, ant2, numAnt); /* Baseline index this assumes a1<=a2 always */ blindx = blLookup[ant1-1] + ant2-ant1; blindx = MAX (0, MIN (blindx, numBL-1)); curTime = inBuffer[iindx+inDesc->iloct]; /* Time */ if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu]; /* Set time window etc. if needed */ if (startTime < -1000.0) { startTime = curTime; lastSourceID = curSourceID; } /* If end of data, new scan, source, etc., finish all accumulations */ doAllBl = (curSourceID != lastSourceID) || /* Same source */ (inDesc->firstVis>inDesc->nvis) || /* Not end of data */ (iretCode!=OBIT_IO_OK); /* Not end of data */ lastSourceID = curSourceID; /* Reset baseline start on first accumulation */ jndx = blindx*(1+nrparm); if (accRP[jndx]<1.0) { stBlTime[blindx] = inBuffer[iindx+inDesc->iloct]; stBlU[blindx] = inBuffer[iindx+inDesc->ilocu]; stBlV[blindx] = inBuffer[iindx+inDesc->ilocv]; } /* Compute square of UV distance since start of integration */ UVDist2 = (inBuffer[iindx+inDesc->ilocu]-stBlU[blindx])*(inBuffer[iindx+inDesc->ilocu]-stBlU[blindx]) + (inBuffer[iindx+inDesc->ilocv]-stBlV[blindx])*(inBuffer[iindx+inDesc->ilocv]-stBlV[blindx]); /* Still in current baseline integration? */ sameInteg = ((!doAllBl) && /* Not end of scan or data */ ((curTime-stBlTime[blindx])<maxInt) && /* Max. integration */ (UVDist2<maxUVDist2)); /* Max. smearing */ if (!sameInteg) { /* Write */ process: /* Now may have the next record in the IO Buffer */ if ((iretCode==OBIT_IO_OK) && (ivis<(inDesc->numVisBuff-1))) gotOne = TRUE; /* Finish this or all baselines? */ if (doAllBl) { blLo = 0; blHi = numBL-1; } else { /* only this one */ blLo = blindx; blHi = blindx; } /* Loop over this or all baselines */ for (blindx=blLo; blindx<=blHi; blindx++) { /* Anything this baseline? */ jndx = blindx*(1+nrparm); if (accRP[jndx]>0.0) { /* Average u, v, w, time random parameters */ indx = 0; for (i=0; i<nrparm; i++) { /* Average known parameters */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct)) accRP[jndx+i+1] /= accRP[jndx]; /* Copy to output buffer */ ttVis[indx++] = accRP[jndx+i+1]; } /* End random parameter loop */ /* Average vis data in time */ indx = outDesc->nrparm; for (j=0; j<ncorr; j++) { jndx = j*4 + blindx*4*ncorr; if (accVis[jndx]>0.0) { accVis[jndx+1] /= accVis[jndx]; accVis[jndx+2] /= accVis[jndx]; } /* Copy to tempory vis */ tVis[indx++] = accVis[jndx+1]; tVis[indx++] = accVis[jndx+2]; tVis[indx++] = accVis[jndx+3]; } /* end loop over correlators */ if (doAvgFreq) { /* Average data in frequency to output buffer */ AvgFAver (inDesc, outDesc, NumChAvg, ChanSel, doAvgAll, corChan, corIF, corStok, corMask, &tVis[outDesc->nrparm], &ttVis[outDesc->nrparm], work, err); if (err->error) goto cleanup; /* Scale u,v,w for new reference frequency */ ttVis[outDesc->ilocu] *= scale; ttVis[outDesc->ilocv] *= scale; ttVis[outDesc->ilocw] *= scale; } else { /* only time averaging */ /* Copy to output buffer */ indx = outDesc->nrparm; jndx = outDesc->nrparm; for (j=0; j<ncorr; j++) { ttVis[indx++] = tVis[jndx++]; ttVis[indx++] = tVis[jndx++]; ttVis[indx++] = tVis[jndx++]; } } /* Set integration time */ if (inDesc->ilocit>=0) ttVis[outDesc->ilocit] = MAX (lsBlTime[blindx]-stBlTime[blindx],ttVis[outDesc->ilocit]); else ttVis[outDesc->ilocit] = lsBlTime[blindx]-stBlTime[blindx]; /* Copy to Sort Buffer (Sorts and writes when full) */ count++; maxTime = curTime - 0.6*maxInt; ObitUVSortBufferAddVis(outBuffer, ttVis, maxTime, err); if (err->error) goto cleanup; /* Reinitialize baseline */ jndx = blindx*(1+nrparm); for (i=0; i<=nrparm; i++) accRP[jndx+i] = 0.0; jndx = blindx*4*ncorr; for (i=0; i<4*ncorr; i++) accVis[jndx+i] = 0.0; lsBlTime[blindx] = 0.0; stBlTime[blindx] = 0.0; } /* End any data this baseline */ } /* end loop over baseline */ } /* end process interval */ /* accumulate */ blindx = blLookup[ant1-1] + ant2-ant1; jndx = blindx*(1+nrparm); if (accRP[jndx]<1.0) { /* starting conditions */ stBlTime[blindx] = inBuffer[iindx+inDesc->iloct]; stBlU[blindx] = inBuffer[iindx+inDesc->ilocu]; stBlV[blindx] = inBuffer[iindx+inDesc->ilocv]; } lsBlTime[blindx] = inBuffer[iindx+inDesc->iloct]; /* Highest time */ /* Accumulate RP (1,*) = count (2...,*) = Random parameters, sum u, v, w, time, int. */ accRP[jndx]++; for (i=0; i<nrparm; i++) { /* Sum known parameters to average */ if ((i==inDesc->ilocu) || (i==inDesc->ilocv) || (i==inDesc->ilocw) || (i==inDesc->iloct) || (i==inDesc->ilocit)) { accRP[jndx+i+1] += inBuffer[iindx+i]; } else { /* merely keep the rest */ accRP[jndx+i+1] = inBuffer[iindx+i]; } } /* end loop over parameters */ /* Accumulate Vis (1,*) = count (2,*) = sum Real (3,*) = sum Imag (4,*) = Sum Wt */ indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) { jndx = i*4 + blindx*4*ncorr; accVis[jndx] += 1.0; accVis[jndx+1] += inBuffer[indx]; accVis[jndx+2] += inBuffer[indx+1]; accVis[jndx+3] += inBuffer[indx+2]; } indx += 3; } /* end loop over correlations */; } /* end loop processing buffer of input data */ } /* End loop over input file */ /* End of processing */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: if (accVis) g_free(accVis); accVis = NULL; if (accRP) g_free(accRP); accRP = NULL; if (tVis) g_free(tVis); tVis = NULL; if (ttVis) g_free(ttVis); ttVis = NULL; if (blLookup) g_free(blLookup); blLookup = NULL; if (lsBlTime) g_free(lsBlTime); lsBlTime = NULL; if (stBlTime) g_free(stBlTime); stBlTime = NULL; if (stBlU) g_free(stBlU); stBlU = NULL; if (stBlV) g_free(stBlV); stBlV = NULL; if (work) g_free(work); work = NULL; if (corChan) g_free(corChan); corChan = NULL; if (corIF) g_free(corIF); corIF = NULL; if (corStok) g_free(corStok); corStok = NULL; if (corMask) g_free(corMask); corMask = NULL; /* Flush Sort Buffer */ ObitUVSortBufferFlush (outBuffer, err); if (err->error) Obit_traceback_val (err, routine, outUV->name, outUV); outBuffer = ObitUVSortBufferUnref(outBuffer); /* close files */ iretCode = ObitUVClose (inUV, err); oretCode = ObitUVClose (outUV, err); if ((oretCode!=OBIT_IO_OK) || (iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, outUV->name, outUV); /* Restore no vis per read in output */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (outUV->info, "nVisPIO", OBIT_long, dim, &NPIO); /* Give report */ Obit_log_error(err, OBIT_InfoErr, "Wrote %d averaged visibilities",count); ObitErrLog(err); return outUV; } /* end ObitUVUtilBlAvgTF */ /** * Count number of good correlations per time interval * \param inData Input UV data, data selections, if any, applied * \param timeInt Size of time interval in days, max. 500 intervals * If data from a new source is found a new interval * is started. * \param err Error stack, returns if not empty. * \return ObitInfoList with entries: * \li "numTime" OBIT_int [1] Number of time intervals * \li "numCorr" OBIT_int [1] Number of Correlations per vis * \li "Count" OBIT_int [?] Count of good correlations per interval * \li "Bad" OBIT_int [?] Count of bad correlations per interval * \li "Source" OBIT_int [?] Source ID per interval * \li "LST" OBIT_float [?] Average LST (days) per interval * -1000.0 => no data. */ ObitInfoList* ObitUVUtilCount (ObitUV *inUV, ofloat timeInt, ObitErr *err) { ObitInfoList *outList = NULL; ObitTableAN *ANTable=NULL; ObitIOCode iretCode; gboolean doCalSelect; olong i, ver, ivis; ObitInfoType type; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitIOAccess access; ObitUVDesc *inDesc; ofloat *inBuffer; olong numTime, ncorr, indx, iindx, lastSourceID, curSourceID; gboolean gotOne, done, isVLA; odouble GSTiat0, DegDay, ArrayX, ArrayY; ofloat dataIat, ArrLong; ofloat startTime, endTime, curTime; ollong visCnt[500], goodCnt[500], badCnt[500], timeCnt[500], timeSou[500]; ofloat timeSum[500]; odouble dtemp[500]; gchar *routine = "ObitUVUtilCount"; /* error checks */ if (err->error) return outList; g_assert (ObitUVIsA(inUV)); /* Initialize sums */ numTime = 0; for (i=0; i<500; i++) { visCnt[i] = goodCnt[i] = badCnt[i] = timeCnt[i] = timeSou[i] = 0; timeSum[i] = 0.0; } timeInt /= 1440.0; /* timeInt to days */ /* Selection of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* Open input */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_val (err, routine, inUV->name, outList); inDesc = inUV->myDesc; /* Get descriptor */ /* Initialize things */ startTime = -1.0e20; endTime = 1.0e20; lastSourceID = -1; curSourceID = 0; inBuffer = inUV->buffer; ncorr = inDesc->ncorr; /* Loop over intervals */ done = FALSE; gotOne = FALSE; /* we're in business, average data */ while (iretCode==OBIT_IO_OK) { if ((!gotOne) || (inDesc->numVisBuff<=0)) { /* need to read new record? */ if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode > OBIT_IO_EOF) goto cleanup; } /* Are we there yet??? */ done = (inDesc->firstVis >= inDesc->nvis) || (iretCode==OBIT_IO_EOF); if (done && (startTime>0.0)) goto process; /* Final? */ /* Make sure valid data found */ if (inUV->myDesc->numVisBuff<=0) continue; iindx = 0; /* loop over visibilities in buffer */ for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { gotOne = FALSE; visCnt[numTime]++; /* Count vis */ curTime = inBuffer[iindx+inDesc->iloct]; /* Time */ if (inDesc->ilocsu>=0) curSourceID = inBuffer[iindx+inDesc->ilocsu]; if (startTime < -1000.0) { /* Set time window etc. if needed */ startTime = curTime; endTime = startTime + timeInt; lastSourceID = curSourceID; } /* Still in current interval */ if ((curTime<endTime) && (curSourceID == lastSourceID) && (inDesc->firstVis<=inDesc->nvis) && (iretCode==OBIT_IO_OK)) { /* sums */ timeSou[numTime] = curSourceID; timeCnt[numTime]++; timeSum[numTime] += curTime; indx = iindx+inDesc->nrparm; /* offset of start of vis data */ for (i=0; i<ncorr; i++) { if (inBuffer[indx+2] > 0.0) goodCnt[numTime]++; else badCnt[numTime]++; indx += 3; } /* end loop over correlations */; } else { numTime++; /* new interval */ startTime = -1.0e20; endTime = 1.0e20; /* Check over run */ Obit_retval_if_fail ((numTime<100), err, outList, "%s Too many time intervals %d", routine, numTime); } iindx += inDesc->lrec; } /* end loop processing buffer of input data */ } /* End loop over input file */ process: /* Create output */ outList = newObitInfoList(); /* Get time information */ ver = 1; ANTable = newObitTableANValue (inUV->name, (ObitData*)inUV, &ver, OBIT_IO_ReadOnly, 0, 0, 0, err); GSTiat0 = ANTable->GSTiat0; DegDay = ANTable->DegDay; ArrayX = ANTable->ArrayX; ArrayY = ANTable->ArrayY; if (!strncmp (ANTable->TimeSys, "IAT", 3)) { dataIat = 0.0; /* in IAT */ } else { /* Assume UTC */ dataIat = ANTable->dataUtc/86400.0; /* in days */ } isVLA = !strncmp(ANTable->ArrName, "VLA ", 8); ANTable = ObitTableANUnref(ANTable); /* Done with table */ if (err->error) Obit_traceback_val (err, routine, ANTable->name, outList); /* Need longitude */ if (isVLA) ArrLong = 1.878283678; else ArrLong = atan2(ArrayY, ArrayX); ArrLong *= RAD2DG; /* Average times and convert to LST */ numTime++; for (i=0; i<numTime; i++) { if (timeCnt[i]>0) { timeSum[i] /= timeCnt[i]; /* To LST in deg */ timeSum[i] = ((timeSum[i]-dataIat)*DegDay) + GSTiat0 + ArrLong; timeSum[i] /= 360.0; /* Back to days */ } else timeSum[i] = -1000.0; } /* end loop over time */ /* save values */ ObitInfoListAlwaysPut (outList, "numTime", OBIT_long, dim, &numTime); ObitInfoListAlwaysPut (outList, "numCorr", OBIT_long, dim, &ncorr); dim[0] = numTime; ObitInfoListAlwaysPut (outList, "Source", OBIT_long, dim, timeSou); ObitInfoListAlwaysPut (outList, "LST", OBIT_float, dim, timeSum); for (i=0; i<numTime; i++) dtemp[i] = (odouble)goodCnt[i]; ObitInfoListAlwaysPut (outList, "Count", OBIT_double, dim, dtemp); for (i=0; i<numTime; i++) dtemp[i] = (odouble)badCnt[i]; ObitInfoListAlwaysPut (outList, "Bad", OBIT_double, dim, dtemp); for (i=0; i<numTime; i++) dtemp[i] = (odouble)visCnt[i]; ObitInfoListAlwaysPut (outList, "Vis", OBIT_double, dim, dtemp); /* End of processing */ /* Cleanup */ cleanup: /* close file */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, inUV->name, outList); return outList; } /* end ObitUVUtilCount */ /** * Copy blocks of channels from one UV to a set of output UVs.. * All selected IFs and polarizations are also copied, there must be * an integran number of IFs per output. * \param inUV Input uv data to average, * Any request for calibration, editing and selection honored * \param nOut Number of outout images * \param outUV Array of previously defined but not yet instantiated * (never opened) UV data objects to receive 1/nOut * of the data channels in inUV. * \param err Error stack, returns if not empty. */ void ObitUVUtilSplitCh (ObitUV *inUV, olong nOut, ObitUV **outUV, ObitErr *err) { ObitIOCode iretCode=OBIT_IO_SpecErr, oretCode=OBIT_IO_SpecErr; gboolean doCalSelect; gchar *exclude[]={"AIPS CL", "AIPS SN", "AIPS FG", "AIPS CQ", "AIPS WX", "AIPS AT", "AIPS CT", "AIPS OB", "AIPS IM", "AIPS MC", "AIPS PC", "AIPS NX", "AIPS TY", "AIPS GC", "AIPS HI", "AIPS PL", "AIPS NI", "AIPS BP", "AIPS OF", "AIPS PS", "AIPS FQ", "AIPS SU", "AIPS AN", "AIPS PD", "AIPS SY", "AIPS PT", "AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; olong *BChan=NULL, *numChan=NULL, *BIF=NULL, *numIF=NULL; olong chinc=1, nchan, nif, nchOut, NPIO; olong i, j, indx, jndx, ivis, nIFperOut, oldNumberIF, oldStartIF; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]={1,1,1,1,1}; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; ofloat *scale = NULL; gchar *routine = "ObitUVUtilSplitCh"; /* error checks */ if (err->error) return; g_assert (ObitUVIsA(inUV)); for (i=0; i<nOut; i++) { if (!ObitUVIsA(outUV[i])) { Obit_log_error(err, OBIT_Error,"%s Output %d MUST be defined for non scratch files", routine, i); return; } } /* Selection/calibration/editing of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ ObitUVFullInstantiate (inUV, TRUE, err); iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUV->name); /* Get descriptor */ inDesc = inUV->myDesc; /* Allocate work arrays */ scale = g_malloc(nOut*sizeof(ofloat)); BChan = g_malloc(nOut*sizeof(olong)); numChan = g_malloc(nOut*sizeof(olong)); BIF = g_malloc(nOut*sizeof(olong)); numIF = g_malloc(nOut*sizeof(olong)); /* Divvy up channels - must be an integral number of IFs per output - or only 1 */ nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; nIFperOut = (glong) (0.9999 + (nif / (ofloat)nOut)); if ((fabs(((ofloat)nIFperOut)-(nif / (ofloat)nOut))>0.001) && (nif>1)) { Obit_log_error(err, OBIT_Error,"%s Not an equal number of IFs per output", routine); return; } if (nOut>(nchan* nIFperOut)) { Obit_log_error(err, OBIT_Error,"%s Fewer channels, %d than output files %d", routine, nchan, nOut); return; } nchOut = (glong) (0.999 + ((nchan*nif) / (ofloat)nOut)); nchOut = MAX (1, nchOut); nchOut = MIN (nchOut, nchan); for (i=0; i<nOut; i++) { BIF[i] = 1 + i*nIFperOut; numIF[i] = nIFperOut; BChan[i] = 1 + i*nchOut - (BIF[i]-1)*nchan; numChan[i] = MIN (nchOut, nchan-BChan[i]+1); } /* Set up output UV data */ for (i=0; i<nOut; i++) { /* copy Descriptor */ outUV[i]->myDesc = ObitUVDescCopy(inUV->myDesc, outUV[i]->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV[i]->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* Get descriptor */ outDesc = outUV[i]->myDesc; /* Set output frequency info */ outDesc->crval[outDesc->jlocf] = inDesc->crval[outDesc->jlocf] + (BChan[i]-inDesc->crpix[inDesc->jlocf]) * inDesc->cdelt[inDesc->jlocf] + (inDesc->freqIF[BIF[i]-1] - inDesc->freqIF[0]); outDesc->inaxes[outDesc->jlocf] = numChan[i]; /*outDesc->crpix[outDesc->jlocf] = 1.0;*/ outDesc->cdelt[outDesc->jlocf] = inDesc->cdelt[inDesc->jlocf] * chinc; /* UVW scaling parameter */ scale[i] = outDesc->crval[outDesc->jlocf]/inDesc->freq; /* IFs */ if (outDesc->jlocif>=0) { outDesc->crval[outDesc->jlocif] = inDesc->crval[outDesc->jlocif] + (BIF[i]-inDesc->crpix[inDesc->jlocif]) * inDesc->cdelt[inDesc->jlocif]; outDesc->inaxes[outDesc->jlocif] = numIF[i]; outDesc->crpix[outDesc->jlocif] = 1.0; outDesc->cdelt[outDesc->jlocif] = inDesc->cdelt[inDesc->jlocif] * chinc; } /* Alternate frequency/vel */ outDesc->altCrpix = inDesc->altCrpix - (BChan[i] + 1.0)/chinc; outDesc->altRef = inDesc->altRef; /* Copy number of records per IO to output */ ObitInfoListGet (inUV->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListAlwaysPut (outUV[i]->info, "nVisPIO", type, dim, (gpointer)&NPIO); if (err->error) goto cleanup; /* test open output */ oretCode = ObitUVOpen (outUV[i], OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV[i], OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV[i], exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV[i], NULL, sourceInclude, err); /* Fiddle IF selection */ oldNumberIF = inUV->mySel->numberIF; oldStartIF = inUV->mySel->startIF; inUV->mySel->numberIF = nIFperOut; inUV->mySel->startIF = BIF[i]; ObitTableFQSelect (inUV, outUV[i], NULL, 0.0, err); /* reset IF selection */ inUV->mySel->numberIF = oldNumberIF; inUV->mySel->startIF = oldStartIF; if (err->error) goto cleanup; /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV[i]->myIO, outUV[i]->info, err); if (err->error) goto cleanup; /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) goto cleanup; } /* end loop over output files */ /* we're in business, copy data */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ for (i=0; i<nOut; i++) { outUV[i]->myDesc->numVisBuff = inDesc->numVisBuff; } /* Copy data */ for (ivis=0; ivis<inDesc->numVisBuff; ivis++) { /* loop over visibilities */ /* Copy random parameters */ indx = ivis*inDesc->lrec; for (i=0; i<nOut; i++) { jndx = ivis*outUV[i]->myDesc->lrec; for (j=0; j<inDesc->nrparm; j++) outUV[i]->buffer[jndx+j] = inUV->buffer[indx+j]; /* Scale u,v,w for new reference frequency */ outUV[i]->buffer[jndx+inDesc->ilocu] *= scale[i]; outUV[i]->buffer[jndx+inDesc->ilocv] *= scale[i]; outUV[i]->buffer[jndx+inDesc->ilocw] *= scale[i]; } /* Copy visibility */ indx += inDesc->nrparm; for (i=0; i<nOut; i++) { jndx = ivis*outUV[i]->myDesc->lrec + outUV[i]->myDesc->nrparm; FreqSel (inUV->myDesc, outUV[i]->myDesc, BChan[i], BChan[i]+numChan[i]-1, chinc, BIF[i], BIF[i]+nIFperOut-1, &inUV->buffer[indx], &outUV[i]->buffer[jndx]); } } /* end loop over visibilities */ /* Write outputs */ for (i=0; i<nOut; i++) { oretCode = ObitUVWrite (outUV[i], outUV[i]->buffer, err); if (err->error) goto cleanup; } } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) goto cleanup; /* Cleanup */ cleanup: if (scale) g_free(scale); if (BChan) g_free(BChan); if (numChan) g_free(numChan); if (BIF) g_free(BIF); if (numIF) g_free(numIF); /* close files */ iretCode = ObitUVClose (inUV, err); for (i=0; i<nOut; i++) { oretCode = ObitUVClose (outUV[i], err); if ((iretCode!=OBIT_IO_OK) || (oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUV->name); } if (err->error) Obit_traceback_msg (err, routine, inUV->name); return; } /* end ObitUVUtilSplitCh */ /** * Add Gaussian noise to an UV * out = in*scale + noise (sigma), real, imag, each vis * Note: This uses the GSL random number generator, if this is not available * then only the scaling is done. * \param inUV Input UV * \param outUV Output UV, must already be defined but may be inUV * \param scale scaling factor for data * \param sigma Standard deviation of Gaussian noise . * \param err Error stack */ void ObitUVUtilNoise(ObitUV *inUV, ObitUV *outUV, ofloat scale, ofloat sigma, ObitErr *err) { ObitIOCode retCode; gboolean doCalSelect, done, same; ObitInfoType type; ObitIOAccess access, oaccess; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat val, fblank = ObitMagicF(); odouble dsigma = sigma; olong i, j, indx, NPIO, firstVis; ObitUVDesc *inDesc, *outDesc; /* Don't copy Cal and Soln or data or flag tables */ gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS SY","AIPS PT","AIPS OT", NULL}; #if HAVE_GSL==1 /* GSL stuff */ gsl_rng *ran=NULL; #endif /* HAVE_GSL */ gchar *routine = "ObitUVUtilNoise"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV)); g_assert (ObitUVIsA(outUV)); /* Are input and output the same file? */ same = ObitUVSame(inUV, outUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Local pointers */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Open Input Data */ retCode = ObitUVOpen (inUV, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inUV->name); /* use same data buffer on input and output. If multiple passes are made the input files will be closed which deallocates the buffer, use output buffer. so free input buffer */ if (!same) { /* use same data buffer on input 1 and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; } /* Copy number of records per IO to output */ ObitInfoListGet (inUV->info, "nVisPIO", &type, dim, (gpointer)&NPIO, err); ObitInfoListPut (outUV->info, "nVisPIO", type, dim, (gpointer)&NPIO, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Open Output Data */ if (same) oaccess = OBIT_IO_ReadWrite; else oaccess = OBIT_IO_WriteOnly; retCode = ObitUVOpen (outUV, oaccess, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) { outUV->buffer = NULL; /* remove pointer to inUV buffer */ outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* Copy tables before data */ if (!same) { retCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); if (err->error) {/* add traceback,return */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } /* Close and reopen input to init calibration which will have been disturbed by the table copy */ retCode = ObitUVClose (inUV, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } retCode = ObitUVOpen (inUV, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } } /* end if not same */ outUV->buffer = inUV->buffer; /* Init random number generator */ #if HAVE_GSL==1 /* GSL stuff */ ran = gsl_rng_alloc(gsl_rng_default); #endif /* HAVE_GSL */ /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */ retCode = ObitUVRead (inUV, NULL, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; /* How many? */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ indx = i*inDesc->lrec + inDesc->nrparm; for (j=0; j<inDesc->ncorr; j++) { /* loop over correlations */ if (inUV->buffer[indx]!=fblank) { val = inUV->buffer[indx]*scale; #if HAVE_GSL==1 /* GSL stuff */ val += (ofloat)gsl_ran_gaussian (ran, dsigma); #endif /* HAVE_GSL */ inUV->buffer[indx] = val; } if (inUV->buffer[indx+1]!=fblank) { val = inUV->buffer[indx+1]*scale; #if HAVE_GSL==1 /* GSL stuff */ val += (ofloat)gsl_ran_gaussian (ran, dsigma); #endif /* HAVE_GSL */ inUV->buffer[indx+1] = val; } indx += inDesc->inaxes[0]; } /* end loop over correlations */ } /* end loop over visibilities */ /* Write buffer - if same as input, fiddle first vis value */ firstVis = outDesc->firstVis; retCode = ObitUVWrite (outUV, NULL, err); if (same) { outDesc->firstVis = firstVis; ((ObitUVDesc*)(outUV->myIO->myDesc))->firstVis = firstVis; } if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } } /* end loop over data */ /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* Free random number generator */ #if HAVE_GSL==1 /* GSL stuff */ gsl_rng_free(ran); #endif /* HAVE_GSL */ /* Close input */ retCode = ObitUVClose (inUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Close output */ retCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); } /* end ObitUVUtilNoise */ /** * Adds flagging entry to associated flag table * Input values on inUV * \li "flagVer" OBIT_Int (1,1,1) Flagging table version, default = 1 * \li "subA" OBIT_Int (1,1,1) Subarray, default = 0 * \li "freqID" OBIT_Int (1,1,1) Frequency ID, default = 0 * \li "timeRange" OBIT_float (2,1,1) Start and stop times to flag (days) def, 0s=all * \li "Chans" OBIT_Int (2,1,1) First and highest channels to flag (1-rel), def, 0=>all * \li "IFs" OBIT_Int (2,1,1) First and highest IF to flag (1-rel), def, 0=>all * \li "Ants" OBIT_Int (2,1,1) first and second antenna numbers for a baseline, 0=$>$all * \li "Source" OBIT_string (?,1,1) Name of source, def, "Any" => all * \li "Stokes" OBIT_string (?,1,1) Stokes to flag, def " " = flag all * "FFFF" where F is '1' to flag corresponding Stokes, '0' not. * Stokes order 'R', 'L', 'RL' 'LR' or 'X', 'Y', 'XY', 'YX' * \li "Reason" OBIT_string (?,1,1) reason string for flagging (max. 24 char). * \param inUV Input UV data * \param err Error stack, returns if not empty. * \return IO return code, OBIT_IO_OK = OK */ ObitIOCode ObitUVUtilFlag (ObitUV *inUV, ObitErr *err) { ObitIOCode retCode = OBIT_IO_SpecErr; oint iarr[2]; olong flagVer, subA, freqID, chans[2], ifs[2], ants[2], SouID; ofloat timerange[2]; gchar source[49], stokes[10], reason[49]; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitInfoType type; ObitTableFG *FlagTable=NULL; ObitTableFGRow *FlagRow=NULL; ObitTableSU *SourceTable=NULL; gchar *tname, souCode[5]; olong ver, iRow, Qual, Number; gboolean xselect; oint numIF; gchar *routine = "ObitUVUtilFlag"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return retCode; g_assert (ObitUVIsA(inUV)); /* Get parameters */ flagVer = 1; ObitInfoListGetTest(inUV->info, "flagVer", &type, dim, &flagVer); subA = 0; ObitInfoListGetTest(inUV->info, "subA", &type, dim, &subA); freqID = 0; ObitInfoListGetTest(inUV->info, "freqID", &type, dim, &freqID); chans[0] = 1; chans[0] = 0; ObitInfoListGetTest(inUV->info, "Chans", &type, dim, chans); ifs[0] = 1; ifs[0] = 0; ObitInfoListGetTest(inUV->info, "IFs", &type, dim, ifs); ants[0] = 1; ants[0] = 0; ObitInfoListGetTest(inUV->info, "Ants", &type, dim, ants); timerange[0] = -1.0e20; timerange[1] = 1.0e20; ObitInfoListGetTest(inUV->info, "timeRange", &type, dim, timerange); /* default */ if ((timerange[0]==0.0) && (timerange[1]==0.0)) { timerange[0] = -1.0e20; timerange[1] = 1.0e20; } g_snprintf (source, 48, "Any"); ObitInfoListGetTest(inUV->info, "Source", &type, dim, source); source[dim[0]] = 0; /* terminate */ g_snprintf (stokes, 9, " "); ObitInfoListGetTest(inUV->info, "Stokes", &type, dim, stokes); stokes[dim[0]] = 0; /* terminate */ g_snprintf (reason, 48, " "); ObitInfoListGetTest(inUV->info, "Reason", &type, dim, reason); reason[dim[0]] = 0; /* terminate */ /* Open/close input UV to fully instantiate */ retCode = ObitUVOpen (inUV, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* Close */ retCode = ObitUVClose (inUV, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* Look up Source number if needed */ if (strncmp ("Any", source, 3)) { /* Instantiate/Create Source Table */ retCode = OBIT_IO_ReadErr; tname = g_strconcat ("SU table for: ",inUV->name, NULL); ver = 1; if (inUV->myDesc->jlocif>=0) numIF = inUV->myDesc->inaxes[inUV->myDesc->jlocif]; else numIF = 1; SourceTable = newObitTableSUValue(tname, (ObitData*)inUV, &ver, OBIT_IO_ReadWrite, numIF, err); dim[0] = strlen(source); dim[1] = 1; Number = 1; Qual = -1; sprintf (souCode, " "); ObitTableSULookup (SourceTable, dim, source, Qual, souCode, iarr, &xselect, &Number, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); SouID = iarr[0]; /* Source ID */ SourceTable = ObitTableSUUnref(SourceTable); g_free (tname); } else { /* flag all sources */ SouID = 0; } /* Instantiate/Create output Flag Table */ tname = g_strconcat ("FG table for: ", inUV->name, NULL); ver = flagVer; FlagTable = newObitTableFGValue(tname, (ObitData*)inUV, &ver, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); g_free (tname); /* Open table */ retCode = ObitTableFGOpen (FlagTable, OBIT_IO_ReadWrite, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* Create Table Row */ FlagRow = newObitTableFGRow (FlagTable); /* Attach row to output buffer */ ObitTableFGSetRow (FlagTable, FlagRow, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* If there are entries in the table, mark it unsorted */ if (FlagTable->myDesc->nrow>0) {FlagTable->myDesc->sort[0]=0; FlagTable->myDesc->sort[1]=0;} /* Fill in Flag row */ FlagRow->SourID = SouID; FlagRow->SubA = subA; FlagRow->freqID = freqID; FlagRow->TimeRange[0] = timerange[0]; FlagRow->TimeRange[1] = timerange[1]; FlagRow->ants[0] = ants[0]; FlagRow->ants[1] = ants[1]; FlagRow->chans[0] = chans[0]; FlagRow->chans[1] = chans[1]; FlagRow->ifs[0] = ifs[0]; FlagRow->ifs[1] = ifs[1]; FlagRow->pFlags[0] = 0; strncpy (FlagRow->reason, reason, 24); if (stokes[0]==' ') { FlagRow->pFlags[0] = 15; } else { if (stokes[0]!='0') FlagRow->pFlags[0] += 1; if (stokes[1]!='0') FlagRow->pFlags[0] += 2; if (stokes[2]!='0') FlagRow->pFlags[0] += 4; if (stokes[3]!='0') FlagRow->pFlags[0] += 8; } /* write row */ iRow = FlagTable->myDesc->nrow+1; retCode = ObitTableFGWriteRow (FlagTable, iRow, FlagRow, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* Close Flag table */ retCode = ObitTableFGClose (FlagTable, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, retCode); /* Cleanup */ FlagTable = ObitTableFGUnref(FlagTable); FlagRow = ObitTableFGRowUnref(FlagRow); return retCode; } /* end ObitUVUtilFlag */ /** * Make copy of ObitUV with the u,v,w terms calculated * \param inUV Input uv data to copy. * \param outUV If not scratch, then the previously defined output file * May be NULL for scratch only * If it exists and scratch, it will be Unrefed * \param err Error stack, returns if not empty. */ void ObitUVUtilCalcUVW (ObitUV *inUV, ObitUV *outUV, ObitErr *err) { ObitIOCode iretCode, oretCode; gboolean doCalSelect; gchar *exclude[]={"AIPS CL","AIPS SN","AIPS FG","AIPS CQ","AIPS WX", "AIPS AT","AIPS CT","AIPS OB","AIPS IM","AIPS MC", "AIPS PC","AIPS NX","AIPS TY","AIPS GC","AIPS HI", "AIPS PL","AIPS NI","AIPS OT", NULL}; gchar *sourceInclude[] = {"AIPS SU", NULL}; ObitUVWCalc *uvwCalc=NULL; olong i, indx, SId, subA, ant1, ant2; ofloat uvw[3]; ObitInfoType type; gint32 dim[MAXINFOELEMDIM]; ObitIOAccess access; ObitUVDesc *inDesc, *outDesc; gchar *today=NULL; gchar *routine = "ObitUVUtilCopyZero"; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitUVIsA(inUV)); if (outUV==NULL) { Obit_log_error(err, OBIT_Error,"%s Output MUST be defined", routine); return; } /* Selection of input? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadOnly; /* test open to fully instantiate input and see if it's OK */ iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine, inUV->name); /* copy Descriptor */ outUV->myDesc = ObitUVDescCopy(inUV->myDesc, outUV->myDesc, err); /* Creation date today */ today = ObitToday(); strncpy (outUV->myDesc->date, today, UVLEN_VALUE-1); if (today) g_free(today); /* use same data buffer on input and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = NULL; outUV->bufferSize = -1; /* test open output */ oretCode = ObitUVOpen (outUV, OBIT_IO_WriteOnly, err); /* If this didn't work try OBIT_IO_ReadWrite */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { ObitErrClear(err); oretCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err); } /* if it didn't work bail out */ if ((oretCode!=OBIT_IO_OK) || (err->error)) { /* unset output buffer (may be multiply deallocated) */ outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } /* iretCode = ObitUVClose (inUV, err); DEBUG */ /* Copy tables before data */ iretCode = ObitUVCopyTables (inUV, outUV, exclude, NULL, err); /* If multisource out then copy SU table, multiple sources selected or sources deselected suggest MS out */ if ((inUV->mySel->numberSourcesList>1) || (!inUV->mySel->selectSources)) iretCode = ObitUVCopyTables (inUV, outUV, NULL, sourceInclude, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } /* reset to beginning of uv data */ iretCode = ObitIOSet (inUV->myIO, inUV->info, err); oretCode = ObitIOSet (outUV->myIO, outUV->info, err); if (err->error) Obit_traceback_msg (err, routine,inUV->name); /* Close and reopen input to init calibration which will have been disturbed by the table copy */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV->name); iretCode = ObitUVOpen (inUV, access, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine,inUV->name); outUV->buffer = inUV->buffer; /* Get descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; SId = 0; /* In case single source */ uvwCalc = ObitUVWCalcCreate("UVWCalc", outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); /* we're in business, copy, recompute u,v,w */ while ((iretCode==OBIT_IO_OK) && (oretCode==OBIT_IO_OK)) { if (doCalSelect) iretCode = ObitUVReadSelect (inUV, inUV->buffer, err); else iretCode = ObitUVRead (inUV, inUV->buffer, err); if (iretCode!=OBIT_IO_OK) break; /* How many */ outDesc->numVisBuff = inDesc->numVisBuff; /* Modify data */ for (i=0; i<inDesc->numVisBuff; i++) { /* loop over visibilities */ indx = i*inDesc->lrec; if (inUV->myDesc->ilocsu>=0) SId = (olong)(inUV->buffer[indx+inUV->myDesc->ilocsu] + 0.5); ObitUVDescGetAnts(inUV->myDesc, &inUV->buffer[indx], &ant1, &ant2, &subA); ObitUVWCalcUVW(uvwCalc, inUV->buffer[indx+inDesc->iloct], SId, subA, ant1, ant2, uvw, err); inUV->buffer[indx+inDesc->ilocu] = uvw[0]; inUV->buffer[indx+inDesc->ilocv] = uvw[1]; inUV->buffer[indx+inDesc->ilocw] = uvw[2]; } /* end loop over visibilities */ /* Write */ oretCode = ObitUVWrite (outUV, inUV->buffer, err); if (err->error) { uvwCalc = ObitUVWCalcUnref(uvwCalc); Obit_traceback_msg (err, routine,inUV->name); } } /* end loop processing data */ /* check for errors */ if ((iretCode > OBIT_IO_EOF) || (oretCode > OBIT_IO_EOF) || (err->error)) /* add traceback,return */ Obit_traceback_msg (err, routine,inUV->name); /* unset input buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; uvwCalc = ObitUVWCalcUnref(uvwCalc); /* Cleanup */ /* close files */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUV->name); oretCode = ObitUVClose (outUV, err); if ((oretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outUV->name); return; } /* end ObitUVUtilCalcUVW */ /** * Compute low precision visibility uvw * \param b Baseline vector * \param dec Pointing declination (rad) * \param ha Pointing hour angle (rad) * \param uvw [out] baseline u,v,w in units of b */ void ObitUVUtilUVW(const ofloat b[3], odouble dec, ofloat ha, ofloat uvw[3]) { odouble cosdec, sindec; ofloat sinha, cosha, vw; cosdec = cos (dec); sindec = sin (dec); cosha = cos (ha); sinha = sin (ha); vw = b[0]*cosha - b[1]*sinha; uvw[0] = b[0]*sinha + b[1]*cosha; uvw[1] = -vw*sindec + b[2]*cosdec; uvw[2] = vw*cosdec + b[2]*sindec; } /* end ObitUVUtilUVW */ /** * Append the contents of one UV onto the end of another * \param inUV Input UV * \param outUV Output UV, must already be defined * \param err Error stack */ void ObitUVUtilAppend(ObitUV *inUV, ObitUV *outUV, ObitErr *err) { ObitIOCode retCode; gboolean doCalSelect, done; ObitInfoType type; ObitIOAccess access; gboolean incompatible; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ObitUVDesc *inDesc, *outDesc; olong inNPIO, outNPIO, NPIO; gchar *routine = "ObitUVUtilAppend"; /* error checks */ if (err->error) return; g_assert (ObitUVIsA(inUV)); g_assert (ObitUVIsA(outUV)); /* Get input descriptors */ inDesc = inUV->myDesc; outDesc = outUV->myDesc; /* Check compatability between inUV, outUV */ incompatible = (inDesc->ncorr!=outDesc->ncorr); incompatible = incompatible || (inDesc->jlocs!=outDesc->jlocs); incompatible = incompatible || (inDesc->jlocf!=outDesc->jlocf); incompatible = incompatible || (inDesc->jlocif!=outDesc->jlocif); incompatible = incompatible || (inDesc->ilocb!=outDesc->ilocb); if (incompatible) { Obit_log_error(err, OBIT_Error,"%s inUV and outUV have incompatible structures", routine); return ; } /* Calibration wanted? */ doCalSelect = FALSE; ObitInfoListGetTest(inUV->info, "doCalSelect", &type, dim, &doCalSelect); if (doCalSelect) access = OBIT_IO_ReadCal; else access = OBIT_IO_ReadWrite; /* Set number of vis per I/O */ inNPIO = 1000; ObitInfoListGetTest (inUV->info, "nVisPIO", &type, dim, &inNPIO); outNPIO = 1000; ObitInfoListGetTest (outUV->info, "nVisPIO", &type, dim, &outNPIO); NPIO = 1000; dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (inUV->info, "nVisPIO", OBIT_long, dim, &NPIO); ObitInfoListAlwaysPut (outUV->info, "nVisPIO", OBIT_long, dim, &NPIO); /* Open Input Data */ retCode = ObitUVOpen (inUV, access, err); if ((retCode != OBIT_IO_OK) || (err->error>0)) Obit_traceback_msg (err, routine, inUV->name); /* use same data buffer on input and output so don't assign buffer for output */ if (outUV->buffer) ObitIOFreeBuffer(outUV->buffer); /* free existing */ outUV->buffer = inUV->buffer; outUV->bufferSize = inUV->bufferSize; /* Open Output Data */ retCode = ObitUVOpen (outUV, OBIT_IO_ReadWrite, err) ; if ((retCode != OBIT_IO_OK) || (err->error>0)) { outUV->buffer = NULL; /* remove pointer to inUV buffer */ outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } outDesc->firstVis = outDesc->nvis+1; /* Write to end */ /* Loop over data */ done = (retCode != OBIT_IO_OK); while (!done) { /* read buffer */ retCode = ObitUVRead (inUV, NULL, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, inUV->name); } done = (retCode == OBIT_IO_EOF); /* done? */ if (done) break; /* How many? */ outDesc->numVisBuff = inDesc->numVisBuff; /* Write buffer */ retCode = ObitUVWrite (outUV, NULL, err); if (err->error) { outUV->buffer = NULL; outUV->bufferSize = 0; Obit_traceback_msg (err, routine, outUV->name); } } /* end loop over data */ /* unset output buffer (may be multiply deallocated ;'{ ) */ outUV->buffer = NULL; outUV->bufferSize = 0; /* Close input */ retCode = ObitUVClose (inUV, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Close output */ retCode = ObitUVClose (outUV, err); if (err->error) Obit_traceback_msg (err, routine, outUV->name); /* Reset number of vis per I/O */ ObitInfoListAlwaysPut (inUV->info, "nVisPIO", OBIT_long, dim, &inNPIO); ObitInfoListAlwaysPut (outUV->info, "nVisPIO", OBIT_long, dim, &outNPIO); } /* end ObitUVUtilAppend */ #ifndef VELIGHT #define VELIGHT 2.997924562e8 #endif /* VELIGHT */ /** * How many channels can I average * \param inUV Input UV * \param maxFact Maximum allowed bandwith smearing amplitude loss * \param FOV Radius of desired FOV (deg) * \param err Error stack */ olong ObitUVUtilNchAvg(ObitUV *inUV, ofloat maxFact, ofloat FOV, ObitErr *err) { olong out=1; ObitIOCode iretCode; ObitUVDesc *inDesc; ObitTableAN *ANTable=NULL; ObitAntennaList **AntList=NULL; olong i, j, numSubA, iANver, numIF, numOrb, numPCal; ofloat chBW, maxBL, BL, fact, beta, tau; gchar *routine = "ObitUVUtilNchAv"; /* error checks */ if (err->error) return out; g_assert (ObitUVIsA(inUV)); /* test open to fully instantiate input and see if it's OK */ ObitUVFullInstantiate (inUV, TRUE, err); iretCode = ObitUVOpen (inUV, OBIT_IO_ReadCal, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, inUV->name, out); /* Get descriptor */ inDesc = inUV->myDesc; /* Channel bandwidth */ chBW = inDesc->cdelt[inDesc->jlocf]; /* Antenna List How many AN tables (no. subarrays)? */ numSubA = ObitTableListGetHigh (inUV->tableList, "AIPS AN"); AntList = g_malloc0(numSubA*sizeof(ObitAntennaList*)); maxBL = 0.0; /* Loop over AN tables (subarrays) */ for (iANver=1; iANver<=numSubA; iANver++) { numOrb = 0; numPCal = 0; numIF = 0; ANTable = newObitTableANValue ("AN table", (ObitData*)inUV, &iANver, OBIT_IO_ReadOnly, numIF, numOrb, numPCal, err); if (ANTable==NULL) Obit_log_error(err, OBIT_Error, "ERROR with AN table"); AntList[iANver-1] = ObitTableANGetList (ANTable, err); if (err->error) Obit_traceback_val (err, routine, inUV->name, out); /* Cleanup */ ANTable = ObitTableANUnref(ANTable); /* Find maximum baseline */ for (i=0; i<AntList[iANver-1]->number-1; i++) { /* Antenna in array? */ if ((fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[0]<1.0)) && (fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[1]<1.0)) && (fabs(AntList[iANver-1]->ANlist[i]->AntXYZ[2]<1.0))) continue; for (j=i+1; j<AntList[iANver-1]->number; j++) { /* Antenna in array? */ if ((fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[0]<1.0)) && (fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[1]<1.0)) && (fabs(AntList[iANver-1]->ANlist[j]->AntXYZ[2]<1.0))) continue; BL = (AntList[iANver-1]->ANlist[i]->AntXYZ[0]-AntList[iANver-1]->ANlist[j]->AntXYZ[0]) * (AntList[iANver-1]->ANlist[i]->AntXYZ[0]-AntList[iANver-1]->ANlist[j]->AntXYZ[0]) + (AntList[iANver-1]->ANlist[i]->AntXYZ[1]-AntList[iANver-1]->ANlist[j]->AntXYZ[1]) * (AntList[iANver-1]->ANlist[i]->AntXYZ[1]-AntList[iANver-1]->ANlist[j]->AntXYZ[1]) + (AntList[iANver-1]->ANlist[i]->AntXYZ[2]-AntList[iANver-1]->ANlist[j]->AntXYZ[2]) * (AntList[iANver-1]->ANlist[i]->AntXYZ[2]-AntList[iANver-1]->ANlist[j]->AntXYZ[2]); maxBL = MAX (maxBL, BL); } } } /* End loop over subarrays */ maxBL = sqrt(maxBL); /* Cleanup */ if (AntList) { for (i=0; i<numSubA; i++) { AntList[i] = ObitAntennaListUnref(AntList[i]); } g_free(AntList); } /* Close up */ iretCode = ObitUVClose (inUV, err); if ((iretCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_val (err, routine, inUV->name, out); /* Calculate number of channels to average */ tau = sin(FOV*DG2RAD) * maxBL / VELIGHT; /* Maximum delay across FOV */ for (i=2; i<=inDesc->inaxes[inDesc->jlocf]; i++) { beta = i * chBW; fact = (G_PI*beta*tau) / fabs(sin(G_PI*beta*tau)); if (fact>maxFact) break; out = i; } return out; } /* end ObitUVUtilNchAvg */ /*----------------------Private functions---------------------------*/ /** * Count channels after selection and averaging and modify descriptor. * Also determines arrays giving the channel, IF and stokes of each correlator * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified * \param NumChAvg Number of channels to average * \param ChanSel Groups of channels/IF in input to be averaged together * (start, end, increment, IF) where start and end at the * beginning and ending channel numbers (1-rel) of the group * to be averaged together, increment is the increment between * selected channels and IF is the IF number (1-rel) * ChanSel is ignored if NumChAvg is given and > 0. * default increment is 1, IF=0 means all IF. * The list of groups is terminated by a start <=0 * \param doAvgAll If true all channels and IFs to be averaged together * \param corChan [out] 0-rel output channel numbers * Should be externally allocated to at least the number of correlators * \param corIF [out] 0-rel output IF numbers * Should be externally allocated to at least the number of correlators * \param corStok [out] 0-rel output Stokes parameter code. * Should be externally allocated to at least the number of correlators * \param corMask [out] Array of masks per correlator for selected channels/IFs * Should be externally allocated to at least the number of correlators * \param err Error stack, returns if not empty. * \return scaling factor for U,V,W to new reference frequency */ static ofloat AvgFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChAvg, olong *ChanSel, gboolean doAvgAll, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ObitErr *err) { ofloat scale = 1.0; olong i, ii, count, count2, NumIFAvg, numChan = 1, numIF = 1; olong ichan, iif, istok, nchan, nif, nstok; olong incs, incf, incif, ioff, lfoff, soff; olong *selTemp; olong *tcorChan=NULL, *tcorIF=NULL; gboolean more, match; odouble oldFreq, sum, sum2; /* error checks */ if (err->error) return scale; g_assert(ObitUVDescIsA(inDesc)); g_assert(ObitUVDescIsA(outDesc)); /* Set up for parsing data */ nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; numChan = 1 + (nchan-1) / MAX (1, NumChAvg); /* Number of output channels */ /* IF averaging */ NumIFAvg = 1; if (doAvgAll) NumIFAvg = nif; /* Enforce ChanSel Limits */ selTemp = ChanSel; more = selTemp[1]>0; while (more) { if (selTemp[0]<1) selTemp[0] = 1; if (selTemp[1]>nchan) selTemp[1] = nchan; if (selTemp[2]<1) selTemp[2] = 1; if (selTemp[3]<0) selTemp[3] = 0; if (selTemp[3]>nif) selTemp[3] = nif; selTemp += 4; more = selTemp[1]>0; } /* end loop enforcing limits */ /* get increments (one word per correlator) */ incs = inDesc->incs / inDesc->inaxes[0]; incf = inDesc->incf / inDesc->inaxes[0]; incif = inDesc->incif / inDesc->inaxes[0]; /* temp arrays */ tcorChan = g_malloc0(inDesc->ncorr*sizeof(olong)); tcorIF = g_malloc0(inDesc->ncorr*sizeof(olong)); /* loop over IF */ for (iif=0; iif<nif; iif++) { lfoff = iif * incif; ioff = lfoff; /* Loop over frequency channel */ for (ichan=0; ichan<nchan; ichan++) { /* loop 60 */ soff = ioff; /* Loop over polarization */ for (istok=0; istok<nstok; istok++) { corChan[soff] = (ichan/NumChAvg); corIF[soff] = (iif/NumIFAvg); corStok[soff] = istok; corMask[soff] = FALSE; tcorChan[soff] = (ichan); tcorIF[soff] = (iif); /* Is this correlator/IF in ChanSel? */ selTemp = ChanSel; more = selTemp[1]>0; while (more) { /* In IF range? */ if ((selTemp[3]<=0) || (selTemp[3]==(iif+1))) { if ((selTemp[0]<=(ichan+1)) && (selTemp[1]>=(ichan+1))) { /* Desired channel? */ match = (selTemp[2]<=1) || (((ichan-selTemp[0])%(selTemp[2]))==0); corMask[soff] = match; } /* end channel range */ } /* end IF range */ selTemp += 4; more = selTemp[1]>0; } soff += incs; } /* end loop over stokes */ ioff += incf; } /* end loop over channel */ } /* end loop over IF */ /* Averaging all channels/IF? */ if (doAvgAll) { outDesc->inaxes[outDesc->jlocf] = nchan; /* Average all frequencies */ sum = 0.0; count = 0; sum2 = 0.0; count2 = 0; for (i=0; i<inDesc->ncorr; i++) { ii = tcorChan[i] + tcorIF[i]*nchan; sum2 += inDesc->freqArr[ii]; count2++; if (corMask[i]) { sum += inDesc->freqArr[ii]; count++; } } /* end loop over correlators */ if (count>0) outDesc->crval[outDesc->jlocf] = sum / (ofloat)count; else if (count2>0) outDesc->crval[outDesc->jlocf] = sum2 / (ofloat)count2; outDesc->inaxes[outDesc->jlocf] = numChan; outDesc->crpix[outDesc->jlocf] = 1.0; outDesc->cdelt[outDesc->jlocf] = inDesc->cdelt[inDesc->jlocf] * inDesc->inaxes[inDesc->jlocf]; if (outDesc->jlocif>=0) { outDesc->inaxes[outDesc->jlocif] = numIF; outDesc->crval[outDesc->jlocif] = 1.0; outDesc->crpix[outDesc->jlocif] = 1.0; outDesc->cdelt[outDesc->jlocif] = 1.0; } /* Alternate frequency/vel */ outDesc->altCrpix = 1.0; outDesc->altRef = inDesc->altRef; return scale; } /* End doAvgAll */ /* Averaging channels - IFs unaffected */ numChan = 1 + ((inDesc->inaxes[inDesc->jlocf]-1) / NumChAvg); /* Get frequency of first average */ sum = 0.0; count = 0; sum2 = 0.0; count2 = 0; ii = -1; for (i=0; i<inDesc->ncorr; i++) { if ((corChan[i]>0) || (corStok[i]>0) || (corIF[i]>0)) continue; /* want? */ ii++; sum2 += inDesc->freqArr[ii]; count2++; if (corMask[i]) { sum += inDesc->freqArr[ii]; count++; } } /* end loop over correlators */ oldFreq = outDesc->crval[outDesc->jlocf]; /* Save old reference freq */ outDesc->inaxes[outDesc->jlocf] = numChan; if (count>0) outDesc->crval[outDesc->jlocf] = sum / (ofloat)count; else if (count2>0) outDesc->crval[outDesc->jlocf] = sum2 / (ofloat)count2; outDesc->crpix[outDesc->jlocf] = 1.0; outDesc->cdelt[outDesc->jlocf] = inDesc->cdelt[inDesc->jlocf] * NumChAvg; /* Frequency scaling */ scale = outDesc->crval[outDesc->jlocf]/oldFreq; /* Alternate frequency/vel */ outDesc->altCrpix = 1.0 + (outDesc->altCrpix-1.0)/NumChAvg; outDesc->altRef = inDesc->altRef; /* Cleanup */ if (tcorChan) g_free(tcorChan); if (tcorIF) g_free(tcorIF); return scale; } /* end AvgFSetDesc */ /** * Modify descriptor for duplicatiing channels * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified, assumed mostly copied. * \param nBloat Number of time to duplicate channels * \param err Error stack, returns if not empty. * \return scaling factor for U,V,W to new reference frequency */ static ofloat BloatFSetDesc (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat, ObitErr *err) { olong nchan; ofloat scale = 1.0; /* error checks */ if (err->error) return scale; g_assert(ObitUVDescIsA(inDesc)); g_assert(ObitUVDescIsA(outDesc)); /* Modify */ nchan = (inDesc->inaxes[inDesc->jlocf]+nBloat-1) * nBloat; outDesc->inaxes[outDesc->jlocf] = nchan; outDesc->cdelt[outDesc->jlocf] = inDesc->cdelt[inDesc->jlocf] / nBloat; outDesc->crval[outDesc->jlocf] = inDesc->crval[inDesc->jlocf] - 0.5 * outDesc->cdelt[outDesc->jlocf]; scale = outDesc->crval[outDesc->jlocf] / inDesc->crval[inDesc->jlocf]; /* Alternate frequency/vel */ outDesc->altCrpix = 1.0 + (outDesc->altCrpix-1.0)*nBloat; outDesc->altRef = inDesc->altRef; return scale; } /* end BloatFSetDesc */ /** * Average visibility in frequency * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified * \param NumChAvg Number of channels to average * \param ChanSel Groups of channels/IF in input to be averaged together * (start, end, increment, IF) where start and end at the * beginning and ending channel numbers (1-rel) of the group * to be averaged together, increment is the increment between * selected channels and IF is the IF number (1-rel) * ChanSel is ignored if NumChAvg is given and > 0. * default increment is 1, IF=0 means all IF. * The list of groups is terminated by a start <=0 * corMask actually used to select. * \param doAvgAll If true all channels and IFs to be averaged together * \param corChan 0-rel output channel numbers * \param corIF 0-rel output IF numbers * \param corStok 0-rel output Stokes parameter code. * \param corMask Array of masks per correlator for selected channels/IFs * TRUE => select * \param inBuffer Input buffer (data matrix) * \param outBuffer Output buffer (data matrix) * \param work Work array twice the size of the output visibility * \param err Error stack, returns if not empty. */ static void AvgFAver (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChAvg, olong *ChanSel, gboolean doAvgAll, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err) { olong i, n, indx, jndx, jf, jif, js, nochan, noif; olong nchan, nif, nstok, incs, incf, incif; /* error checks */ if (err->error) return; nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; incs = outDesc->incs; incf = outDesc->incf; incif = outDesc->incif; nochan = outDesc->inaxes[outDesc->jlocf]; if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif]; else noif = 1; /* Zero work accumulator */ n = 4 * inDesc->ncorr; for (i=0; i<n; i++) work[i] = 0.0; /* Accumulate order, channel, IF, poln */ indx = 0; for (i=0; i<inDesc->ncorr; i++) { jndx = 4*(corChan[i] + corIF[i]*nchan + corStok[i]*nchan*nif); if ((inBuffer[indx+2]>0.0) && corMask[i]) { work[jndx] += inBuffer[indx]; work[jndx+1] += inBuffer[indx+1]; work[jndx+2] += inBuffer[indx+2]; work[jndx+3] += 1.0; } indx += inDesc->inaxes[0]; } /* end accumulation loop */ /* Normalize to output */ /* Loop over Stokes */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<noif; jif++) { /* IF loop */ for (jf=0; jf<nochan; jf++) { /* Frequency loop */ jndx = 4*(jf + jif*nchan + js*nchan*nif); indx = js*incs + jif*incif + jf*incf; if (work[jndx+3]>0.0) { outBuffer[indx] = work[jndx] / work[jndx+3]; outBuffer[indx+1] = work[jndx+1] / work[jndx+3]; outBuffer[indx+2] = work[jndx+2]; } else { outBuffer[indx] = 0.0; outBuffer[indx+1] = 0.0; outBuffer[indx+2] = 0.0; } } /* end Frequency loop */ } /* end IF loop */ } /* end Stokes loop */ } /* end AvgFAver */ /** * Frequency boxcar smooth a visibility * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified * \param NumChSMO Number of channels to smooth, should be odd * \param corChan 0-rel output channel numbers * \param corIF 0-rel output IF numbers * \param corStok 0-rel output Stokes parameter code. * \param corMask Array of masks per correlator for selected channels/IFs * TRUE => select * \param inBuffer Input buffer (data matrix) * \param outBuffer Output buffer (data matrix) * \param work Work array twice the size of the output visibility * \param err Error stack, returns if not empty. */ static void SmooF (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong NumChSmo, olong *corChan, olong *corIF, olong *corStok, gboolean *corMask, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err) { olong i, j, half, n, indx, jndx, kndx, jf, jif, js, nochan, noif, off; olong nchan, nif, nstok, iincs, iincf, iincif, incs, incf, incif; /* error checks */ if (err->error) return; half = NumChSmo/2; iincs = inDesc->incs; iincf = inDesc->incf; iincif = inDesc->incif; nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; incs = outDesc->incs; incf = outDesc->incf; incif = outDesc->incif; nochan = outDesc->inaxes[outDesc->jlocf]; if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif]; else noif = 1; /* Zero work accumulator */ n = 4 * inDesc->ncorr; for (i=0; i<n; i++) work[i] = 0.0; /* Accumulate order, channel, IF, poln */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<nif; jif++) { /* IF loop */ for (jf=half; jf<nchan-half+1; jf++) { /* Frequency loop */ indx = js*iincs + jif*iincif + jf*iincf; jndx = 4*(jf + jif*nchan + js*nchan*nif); off = -half*iincf; /* Sums for smoothing */ for (j=0; j<NumChSmo; j++) { if (inBuffer[indx+off+2]>0.0) { /* Valid? */ work[jndx] += inBuffer[indx+off]; work[jndx+1] += inBuffer[indx+off+1]; work[jndx+2] += inBuffer[indx+off+2]; work[jndx+3] += 1.0; off += iincf; } /* end data valid */ } /* end smoothing loop */ } /* end freq loop */ /* Copy end channels */ jndx = 4*(half + jif*nchan + js*nchan*nif); for (jf=0; jf<half; jf++) { kndx = 4*(jf + jif*nchan + js*nchan*nif); work[kndx] = work[jndx]; work[kndx+1] = work[jndx+1]; work[kndx+2] = work[jndx+2]; work[kndx+3] = work[jndx+3]; } jndx = 4*(nchan-half-1 + jif*nchan + js*nchan*nif); for (jf=half; jf>0; jf--) { kndx = 4*(nchan-jf + jif*nchan + js*nchan*nif); work[kndx] = work[jndx]; work[kndx+1] = work[jndx+1]; work[kndx+2] = work[jndx+2]; work[kndx+3] = work[jndx+3]; } } /* end IF loop */ } /* end stokes loop */ /* Normalize to output */ /* Loop over Stokes */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<noif; jif++) { /* IF loop */ for (jf=0; jf<nochan; jf++) { /* Frequency loop */ jndx = 4*(jf + jif*nchan + js*nchan*nif); indx = js*incs + jif*incif + jf*incf; /* Check for zero data */ if ((work[jndx+3]>0.0) && !(( work[jndx]==0.0) && (work[jndx+1]==0.0))) { outBuffer[indx] = work[jndx] / work[jndx+3]; outBuffer[indx+1] = work[jndx+1] / work[jndx+3]; outBuffer[indx+2] = work[jndx+2]; } else { outBuffer[indx] = 0.0; outBuffer[indx+1] = 0.0; outBuffer[indx+2] = 0.0; } } /* end Frequency loop */ } /* end IF loop */ } /* end Stokes loop */ } /* end SmooF */ /** * Hanning smooth a visibility * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified * \param doDescm If TRUE drop every other channel * \param inBuffer Input buffer (data matrix) * \param outBuffer Output buffer (data matrix) * \param work Work array twice the size of the output visibility * \param err Error stack, returns if not empty. */ static void Hann (ObitUVDesc *inDesc, ObitUVDesc *outDesc, gboolean doDescm, ofloat *inBuffer, ofloat *outBuffer, ofloat *work, ObitErr *err) { olong i, n, indx, jndx, jf, jif, js, nochan, noif, off, wincf; olong nchan, nif, nstok, iincs, iincf, iincif, incs, incf, incif; /* error checks */ if (err->error) return; iincs = inDesc->incs; iincf = inDesc->incf; iincif = inDesc->incif; nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocif>=0) nif = inDesc->inaxes[inDesc->jlocif]; else nif = 1; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; incs = outDesc->incs; incf = outDesc->incf; incif = outDesc->incif; nochan = outDesc->inaxes[outDesc->jlocf]; if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif]; else noif = 1; /* Zero work accumulator */ n = 4 * inDesc->ncorr; for (i=0; i<n; i++) work[i] = 0.0; /* Accumulate order, channel, IF, poln */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<nif; jif++) { /* IF loop */ for (jf=0; jf<nchan; jf++) { /* Frequency loop */ indx = js*iincs + jif*iincif + jf*iincf; jndx = 4*(jf + jif*nchan + js*nchan*nif); off = -iincf; if ((jf>0) && (inBuffer[indx+off+2]>0.0)) { /* Prior channel 0.25 wt */ work[jndx] += 0.25*inBuffer[indx+off]; work[jndx+1] += 0.25*inBuffer[indx+off+1]; work[jndx+2] += 0.25*inBuffer[indx+off+2]; work[jndx+3] += 0.25; } /* Center channel 0.5 wt */ if (inBuffer[indx+2]>0.0) { work[jndx] += 0.5*inBuffer[indx]; work[jndx+1] += 0.5*inBuffer[indx+1]; work[jndx+2] += 0.5*inBuffer[indx+2]; work[jndx+3] += 0.5; } /* Follow channel 0.25 wt */ off = iincf; if ((jf<(nchan-1)) && (inBuffer[indx+off+2]>0.0)) { work[jndx] += 0.25*inBuffer[indx+off]; work[jndx+1] += 0.25*inBuffer[indx+off+1]; work[jndx+2] += 0.25*inBuffer[indx+off+2]; work[jndx+3] += 0.25; } } /* end freq loop */ } /* end IF loop */ } /* end stokes loop */ /* Descimating output? */ if (doDescm) wincf = 2; else wincf = 1; /* Normalize to output */ /* Loop over Stokes */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<noif; jif++) { /* IF loop */ for (jf=0; jf<nochan; jf++) { /* Frequency loop */ jndx = 4*(jf*wincf + jif*nchan + js*nchan*nif); indx = js*incs + jif*incif + jf*incf; /* Check for zero data */ if ((work[jndx+3]>0.0) && !(( work[jndx]==0.0) && (work[jndx+1]==0.0))) { outBuffer[indx] = work[jndx] / work[jndx+3]; outBuffer[indx+1] = work[jndx+1] / work[jndx+3]; outBuffer[indx+2] = work[jndx+2]; } else { outBuffer[indx] = 0.0; outBuffer[indx+1] = 0.0; outBuffer[indx+2] = 0.0; } } /* end Frequency loop */ } /* end IF loop */ } /* end Stokes loop */ } /* end Hann */ /** * Duplicate channels * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor to be modified * \param nBloat Number of duplicates of each input channel * \param unHann If true, undo prior Hanning * \param inBuffer Input buffer (data matrix) * \param outBuffer Output buffer (data matrix) * \param err Error stack, returns if not empty. */ static void Bloat (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong nBloat, gboolean unHann, ofloat *inBuffer, ofloat *outBuffer, ObitErr *err) { olong j, indx, jndx, jf, jif, js, nochan, noif; olong nchan, nstok, iincs, iincf, iincif, incs, incf, incif; ofloat WtFact; /* error checks */ if (err->error) return; WtFact = 1.0 / nBloat; /* Weight factor */ if (unHann) WtFact = 1.0; /* Undoing Hanning? */ iincs = inDesc->incs; iincf = inDesc->incf; iincif = inDesc->incif; nchan = inDesc->inaxes[inDesc->jlocf]; if (inDesc->jlocs>=0) nstok = inDesc->inaxes[inDesc->jlocs]; else nstok = 1; incs = outDesc->incs; incf = outDesc->incf; incif = outDesc->incif; nochan = outDesc->inaxes[outDesc->jlocf]; if (outDesc->jlocif>=0) noif = outDesc->inaxes[outDesc->jlocif]; else noif = 1; /* Duplicate to output */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=0; jif<noif; jif++) { /* IF loop */ for (jf=0; jf<nchan; jf++) { /* Frequency loop */ indx = js*iincs + jif*iincif + jf*iincf; for (j=0; j<nBloat; j++) { jndx = (jf*nBloat+j)*incf + jif*incif + js*incs; /* Check for zero data, final channels */ if ((inBuffer[indx+2]>0.0) && ((jf*nBloat+j)<nochan)) { outBuffer[jndx] = inBuffer[indx]; outBuffer[jndx+1] = inBuffer[indx+1]; outBuffer[jndx+2] = inBuffer[indx+2] * WtFact; } else { outBuffer[jndx] = 0.0; outBuffer[jndx+1] = 0.0; outBuffer[jndx+2] = 0.0; } } /* end duplication */ } /* end Frequency loop */ } /* end IF loop */ } /* end Stokes loop */ } /* end Bloat */ /** * Select visibility in frequency * \param inDesc Input UV descriptor * \param outDesc Output UV descriptor * \param BChan First (1-rel) input channel selected * \param EChan Highest (1-rel) channel selected * \param chinc Increment of channels selected * \param BIF First IF (1-rel) selected * \param EIF Highest IF selected * \param inBuffer Input buffer (data matrix) * \param outBuffer Output buffer (data matrix) */ static void FreqSel (ObitUVDesc *inDesc, ObitUVDesc *outDesc, olong BChan, olong EChan, olong chinc, olong BIF, olong EIF, ofloat *inBuffer, ofloat *outBuffer) { olong indx, jndx, jf, jif, js, ojf, ojif; olong nstok, iincs, iincf, iincif, oincs, oincf, oincif; olong bchan=BChan-1, echan=EChan-1, bif=BIF-1, eif=EIF-1; /* Data increments */ nstok = outDesc->inaxes[outDesc->jlocs]; iincs = outDesc->incs; iincf = outDesc->incf; iincif = outDesc->incif; oincs = outDesc->incs; oincf = outDesc->incf; oincif = outDesc->incif; /* Copy to output */ /* Loop over Stokes */ for (js=0; js<nstok; js++) { /* Stokes loop */ for (jif=bif; jif<=eif; jif++) { /* IF loop */ for (jf=bchan; jf<=echan; jf+=chinc) { /* Frequency loop */ jndx = js*iincs + jif*iincif + jf*iincf; ojf = jf - bchan; ojif = jif - bif; indx = js*oincs + ojif*oincif + ojf*oincf; outBuffer[indx] = inBuffer[jndx]; outBuffer[indx+1] = inBuffer[jndx+1]; outBuffer[indx+2] = inBuffer[jndx+2]; } /* end Frequency loop */ } /* end IF loop */ } /* end Stokes loop */ } /* end FreqSel */ /** * Update FQ table for averaging * \param inUV Input UV data * \param chAvg Number of channels averaged * \param fqid Desired FQ ID to update * \param err Error stack, returns if not empty. */ static void FQSel (ObitUV *inUV, olong chAvg, olong fqid, ObitErr *err) { ObitTableFQ *inTab=NULL; olong iFQver, highFQver; oint numIF; olong i, nif; odouble *freqOff=NULL; ofloat *chBandw=NULL; oint *sideBand=NULL; gchar *FQType = "AIPS FQ"; gchar *routine = "ObitUVUtil:FQSel"; /* error checks */ if (err->error) return; g_assert (ObitUVIsA(inUV)); /* How many FQ tables */ highFQver = ObitTableListGetHigh (inUV->tableList, FQType); /* Are there any? */ if (highFQver <= 0) return; /* Should only be one FQ table */ iFQver = 1; if (inUV->myDesc->jlocif>=0) nif = inUV->myDesc->inaxes[inUV->myDesc->jlocif]; else nif = 1; /* Get input table */ numIF = 0; inTab = newObitTableFQValue (inUV->name, (ObitData*)inUV, &iFQver, OBIT_IO_ReadOnly, numIF, err); if (err->error) Obit_traceback_msg (err, routine, inUV->name); /* Find it? */ Obit_return_if_fail(((inTab!=NULL) || (nif<=1)), err, "%s: Could not find FQ table for %s %d IFs", routine, inUV->name, nif); /* Fetch values */ ObitTableFQGetInfo (inTab, fqid, &nif, &freqOff, &sideBand, &chBandw, err); if (err->error) Obit_traceback_msg (err, routine, inTab->name); /* Update channel widths */ for (i=0; i<nif; i++) chBandw[i] *= (ofloat)chAvg; /* Save values */ ObitTableFQPutInfo (inTab, fqid, nif, freqOff, sideBand, chBandw, err); if (err->error) Obit_traceback_msg (err, routine, inTab->name); /* Cleanup */ if (freqOff) g_free(freqOff); if (sideBand) g_free(sideBand); if (chBandw) g_free(chBandw); inTab = ObitTableFQUnref(inTab); } /* end FQSel */ /** * Low accuracy inverse Sinc function * \param arg Argument * \return angle in radians */ static ofloat InvSinc(ofloat arg) { odouble x0, x1, a; olong i, n=1000; /* Some iterations of Newton-Raphson starting with the value near 1.0 */ x1 = 0.001; for (i=0; i<n; i++) { x0 = x1; a = x0 * G_PI; x1 = x0 - ((sin(a)/a) - arg) / ((a*cos(a) - G_PI*sin(a))/(a*a)); if (fabs(x1-x0)<1.0e-6) break; /* Convergence test */ } return (ofloat)x1; } /* end InvSinc */
{ "alphanum_fraction": 0.6277283381, "avg_line_length": 35.9531060737, "ext": "c", "hexsha": "a83196dce9b2194a26edacfd76374a351d83a128", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_path": "ObitSystem/Obit/src/ObitUVUtil.c", "max_stars_repo_stars_event_max_datetime": "2020-09-01T05:30:45.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-01T05:30:45.000Z", "num_tokens": 69359, "size": 207773 }
/* block/gsl_block_ushort.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_BLOCK_USHORT_H__ #define __GSL_BLOCK_USHORT_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS struct gsl_block_ushort_struct { size_t size; unsigned short *data; }; typedef struct gsl_block_ushort_struct gsl_block_ushort; gsl_block_ushort *gsl_block_ushort_alloc (const size_t n); gsl_block_ushort *gsl_block_ushort_calloc (const size_t n); void gsl_block_ushort_free (gsl_block_ushort * b); int gsl_block_ushort_fread (FILE * stream, gsl_block_ushort * b); int gsl_block_ushort_fwrite (FILE * stream, const gsl_block_ushort * b); int gsl_block_ushort_fscanf (FILE * stream, gsl_block_ushort * b); int gsl_block_ushort_fprintf (FILE * stream, const gsl_block_ushort * b, const char *format); int gsl_block_ushort_raw_fread (FILE * stream, unsigned short * b, const size_t n, const size_t stride); int gsl_block_ushort_raw_fwrite (FILE * stream, const unsigned short * b, const size_t n, const size_t stride); int gsl_block_ushort_raw_fscanf (FILE * stream, unsigned short * b, const size_t n, const size_t stride); int gsl_block_ushort_raw_fprintf (FILE * stream, const unsigned short * b, const size_t n, const size_t stride, const char *format); size_t gsl_block_ushort_size (const gsl_block_ushort * b); unsigned short * gsl_block_ushort_data (const gsl_block_ushort * b); __END_DECLS #endif /* __GSL_BLOCK_USHORT_H__ */
{ "alphanum_fraction": 0.7727845443, "avg_line_length": 36.0757575758, "ext": "h", "hexsha": "f06f320d3e73fb7783926974159630adc10c1861", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_line_length": 132, "max_stars_count": 30, "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_path": "gsl_subset/gsl/gsl_block_ushort.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "num_tokens": 624, "size": 2381 }
static char help[] = "Solve the linear biharmonic equation in 2D. Equation is\n" " Lap^2 u = f\n" "where Lap = - grad^2 is the positive Laplacian, equivalently\n" " u_xxxx + 2 u_xxyy + u_yyyy = f(x,y)\n" "Domain is unit square S = (0,1)^2. Boundary conditions are homogeneous\n" "simply-supported: u = 0, Lap u = 0. The equation is rewritten as a\n" "2x2 block system with SPD Laplacian blocks on the diagonal:\n" " | Lap | 0 | | v | | f | \n" " |-----|-----| |---| = |---| \n" " | -I | Lap | | u | | 0 | \n" "Includes manufactured, polynomial exact solution. The discretization is\n" "structured-grid (DMDA) finite differences. Includes analytical Jacobian.\n" "Recommended preconditioning combines fieldsplit:\n" " -pc_type fieldsplit -pc_fieldsplit_type multiplicative|additive \n" "with multigrid as the preconditioner for the diagonal blocks:\n" " -fieldsplit_v_pc_type mg|gamg -fieldsplit_u_pc_type mg|gamg\n" "(GMG requires setting levels and Galerkin coarsening.) One can also do\n" "monolithic multigrid (-pc_type mg|gamg).\n\n"; #include <petsc.h> typedef struct { PetscReal v, u; } Field; typedef struct { PetscReal (*f)(PetscReal x, PetscReal y); // right-hand side } BiharmCtx; static PetscReal c(PetscReal x) { return x*x*x * (1.0-x)*(1.0-x)*(1.0-x); } static PetscReal ddc(PetscReal x) { return 6.0 * x * (1.0-x) * (1.0 - 5.0 * x + 5.0 * x*x); } static PetscReal d4c(PetscReal x) { return - 72.0 * (1.0 - 5.0 * x + 5.0 * x*x); } static PetscReal u_exact_fcn(PetscReal x, PetscReal y) { return c(x) * c(y); } static PetscReal lap_u_exact_fcn(PetscReal x, PetscReal y) { return - ddc(x) * c(y) - c(x) * ddc(y); // Lap u = - grad^2 u } static PetscReal f_fcn(PetscReal x, PetscReal y) { return d4c(x) * c(y) + 2.0 * ddc(x) * ddc(y) + c(x) * d4c(y); // Lap^2 u = grad^4 u } extern PetscErrorCode FormExactWLocal(DMDALocalInfo*, Field**, BiharmCtx*); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, Field**, Field **FF, BiharmCtx*); extern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, Field**, Mat, Mat, BiharmCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da; SNES snes; Vec w, w_initial, w_exact; BiharmCtx user; Field **aW; PetscReal normv, normu, errv, erru; DMDALocalInfo info; ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr; user.f = &f_fcn; ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR, 3,3,PETSC_DECIDE,PETSC_DECIDE, 2,1, // degrees of freedom, stencil width NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,-1.0); CHKERRQ(ierr); ierr = DMDASetFieldName(da,0,"v"); CHKERRQ(ierr); ierr = DMDASetFieldName(da,1,"u"); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetDM(snes,da); CHKERRQ(ierr); ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDASNESSetJacobianLocal(da, (DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr); ierr = SNESSetType(snes,SNESKSPONLY); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = DMGetGlobalVector(da,&w_initial); CHKERRQ(ierr); ierr = VecSet(w_initial,0.0); CHKERRQ(ierr); ierr = SNESSolve(snes,NULL,w_initial); CHKERRQ(ierr); ierr = DMRestoreGlobalVector(da,&w_initial); CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); ierr = SNESGetSolution(snes,&w); CHKERRQ(ierr); ierr = SNESGetDM(snes,&da); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); ierr = DMCreateGlobalVector(da,&w_exact); CHKERRQ(ierr); ierr = DMDAVecGetArray(da,w_exact,&aW); CHKERRQ(ierr); ierr = FormExactWLocal(&info,aW,&user); CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da,w_exact,&aW); CHKERRQ(ierr); ierr = VecStrideNorm(w_exact,0,NORM_INFINITY,&normv); CHKERRQ(ierr); ierr = VecStrideNorm(w_exact,1,NORM_INFINITY,&normu); CHKERRQ(ierr); ierr = VecAXPY(w,-1.0,w_exact); CHKERRQ(ierr); ierr = VecStrideNorm(w,0,NORM_INFINITY,&errv); CHKERRQ(ierr); ierr = VecStrideNorm(w,1,NORM_INFINITY,&erru); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "done on %d x %d grid ...\n" " errors |v-vex|_inf/|vex|_inf = %.5e, |u-uex|_inf/|uex|_inf = %.5e\n", info.mx,info.my,errv/normv,erru/normu); CHKERRQ(ierr); ierr = VecDestroy(&w_exact); CHKERRQ(ierr); ierr = SNESDestroy(&snes); CHKERRQ(ierr); return PetscFinalize(); } PetscErrorCode FormExactWLocal(DMDALocalInfo *info, Field **aW, BiharmCtx *user) { PetscErrorCode ierr; PetscInt i, j; PetscReal xymin[2], xymax[2], hx, hy, x, y; ierr = DMGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); for (j = info->ys; j < info->ys + info->ym; j++) { y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { x = i * hx; aW[j][i].u = u_exact_fcn(x,y); aW[j][i].v = lap_u_exact_fcn(x,y); } } return 0; } PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, Field **aW, Field **FF, BiharmCtx *user) { PetscErrorCode ierr; PetscInt i, j; PetscReal xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, x, y, ve, vw, vn, vs, ue, uw, un, us; ierr = DMGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); darea = hx * hy; // multiply FD equations by this scx = hy / hx; scy = hx / hy; scdiag = 2.0 * (scx + scy); // diagonal scaling for (j = info->ys; j < info->ys + info->ym; j++) { y = xymin[1] + j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { x = xymin[0] + i * hx; if (i==0 || i==info->mx-1 || j==0 || j==info->my-1) { FF[j][i].v = scdiag * aW[j][i].v; FF[j][i].u = scdiag * aW[j][i].u; } else { ve = (i+1 == info->mx-1) ? 0.0 : aW[j][i+1].v; vw = (i-1 == 0) ? 0.0 : aW[j][i-1].v; vn = (j+1 == info->my-1) ? 0.0 : aW[j+1][i].v; vs = (j-1 == 0) ? 0.0 : aW[j-1][i].v; FF[j][i].v = scdiag * aW[j][i].v - scx * (vw + ve) - scy * (vs + vn) - darea * (*(user->f))(x,y); ue = (i+1 == info->mx-1) ? 0.0 : aW[j][i+1].u; uw = (i-1 == 0) ? 0.0 : aW[j][i-1].u; un = (j+1 == info->my-1) ? 0.0 : aW[j+1][i].u; us = (j-1 == 0) ? 0.0 : aW[j-1][i].u; FF[j][i].u = - darea * aW[j][i].v + scdiag * aW[j][i].u - scx * (uw + ue) - scy * (us + un); } } } ierr = PetscLogFlops(18.0*info->xm*info->ym);CHKERRQ(ierr); return 0; } PetscErrorCode FormJacobianLocal(DMDALocalInfo *info, Field **aW, Mat J, Mat Jpre, BiharmCtx *user) { PetscErrorCode ierr; PetscInt i, j, c, ncol; PetscReal xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, val[6]; MatStencil col[6], row; ierr = DMGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); darea = hx * hy; // multiply FD equations by this scx = hy / hx; scy = hx / hy; scdiag = 2.0 * (scx + scy); // diagonal scaling for (j = info->ys; j < info->ys + info->ym; j++) { row.j = j; for (i = info->xs; i < info->xs + info->xm; i++) { row.i = i; for (c = 0; c < 2; c++) { // v,u equations are c=0,1 row.c = c; col[0].c = c; col[0].i = i; col[0].j = j; val[0] = scdiag; if (i==0 || i==info->mx-1 || j==0 || j==info->my-1) { ierr = MatSetValuesStencil(Jpre,1,&row,1,col,val,INSERT_VALUES); CHKERRQ(ierr); } else { ncol = 1; if (i+1 < info->mx-1) { col[ncol].c = c; col[ncol].i = i+1; col[ncol].j = j; val[ncol++] = -scx; } if (i-1 > 0) { col[ncol].c = c; col[ncol].i = i-1; col[ncol].j = j; val[ncol++] = -scx; } if (j+1 < info->my-1) { col[ncol].c = c; col[ncol].i = i; col[ncol].j = j+1; val[ncol++] = -scy; } if (j-1 > 0) { col[ncol].c = c; col[ncol].i = i; col[ncol].j = j-1; val[ncol++] = -scy; } if (c == 1) { // u equation; has off-diagonal block entry col[ncol].c = 0; col[ncol].i = i; col[ncol].j = j; val[ncol++] = - darea; } ierr = MatSetValuesStencil(Jpre,1,&row,ncol,col,val,INSERT_VALUES); CHKERRQ(ierr); } } } } ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); if (J != Jpre) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); } return 0; }
{ "alphanum_fraction": 0.5251199687, "avg_line_length": 41.8483606557, "ext": "c", "hexsha": "6bcf7d8b450455724b16f4fd0469a18d84cb9f32", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch7/biharm.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch7/biharm.c", "max_line_length": 91, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch7/biharm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 3377, "size": 10211 }
#ifndef SIMPROP_UTILS_GSL_H #define SIMPROP_UTILS_GSL_H #include <gsl/gsl_deriv.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_roots.h> #include <cassert> #include <cmath> #include <functional> #include <iostream> #include <vector> namespace simprop { namespace utils { // Axis std::vector<double> LinAxis(const double &min, const double &max, const size_t &size); std::vector<double> LogAxis(const double &min, const double &max, const size_t &size); inline bool isInside(double x, const std::vector<double> &X) { return (x >= X.front() && x <= X.back()); }; double interpolate(double x, const std::vector<double> &X, const std::vector<double> &Y); double cspline(double x, const std::vector<double> &X, const std::vector<double> &Y); double interpolateEquidistant(double x, double lo, double hi, const std::vector<double> &Y); double interpolate2d(double x, double y, const std::vector<double> &X, const std::vector<double> &Y, const std::vector<double> &Z); template <typename T> T deriv(std::function<T(T)> f, T x, double rel_error = 1e-4) { double result; double abs_error = 0.0; // disabled gsl_function F; F.function = [](double x, void *vf) -> double { auto &func = *static_cast<std::function<double(double)> *>(vf); return func(x); }; F.params = &f; gsl_deriv_central(&F, static_cast<double>(x), rel_error, &result, &abs_error); return T(result); } template <typename T> T deriv5pt(std::function<T(T)> f, T x, T h) { auto result = -f(x + 2 * h) + 8 * f(x + h) - 8 * f(x - h) + f(x - 2 * h); return T(result) / 12 / h; } template <typename T> T QAGIntegration(std::function<T(T)> f, T start, T stop, int LIMIT, double rel_error = 1e-4) { double a = static_cast<double>(start); double b = static_cast<double>(stop); double abs_error = 0.0; // disabled int key = GSL_INTEG_GAUSS31; double result; double error; gsl_function F; F.function = [](double x, void *vf) -> double { auto &func = *static_cast<std::function<double(double)> *>(vf); return func(x); }; F.params = &f; gsl_integration_workspace *workspace_ptr = gsl_integration_workspace_alloc(LIMIT); gsl_integration_qag(&F, a, b, abs_error, rel_error, LIMIT, key, workspace_ptr, &result, &error); gsl_integration_workspace_free(workspace_ptr); return T(result); } template <typename T> T QAGSIntegration(std::function<T(T)> f, T start, T stop, int LIMIT, double rel_error = 1e-4) { double a = static_cast<double>(start); double b = static_cast<double>(stop); double abs_error = 0.0; // disabled double result; double error; gsl_function F; F.function = [](double x, void *vf) -> double { auto &func = *static_cast<std::function<double(double)> *>(vf); return func(x); }; F.params = &f; gsl_integration_workspace *workspace_ptr = gsl_integration_workspace_alloc(LIMIT); gsl_integration_qags(&F, a, b, abs_error, rel_error, LIMIT, workspace_ptr, &result, &error); gsl_integration_workspace_free(workspace_ptr); return T(result); } template <typename T> T simpsonIntegration(std::function<T(T)> f, T start, T stop, int N = 100) { const T a = start; const T b = stop; const T h = (b - a) / N; const T XI0 = f(a) + f(b); T XI1 = 0, XI2 = 0; for (int i = 1; i < N; ++i) { const T X = a + i * h; if (i % 2 == 0) XI2 = XI2 + f(X); else XI1 = XI1 + f(X); } return h * (XI0 + 2 * XI2 + 4 * XI1) / 3.0; } template <typename T> T rootFinder(std::function<T(T)> f, T xLower, T xUpper, int maxIter, double relError = 1e-4) { int status; int iter = 0; const gsl_root_fsolver_type *solverType; gsl_root_fsolver *solver; T r = 0; gsl_function F; F.function = [](double x, void *vf) -> double { auto &func = *static_cast<std::function<double(double)> *>(vf); return func(x); }; F.params = &f; solverType = gsl_root_fsolver_brent; solver = gsl_root_fsolver_alloc(solverType); gsl_root_fsolver_set(solver, &F, xLower, xUpper); do { iter++; status = gsl_root_fsolver_iterate(solver); r = (T)gsl_root_fsolver_root(solver); xLower = gsl_root_fsolver_x_lower(solver); xUpper = gsl_root_fsolver_x_upper(solver); status = gsl_root_test_interval(xLower, xUpper, 0, relError); } while (status == GSL_CONTINUE && iter < maxIter); gsl_root_fsolver_free(solver); return r; } template <typename T> T rk4fixed(std::function<T(T, T)> dydx, T yStart, T xStart, T xEnd, T h) { size_t steps = (size_t)((xEnd - xStart) / h); T x = xStart; T y = yStart; while (steps--) { auto k1 = h * dydx(x, y); auto k2 = h * dydx(x + 0.5 * h, y + 0.5 * k1); auto k3 = h * dydx(x + 0.5 * h, y + 0.5 * k2); auto k4 = h * dydx(x + h, y + k3); y += (k1 + 2. * k2 + 2. * k3 + k4) / 6.; x += h; } return y; } template <typename T> T odeiv(std::function<T(T, T)> dydx, T yStart, T xStart, T xEnd, T rel_error = 1e-4) { const size_t NEQS = 1; double abs_error = 0.0; // disabled const gsl_odeiv2_step_type *stepType = gsl_odeiv2_step_rkf45; gsl_odeiv2_step *s = gsl_odeiv2_step_alloc(stepType, NEQS); gsl_odeiv2_control *c = gsl_odeiv2_control_y_new(abs_error, static_cast<double>(rel_error)); gsl_odeiv2_evolve *e = gsl_odeiv2_evolve_alloc(NEQS); double y[1] = {yStart}; auto func = [](double t, const double *y, double *f, void *params) -> int { auto dydx = *static_cast<std::function<double(double, double)> *>(params); f[0] = dydx(t, y[0]); return GSL_SUCCESS; }; gsl_odeiv2_system sys = {func, nullptr, NEQS, &dydx}; double t = xStart, t1 = xEnd; double h = 1e-5 * (xEnd - xStart); while (t < t1) { int status = gsl_odeiv2_evolve_apply(e, c, s, &sys, &t, t1, &h, y); if (status != GSL_SUCCESS) break; } gsl_odeiv2_evolve_free(e); gsl_odeiv2_control_free(c); gsl_odeiv2_step_free(s); return y[0]; } } // namespace utils } // namespace simprop #endif
{ "alphanum_fraction": 0.6518211921, "avg_line_length": 28.0930232558, "ext": "h", "hexsha": "9f6f58a6cd823f3169103a860e87eb30d725f31b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carmeloevoli/SimProp-beta", "max_forks_repo_path": "include/simprop/utils/numeric.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carmeloevoli/SimProp-beta", "max_issues_repo_path": "include/simprop/utils/numeric.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d3fce16b0d288abcd36b439ef181b50e96b1ee6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "carmeloevoli/SimProp-beta", "max_stars_repo_path": "include/simprop/utils/numeric.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1939, "size": 6040 }
/** * * @file qwrapper_chegst.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @date 2010-11-15 * @generated c Tue Jan 7 11:44:59 2014 * **/ #include <lapacke.h> #include "common.h" #undef REAL #define COMPLEX /***************************************************************************//** * **/ void QUARK_CORE_chegst(Quark *quark, Quark_Task_Flags *task_flags, int itype, PLASMA_enum uplo, int n, PLASMA_Complex32_t *A, int lda, PLASMA_Complex32_t *B, int ldb, PLASMA_sequence *sequence, PLASMA_request *request, int iinfo) { QUARK_Insert_Task(quark, CORE_chegst_quark, task_flags, sizeof(int), &itype, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &n, VALUE, sizeof(PLASMA_Complex32_t)*lda*n, A, INOUT, sizeof(int), &lda, VALUE, #ifdef COMPLEX sizeof(PLASMA_Complex32_t)*ldb*n, B, INOUT, #else sizeof(PLASMA_Complex32_t)*ldb*n, B, INPUT, #endif sizeof(int), &ldb, VALUE, sizeof(PLASMA_sequence*), &sequence, VALUE, sizeof(PLASMA_request*), &request, VALUE, sizeof(int), &iinfo, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_chegst_quark = PCORE_chegst_quark #define CORE_chegst_quark PCORE_chegst_quark #endif void CORE_chegst_quark(Quark *quark) { int itype; PLASMA_enum uplo; int n; PLASMA_Complex32_t *A; int lda; PLASMA_Complex32_t *B; int ldb; PLASMA_sequence *sequence; PLASMA_request *request; int iinfo; int info; quark_unpack_args_10(quark, itype, uplo, n, A, lda, B, ldb, sequence, request, iinfo); info = LAPACKE_chegst_work( LAPACK_COL_MAJOR, itype, lapack_const(uplo), n, A, lda, B, ldb); if (sequence->status == PLASMA_SUCCESS && info != 0) plasma_sequence_flush(quark, sequence, request, iinfo+info); }
{ "alphanum_fraction": 0.5285016287, "avg_line_length": 30.7, "ext": "c", "hexsha": "03c74dd5f276fccfd5093b1b0d6db161292958eb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_chegst.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_chegst.c", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_chegst.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 658, "size": 2456 }
#pragma once #include <cstdint> #include <functional> #include <memory> #include <sstream> #include <string> #include <utility> #include <vector> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "chainerx/array_body.h" #include "chainerx/array_fwd.h" #include "chainerx/array_index.h" #include "chainerx/array_node.h" #include "chainerx/array_repr.h" #include "chainerx/axes.h" #include "chainerx/constant.h" #include "chainerx/context.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/enum.h" #include "chainerx/error.h" #include "chainerx/graph.h" #include "chainerx/scalar.h" #include "chainerx/shape.h" #include "chainerx/strides.h" namespace chainerx { namespace internal { BackpropId GetArrayBackpropId(const Array& array, const nonstd::optional<BackpropId>& backprop_id); Array MakeArray(const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset = 0); inline const std::shared_ptr<ArrayBody>& GetArrayBody(const Array& array); inline std::shared_ptr<ArrayBody>&& MoveArrayBody(Array&& array); } // namespace internal // The user interface of multi-dimensional arrays. // // This wraps an ArrayBody, providing accessors, an interface for graph operations and differentiable operations. class Array { public: Array() = default; // TODO(hvy): Consider making this contructor private and prohibit body from being null (assert that given body is not null). explicit Array(std::shared_ptr<internal::ArrayBody> body) : body_{std::move(body)} { if (body_ == nullptr) { throw ChainerxError{"Cannot create an array from null."}; } } // Copy constructor that copies the pointer to the body instead of the body itself. // // Use MakeView if you want to clone the body. Array(const Array& other) = default; Array(Array&& other) = default; // Assign operators just replace the body. They do not copy data between arrays. Array& operator=(const Array&) = default; Array& operator=(Array&& other) = default; Array operator-() const; Array operator==(const Array& rhs) const; Array operator!=(const Array& rhs) const; Array operator>(const Array& rhs) const; Array operator>=(const Array& rhs) const; Array operator<(const Array& rhs) const; Array operator<=(const Array& rhs) const; Array& operator+=(const Array& rhs); Array& operator+=(Scalar rhs); Array& operator-=(const Array& rhs); Array& operator-=(Scalar rhs); Array& operator*=(const Array& rhs); Array& operator*=(Scalar rhs); Array& operator/=(const Array& rhs); Array& operator/=(Scalar rhs); const Array& operator+=(const Array& rhs) const; const Array& operator+=(Scalar rhs) const; const Array& operator-=(const Array& rhs) const; const Array& operator-=(Scalar rhs) const; const Array& operator*=(const Array& rhs) const; const Array& operator*=(Scalar rhs) const; const Array& operator/=(const Array& rhs) const; const Array& operator/=(Scalar rhs) const; Array operator+(const Array& rhs) const; Array operator+(Scalar rhs) const; Array operator-(const Array& rhs) const; Array operator-(Scalar rhs) const; Array operator*(const Array& rhs) const; Array operator*(Scalar rhs) const; Array operator/(const Array& rhs) const; Array operator/(Scalar rhs) const; // Returns a view selected with the indices. Array At(const std::vector<ArrayIndex>& indices) const; // Returns a transposed view of the array. Array Transpose(const OptionalAxes& axes = nonstd::nullopt) const; // Returns a reshaped array. // TODO(niboshi): Support shape with dimension -1. Array Reshape(const Shape& newshape) const; // Returns a squeezed array with unit-length axes removed. // // If no axes are specified, all axes of unit-lengths are removed. // If no axes can be removed, an array with aliased data is returned. Array Squeeze(const OptionalAxes& axis = nonstd::nullopt) const; // Broadcasts the array to the specified shape. // Returned array is always a view to this array. Array BroadcastTo(const Shape& shape) const; // Returns the indices of the maximum values along the given axis. Array ArgMax(const OptionalAxes& axis = nonstd::nullopt) const; // Returns a sum of the array. // If `axis` is set, it will be summed over the specified axes. // Otherwise, it will be summed over all the existing axes. // Note: When implementing chainerx::Sum(), be careful of the semantics of the default value of `keepdims`. See NumPy documentation. Array Sum(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const; // Returns the maximum value of the array. // If `axis` is set, the maximum value is chosen along the specified axes. // Otherwise, all the elements are searched at once. Array Max(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const; Array Mean(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const; Array Var(const OptionalAxes& axis = nonstd::nullopt, bool keepdims = false) const; // Returns a dot product of the array with another one. Array Dot(const Array& b) const; // Takes elements specified by indices from the array. // // TODO(niboshi): Support Scalar and StackVector as indices. // TODO(niboshi): Support axis=None behavior in NumPy. // TODO(niboshi): Support indices dtype other than int64. Array Take(const Array& indices, int8_t axis) const; // Creates a copy. // It will be connected to all the graphs. // It will be always C-contiguous. Array Copy() const; // Creates a view. // It creates a new array node and connects graphs. Array MakeView() const; // Transfers the array to another device. It will be connected to all the graphs. // // If the destination is the same device, an array with aliased data is returned. // Otherwise, a C-contiguous Array will be created on the target device. // TODO(niboshi): Currently control over whether to make an alias is not supported. Array ToDevice(Device& dst_device) const; // Transfer the array to the native device. It will be connected to all the graphs. // // This is a wrapper function which calls Array::ToDevice with the native:0 device. // See also: Array::ToDevice(); Array ToNative() const; // Creates a copy or a view. It will be disconnected from all the graphs. // If `kind` is `CopyKind::kCopy`, the returned array will be always C-contiguous. Array AsGradStopped(CopyKind kind = CopyKind::kView) const; // Creates a copy or a view. It will be disconnected from the specified graphs. // If `kind` is `CopyKind::kCopy`, the returned array will be always C-contiguous. Array AsGradStopped(gsl::span<const BackpropId> backprop_ids, CopyKind kind = CopyKind::kView) const; Array AsGradStopped(std::initializer_list<const BackpropId> backprop_ids, CopyKind kind = CopyKind::kView) const { return AsGradStopped(gsl::span<const BackpropId>{backprop_ids.begin(), backprop_ids.end()}, kind); } // Casts to a specified type. // By default, always returns a newly allocated array. If `copy` is false, // and the dtype requirement is satisfied, the input array is returned instead of a copy. Array AsType(Dtype dtype, bool copy = true) const; void Fill(Scalar value) const; // Returns the gradient of the array. // // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID. // ChainerxError is thrown if the array is not flagged as requiring gradient. // This function ignores no/force-backprop mode. const nonstd::optional<Array>& GetGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const; // Sets the gradient of the array. // This function also flags the array as requiring gradient, so that preceding GetGrad() can return the gradient. // // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID. // This function ignores no/force-backprop mode. void SetGrad(Array grad, const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const; // Clears the gradient of the array if set. // This function does not change the state of the array other than that. For example, if the array is flagged as requiring gradient, // that will not change. // // ChainerxError is thrown if the array is constant with respect to the computation for the specified backprop ID. // This function ignores no/force-backprop mode. void ClearGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const; // Returns whether the array needs to backprop. // // If no-backprop mode is set with respect to the specified backprop ID, this function returns false. bool IsBackpropRequired(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const; bool IsBackpropRequired(AnyGraph any_graph) const; // Returns whether the array is flagged to compute the gradient during backprop. // // This function ignores no/force-backprop mode. bool IsGradRequired(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const; // Flags the array to compute the gradient during backprop. // If the array is constant with respect to the computation of the backprop ID, this function makes the array non-constant. // // This function ignores no/force-backprop mode. const Array& RequireGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) const { return RequireGradImpl(*this, backprop_id); } Array& RequireGrad(const nonstd::optional<BackpropId>& backprop_id = nonstd::nullopt) { return RequireGradImpl(*this, backprop_id); } int64_t GetTotalSize() const { return body_->GetTotalSize(); } int64_t GetNBytes() const { return body_->GetNBytes(); } int64_t GetItemSize() const { return body_->GetItemSize(); } bool IsContiguous() const { return body_->IsContiguous(); } std::string ToString() const; Context& context() const { return body_->device().context(); } Dtype dtype() const { return body_->dtype(); } Device& device() const { return body_->device(); } int8_t ndim() const { return body_->ndim(); } const Shape& shape() const { return body_->shape(); } const Strides& strides() const { return body_->strides(); } const std::shared_ptr<void>& data() const { return body_->data(); } void* raw_data() const { return body_->data().get(); } int64_t offset() const { return body_->offset(); } private: friend Array internal::MakeArray( const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset); friend const std::shared_ptr<internal::ArrayBody>& internal::GetArrayBody(const Array& array); friend std::shared_ptr<internal::ArrayBody>&& internal::MoveArrayBody(Array&& array); Array(const Shape& shape, const Strides& strides, Dtype dtype, Device& device, std::shared_ptr<void> data, int64_t offset = 0); template <typename T> static T& RequireGradImpl(T& array, const nonstd::optional<BackpropId>& backprop_id); std::shared_ptr<internal::ArrayBody> body_; }; Array operator+(Scalar lhs, const Array& rhs); Array operator-(Scalar lhs, const Array& rhs); Array operator*(Scalar lhs, const Array& rhs); // TODO(hvy): Implement Scalar / Array using e.g. multiplication with reciprocal. namespace internal { inline const std::shared_ptr<ArrayBody>& GetArrayBody(const Array& array) { return array.body_; } inline std::shared_ptr<ArrayBody>&& MoveArrayBody(Array&& array) { return std::move(array.body_); } std::vector<std::shared_ptr<ArrayBody>> MoveArrayBodies(std::vector<Array>&& arrays); std::vector<std::shared_ptr<ArrayBody>> MoveArrayBodies(std::vector<nonstd::optional<Array>>&& arrays); } // namespace internal void DebugDumpComputationalGraph( std::ostream& os, const Array& array, const nonstd::optional<BackpropId>& backprop_id, int indent = 0, const std::vector<std::pair<ConstArrayRef, std::string>>& array_name_map = {}); } // namespace chainerx
{ "alphanum_fraction": 0.7063727455, "avg_line_length": 41.3079470199, "ext": "h", "hexsha": "37fa057ac993e1bef2f088a325321927292a07fa", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hitsgub/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/array.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hitsgub/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/array.h", "max_line_length": 137, "max_stars_count": 1, "max_stars_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hitsgub/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/array.h", "max_stars_repo_stars_event_max_datetime": "2019-03-09T07:39:07.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-09T07:39:07.000Z", "num_tokens": 3028, "size": 12475 }