Exemple #1
0
void findMinMax(node *ptr, int *min, int *max, int hd){
  if(ptr == NULL)
    return;
  if(hd < *min)
    *min = hd;
  else if (hd > *max)
    *max = hd;
  findMinMax(ptr->left, min,max,hd+1);
  findMinMax(ptr->right, min,max,hd-1);
}
Exemple #2
0
int main(int argc, char *argv[]){

  int count = 151671;
  int category = 1;

  if(argc != 3){
    fprintf(stderr, "Usage: ./minmax n category\nHere n is the number of lines, and category is a number from 0..5 indicating which category you want the min and max numbers for\n");
    exit(1);
  } else {
    count    = atoi(argv[1]);
    category = atoi(argv[2]);
  }

  CensusData *cd = new CensusData[count];

  readCensusData(cd, count);
  int minIndex = 0;
  int maxIndex = 0;
  findMinMax(minIndex, maxIndex, cd, count, category);

  printPercentsInfo(minIndex, cd);
  printPercentsInfo(maxIndex, cd);

  return 0;
}
void countingSort( int v[], int N)
{
    int mi, max;
    int z=0;
    findMinMax(v, N, mi, max);
    int nlen = (max-mi)+1;
    int* temp = new int[nlen];
    memset(temp, 0, nlen * sizeof( int ));
    
    for( int i = 0; i < N; i++ )
    {
        temp[v[i] - mi]++;
    }
    
    for( int i = mi; i <= max; i++ )
    {
        while( temp[i - mi] )
        {
            v[z++] = i;
            temp[i - mi]--;
        }
    }
    
    
    delete [] temp;
}
Exemple #4
0
void CalDistPointfromGrid(int gridIdx_X, int gridIdx_Y, int* pCnt) {
	cur = buffNodes_inOneGrid[gridIdx_X][gridIdx_Y].next;
	if(cur!=NULL) {
		PRINTDEBUGMODE1("around[%d][%d]\n",gridIdx_X,gridIdx_Y);
		//FOR_DEBUG_PRINT("x %lf, y %lf\n", (double)i+(double)GRID_SIZE/2,(double)j+(double)GRID_SIZE/2);
		while(cur!=NULL){
			findMinMax(cur->x, cur->y);
			(*pCnt)++;
			if(Head_distfromGrid==NULL) {
				Head_distfromGrid = (Distnode*)malloc(sizeof(struct Dist_Node));
				Head_distfromGrid -> coord = cur;
				Head_distfromGrid -> next = NULL;
				Tail_DistfromGrid = Head_distfromGrid;
			} else {
				Cur_DistfromGrid = (Distnode*)malloc(sizeof(struct Dist_Node));
				Cur_DistfromGrid -> coord = cur;
				Cur_DistfromGrid -> next = NULL;
				Tail_DistfromGrid-> next = Cur_DistfromGrid;
				Tail_DistfromGrid = Cur_DistfromGrid;
			}
			cur = cur->next;
		}
	} else {
		PRINTDEBUGMODE1("NO POINT IN THIS GRID \n");
	}
}
Exemple #5
0
//computes the tfce score of a 3D statistic map(dim_x*dim_y*dim_z)
float * tfce_score(float * map, int dim_x, int dim_y, int dim_z, float E, float H, float dh){
	int n = dim_x * dim_y * dim_z;
	float minData = 0; float maxData = 0; float rangeData = 0;
	float * posData; float * negData;
	float precision, increment;
	float h;
	int i,j;
	int * indexPosData; int * indexNegData; int * indexMatchingData;
	float * clustered_map;
	int num_clusters;
	int numOfElementsMatching;
	float * toReturn = fill0(n);
	float minPos = 0; float maxPos = 0;
	int steps = 0;

	findMinMax(map, n, &minData, &maxData, &rangeData);
	precision = rangeData/dh;

	if (precision > 200) {
		increment = rangeData/200;
	} else{
		increment = rangeData/precision;	
	}

	steps = ceil(rangeData / increment);
#pragma omp parallel for
	for (i = 0; i < steps; i++) {
		computeTfceIteration(minData + i*increment, map, n, dim_x, dim_y, dim_z, E, H, increment, toReturn);
	}
	
	return toReturn;
}
  int maxProfit(int k, vector<int> &prices) {

    findMinMax(prices);
    k = min(k, (int)(prices.size() / 2));

    if (k == 0)
      return 0;

    int size = 2 * k;
    vector<int> balanceCurrent(size);
    vector<int> balanceNext(size);

    for (int idx = 0; idx < size; ++idx) {
      balanceCurrent[idx] = (idx & 1) ? 0 : INT_MIN;
    }

    for (int i = 0; i < prices.size(); ++i) {
      balanceNext[0] = max(balanceCurrent[0], -prices[i]);
      for (int j = 1; j < size; ++j) {
        if (j & 1)
          balanceNext[j] =
              max(balanceCurrent[j], balanceCurrent[j - 1] + prices[i]);
        else
          balanceNext[j] =
              max(balanceCurrent[j], balanceCurrent[j - 1] - prices[i]);
      }
      swap(balanceCurrent, balanceNext);
    }

    return balanceCurrent.back();
  }
int main(void) {
  int max, min;
  init(m,n);
  printf("Масивът:\n"); print(m,n);
  printf("Максимален елемент: %d\n", findMax(m,n));
  printf("Минимален елемент: %d\n", findMin(m,n));
  findMinMax(&min, &max, m, n);
  printf("Минимален и максимален елемент едновременно: %d %d\n", min, max);
  printf("Втори по големина елемент: %d\n", findSecondMax(m,n));
  return 0;
}
float AudioSampleBuffer::getMagnitude (const int channel,
                                       const int startSample,
                                       const int numSamples) const noexcept
{
    jassert (isPositiveAndBelow (channel, numChannels));
    jassert (startSample >= 0 && startSample + numSamples <= size);

    float mn, mx;
    findMinMax (channel, startSample, numSamples, mn, mx);

    return jmax (mn, -mn, mx, -mx);
}
Exemple #9
0
 ReturnCode setData_(const Data &data, const Weights *weights)
 {
     MSS_BEGIN(ReturnCode);
     data_ = data;
     MSS(findMinMax(min_, max_, data_));
     if (weights)
         weights_ = *weights;
     else
         weights_ = Weights(data_.size(), 1.0);
     weightDistribution_.setProbs(weights_);
     MSS_END();
 }
  void findMinMax(const cv::Mat &ir, const std::vector<cv::Point2f> &pointsIr)
  {
    minIr = 0xFFFF;
    maxIr = 0;
    for(size_t i = 0; i < pointsIr.size(); ++i)
    {
      const cv::Point2f &p = pointsIr[i];
      cv::Rect roi(std::max(0, (int)p.x - 2), std::max(0, (int)p.y - 2), 9, 9);
      roi.width = std::min(roi.width, ir.cols - roi.x);
      roi.height = std::min(roi.height, ir.rows - roi.y);

      findMinMax(ir(roi));
    }
  }
Exemple #11
0
void PointModel::moveToOrigin()
{
	findMinMax();
	double midx = (v_minmax[0] + v_minmax[1]) / 2;
	double midy = (v_minmax[2] + v_minmax[3]) / 2;
	double midz = (v_minmax[4] + v_minmax[5]) / 2;

	Matrix4 printTranslate;
	printTranslate.makeTranslate(midx * -1, midy * -1, midz * -1);
	printTranslate.print("Translate matrix is : ");
	cout << endl;

	this->model2world = printTranslate * this->model2world;
}
Exemple #12
0
void verticalTraversal(node *ptr){
  int min=0;
  int max=0;
  int lineNo=0;
  int hd = 0;
  findMinMax(ptr, &min, &max, hd);
  printf("Min: %d\nMax :%d\n",min,max);
  for(lineNo = min; lineNo <= max;lineNo++){
    printVerticalLine(ptr,lineNo,0);
    printf("\n");
  }
  /*
  stack vs,s;
  vs.top = -1;
  s.top = -1;
  while(ptr->left!= NULL){
    push(&vs,ptr);
    ptr = ptr->left;
  }
  while(ptr != NULL){
    printf("%d ",ptr->data);
    if(ptr->right != NULL){
      push(&s,ptr->right);
    }
    ptr = pop(&vs);
    if(ptr == NULL){
      ptr = pop(&s);
      while(ptr != NULL){
	printf("%d ",ptr->data);
	ptr = pop(&s);
      }
      printf("\n");
    }
    printf("\n");
    }*/
}
bool
RawSlabsPlugin::setFile(QStringList files)
{
  m_fileName = files;

  {
    m_slices.clear();

    QFileInfo fi(files[0]);

    QString hdrflnm;
    hdrflnm = QFileDialog::getOpenFileName(0,
					"Load text header file",
					fi.absolutePath(),
					"Files (*.*)");

    int nfX0, nfY0, nfZ0;
    
    if (hdrflnm.isEmpty())
      {
	uchar nvt0;
	QFile fd(m_fileName[0]);
	fd.open(QFile::ReadOnly);
	fd.read((char*)&nvt0, sizeof(unsigned char));
	fd.read((char*)&nfX0, sizeof(int));
	fd.read((char*)&nfY0, sizeof(int));
	fd.read((char*)&nfZ0, sizeof(int));
	fd.close();
    
	m_voxelType = _UChar;
	if (nvt0 == 0) m_voxelType = _UChar;
	if (nvt0 == 1) m_voxelType = _Char;
	if (nvt0 == 2) m_voxelType = _UShort;
	if (nvt0 == 3) m_voxelType = _Short;
	if (nvt0 == 4) m_voxelType = _Int;
	if (nvt0 == 8) m_voxelType = _Float;

	m_headerBytes = m_skipBytes = 13;
	int nslices = nfX0;
	m_slices.append(nslices);
	
	for (int nf=1; nf<m_fileName.count(); nf++)
	  {
	    uchar nvt;
	    int nfX, nfY, nfZ;
	    QFile fd(m_fileName[nf]);
	    fd.open(QFile::ReadOnly);
	    fd.read((char*)&nvt, sizeof(unsigned char));
	    fd.read((char*)&nfX, sizeof(int));
	    fd.read((char*)&nfY, sizeof(int));
	    fd.read((char*)&nfZ, sizeof(int));
	    fd.close();
	    if (nvt != nvt0 || nfY != nfY0 || nfZ != nfZ0)
	      {
		QMessageBox::information(0, "", "Raw File format does not match");
		return false;
	      }
	    
	    nslices += nfX;
	    m_slices.append(nslices);
	  }
      }
    else
      {
	// load header information from a text file
	
	int nvt0, nvt;
	int nfX, nfY, nfZ;
	
	QFile fd(hdrflnm);
	fd.open(QFile::ReadOnly | QFile::Text);
	QTextStream in(&fd);

	QString line = (in.readLine()).simplified();
	QStringList words = line.split(" ", QString::SkipEmptyParts);
	if (words.count() >= 2)
	  {
	    int nvt0 = words[0].toInt();
	    m_voxelType = _UChar;
	    if (nvt0 == 0) m_voxelType = _UChar;
	    if (nvt0 == 1) m_voxelType = _Char;
	    if (nvt0 == 2) m_voxelType = _UShort;
	    if (nvt0 == 3) m_voxelType = _Short;
	    if (nvt0 == 4) m_voxelType = _Int;
	    if (nvt0 == 8) m_voxelType = _Float;
	    m_headerBytes = m_skipBytes = words[1].toInt();
	  }
	else
	  {
	    QMessageBox::information(0, "",
	     QString("Expecting voxeltype and headerbytes\nGot this %1").arg(line));
	    return false;
	  }

	int nslices = 0;
	while (!in.atEnd())
	  {
	    line = (in.readLine()).simplified();
	    words = line.split(" ", QString::SkipEmptyParts);
	    if (words.count() >= 3)
	      {
		nfX = words[0].toInt();
		nfY = words[1].toInt();
		nfZ = words[2].toInt();
		
		if (nslices == 0)
		  {
		    nfY0 = nfY;
		    nfZ0 = nfZ;
		  }
		else
		  {
		    if (nfY0 != nfY || nfZ0 != nfZ)
		      {
			QMessageBox::information(0, "",
			   QString("Slice size not same :: %1 %2 : %3 %4").\
			     arg(nfY0).arg(nfZ0).arg(nfY).arg(nfZ));
			return false;
		      }
		  }

		nslices += nfX;
		m_slices.append(nslices);
	      }
	    else
	      {
		QMessageBox::information(0, "",
	          QString("Expecting dimensions\nGot this %1").arg(line));
		return false;
	      }
	  }	
      }
    m_depth = m_slices[m_slices.count()-1];
    m_width = nfY0;
    m_height = nfZ0;
  }
  //------------------------------
  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  return true;
}
Exemple #14
0
bool
RawPlugin::setFile(QStringList files)
{
  m_fileName = files;

  int nX, nY, nZ;
  {
    // --- load various parameters from the raw file ---
    LoadRawDialog loadRawDialog(0,
				(char *)m_fileName[0].toAscii().data());

    if (!m_4dvol)
      {
	loadRawDialog.exec();    
	if (loadRawDialog.result() == QDialog::Rejected)
	  return false;
      }

    m_voxelType = loadRawDialog.voxelType();
    m_skipBytes = loadRawDialog.skipHeaderBytes();
    loadRawDialog.gridSize(nX, nY, nZ);
    m_depth = nX;
    m_width = nY;
    m_height = nZ;
  }

  //-----------------------------------
  QFile fin(m_fileName[0]);
  fin.open(QFile::ReadOnly);

  //-- recheck the information (for backward compatibility) ----
  if (m_skipBytes == 0)
    {
      int bpv = 1;
      if (m_voxelType == _UChar) bpv = 1;
      else if (m_voxelType == _Char) bpv = 1;
      else if (m_voxelType == _UShort) bpv = 2;
      else if (m_voxelType == _Short) bpv = 2;
      else if (m_voxelType == _Int) bpv = 4;
      else if (m_voxelType == _Float) bpv = 4;

      if (fin.size() == 13+nX*nY*nZ*bpv)
	m_skipBytes = 13;
      else if (fin.size() == 12+nX*nY*nZ*bpv)
	m_skipBytes = 12;
      else
	m_skipBytes = 0;
    }
  m_headerBytes = m_skipBytes;
  fin.close();
  //------------------------------

  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  if (m_4dvol) // do not perform further calculations.
    return true;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  return true;
}
Exemple #15
0
void getTOA_alg1(ptime_observation *obs,pheader *header,tmplStruct *tmpl,toaStruct *toa,FILE *fout_log)
{
  int i,j,k;
  int nbin = header->nbin;
  int nchan = header->nchan;
  int npol = header->npol;
  double chisq;
  double diffVals[nbin];
  double phiRot = 0;
  double step1 = 1.0/nbin/2.0;
  double step = step1;
  double baseline = 0;
  double scale = 1;
  double tmplEval;
  int chan = 0;
  int pol = 0;
  double phi,bestPhi;
  double phi0,phi1,bestChisq;
  int it;
  double chisqVals[nbin*2];
  double phiVals[nbin*2];
  int nChisqVals,ibest;
  int iterateAgain;
  int maxIterations = 10;
  int plotOutput=0;
  double error;
  double *fitX;
  double *fitY;
  double *fitE;
  int    *fitI,*fitJ,*fitK;
  int nfit = npol+1; // Up to 4 baselines per profile + 1 scaling factor
  double outputParams_v[nfit];
  double outputParams_e[nfit];
  double results_v[npol*nchan+nchan];
  double results_e[npol*nchan+nchan];
  int weight = 1;
  double bestParameters[npol*nchan+nchan];
  double chisqTot;

  // Covariance matrix
  double **cvm;
  cvm = (double **)malloc(sizeof(double*)*nfit);
  for (i=0;i<nfit;i++)
    cvm[i] = (double *)malloc(sizeof(double)*nfit);
  if (!(fitX = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitX\n");
    exit(1);
  }
  if (!(fitY = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitY\n");
    exit(1);
  }
  if (!(fitE = (double *)malloc(sizeof(double)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitE\n");
    exit(1);
  }
  if (!(fitI = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitI\n");
    exit(1);
  }
  if (!(fitJ = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitJ\n");
    exit(1);
  }
  if (!(fitK = (int *)malloc(sizeof(int)*npol*nchan*nbin))){
    printf("Unable to allocate enough memory for fitK\n");
    exit(1);
  }

  printf("Baseline sdev = %g, mean = %g\n",obs->chan[0].pol[0].sdev,obs->chan[0].pol[0].baselineVal);
  printf("On the next line\n");
  printf("npol = %d \n",npol);
  printf("Doing fit\n");
  it = 0;
  do {
    printf("Iteration %d\n",it+1);
    if (it == 0) {
      phi0 = -0.5;
      phi1 = 0.5;
    } else {
      phi0 = bestPhi - step;
      phi1 = bestPhi + step;
      step/=(double)10.0;
    }
    nChisqVals = 0;
    for (phiRot = phi0;phiRot < phi1;phiRot += step)
      {
	printf("Complete: %.1f percent\n",(phiRot-phi0)/(phi1-phi0)*100);
	//	phiRot = 0.0;
	// Least squares fit for baseline and amplitude at given phiRot
	//	printf("Doing fit\n");
	chisqTot=0;
	for (j=0;j<nchan;j++){
	  for (i=0;i<npol;i++){
	    for (k=0;k<nbin;k++){
	      //	printf("Setting %d %d %d %d %d\n",i,j,k,npol*nchan*nbin,i*(nchan*nbin)+j*nbin+k);
	      fitI[i*nbin+k] = i;
	      fitJ[i*nbin+k] = j;
	      fitK[i*nbin+k] = k;
	      fitX[i*nbin+k] = (double)k/(double)nbin; 
	      //	printf("This far\n");
	      //	printf("Searching for %g\n",obs->chan[j].pol[i].val[k]);
	      fitY[i*nbin+k] = obs->chan[j].pol[i].val[k];
	      fitE[i*nbin+k] = obs->chan[j].pol[i].sdev; 
	    }
	  }

	  TKleastSquares_svd(fitX,fitY,fitE,fitI,fitJ,fitK,npol*nbin,outputParams_v,outputParams_e,nfit,cvm, &chisq, fitFunc, tmpl, weight,phiRot);
	  chisqTot += chisq;
	  for (i=0;i<npol+1;i++)
	    {
	      results_v[(npol+1)*j + i] = outputParams_v[i];
	      results_e[(npol+1)*j + i] = outputParams_e[i];
	    }
	  //	  for (i=0;i<npol*nbin;i++)
	  //	    {
	  //	      printf("FitVals = %g %g %g\n",fitX[i],fitY[i],fitE[i]);
	  //	    }
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,0,phiRot)+outputParams_v[0]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,1,phiRot)+outputParams_v[1]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,2,phiRot)+outputParams_v[2]);
	  //	  for (i=0;i<nbin;i++)
	  //	    printf("Best %g %g\n",fitX[i],outputParams_v[4]*evaluateTemplateChannel(tmpl,fitX[i],j,3,phiRot)+outputParams_v[3]);

	  //	for (i=0;i<nfit;i++){
	  //	  printf("%d %g %g\n",i,outputParams_v[i],outputParams_e[i]);


	}

	//	printf("Done fit\n");
	//	baseline = outputParams_v[0];
	//	scale = outputParams_v[1];
	//	for (i=0;i<nfit;i++){
	//	  printf("%d %g %g\n",i,outputParams_v[i],outputParams_e[i]);
	//	}
	//	exit(1);	
	chisqVals[nChisqVals] = chisqTot;
	phiVals[nChisqVals] = phiRot;
	if (nChisqVals==0){
	  bestPhi = phiRot;
	  bestChisq = chisqTot;
	  for (i=0;i<nchan*npol+nchan;i++){
	    bestParameters[i] = outputParams_v[i];
	  }
	  ibest = nChisqVals;
	} else {
	  if (bestChisq > chisqTot){
	    bestChisq = chisqTot;
	    bestPhi = phiRot;
	    ibest = nChisqVals;
	    for (i=0;i<nchan*npol+nchan;i++){
	      bestParameters[i] = outputParams_v[i];
	    }
	  }
	}
	//	printf("Chisq = %g\n",chisq);
	//	exit(1);
	nChisqVals++;
      }
    printf("nvals =%d\n",nChisqVals);
    // Should check if we need to iterate again - do check based on how chisq is changing - i.e, must get a good measure of the chisq increasing by 1
    iterateAgain = 1;
    for (i=ibest+1;i<nChisqVals;i++)
      {
	if (chisqVals[i] < bestChisq + 1){
	  iterateAgain = 0;
	  break;
	}
      }
    it++;
  } while (iterateAgain == 1 && it < maxIterations);
  printf("ibest = %d, nChisqVals = %d, bestPhi = %g\n",ibest,nChisqVals,bestPhi);
  //  exit(1);
  {
    int foundStart = 0;
    double start,end;

    // Should think how to improve this method
    for (i=0;i<nChisqVals;i++)
      {
	fprintf(fout_log,"chisqVals %g %g\n",phiVals[i],chisqVals[i]);
	if (foundStart==0 && chisqVals[i] <= bestChisq + 1) 
	  {
	    foundStart = 1;
	    start = phiVals[i]; 
	  }
	else if (foundStart == 1 && chisqVals[i] >= bestChisq + 1)
	  {
	    end = phiVals[i];
	    break;
	  }
      }
    error = (end-start)/2.0;
  }
    
  printf("Number of iterations = %d\n",it);
  printf("bestPhi = %g\n",bestPhi);
  printf("bestChisq = %g\n",bestChisq);
  for (i=0;i<nchan*npol+nchan;i++){
    printf("Best parameter: %d %g\n",i,bestParameters[i]);
  }

  fprintf(fout_log,"Number of iterations = %d\n",it);
  fprintf(fout_log,"bestPhi = %g\n",bestPhi);
  fprintf(fout_log,"bestChisq = %g\n",bestChisq);
  for (i=0;i<nchan*npol+nchan;i++){
    fprintf(fout_log,"Best parameter: %d %g\n",i,bestParameters[i]);
  }

  if (plotOutput == 1){
    float fx[nbin*2],fy[nbin*2],ft[nbin*2],dy[nbin*2];
    float miny,maxy;
    float miny2,maxy2;

    for (i=0;i<nbin;i++)
      {
	fx[i] = (float)i/(float)nbin;
	fx[i+nbin] = fx[i]+1;
	//	tmplEval = bestScale*evaluateTemplateChannel(tmpl,fx[i],chan,pol,bestPhi)+bestBaseline;
	
	fy[i] = obs->chan[chan].pol[pol].val[i];
	fy[i+nbin] = fy[i];
	ft[i] = tmplEval;
	ft[i+nbin] = ft[i];
	dy[i] = fy[i]-ft[i];
	dy[i+nbin] = dy[i];
      }
    findMinMax(nbin,fy,&miny,&maxy);
    findMinMax(nbin,dy,&miny2,&maxy2);

    cpgbeg(0,"/xs",1,1);
    cpgsvp(0.1,0.9,0.5,0.9);
    cpgeras();
    cpgswin(0,2,miny,maxy);
    cpgbox("BCTS",0.0,0,"BCTSN",0.0,0);


    cpgbin(nbin*2,fx,fy,1);
    cpgsci(2); cpgline(nbin*2,fx,ft); cpgsci(1);

    cpgsvp(0.1,0.9,0.15,0.5);
    cpgswin(0,2,miny2,maxy2);
    cpgbox("BCTSN",0.0,0,"BCTSN",0.0,0);
    cpglab("Phase","prof-tmpl","");
    cpgbin(nbin*2,fx,dy,1);



    cpgend();
  }
  toa->dphi = bestPhi;
  toa->dphiErr = error;

  for (i=0;i<nfit;i++)
    free(cvm[i]);
  free(cvm);
  free(fitX); free(fitY); free(fitE); free(fitI); free(fitJ); free(fitK);
  return;
}
Exemple #16
0
int main(int argc, char *argv[]){

	//check validity of input arguments
	if(argc!=4){
		PRINTDEBUGMODE0("[ERROR] Please check number of arguments!\n");
		PRINTDEBUGMODE0("Application <gridsizes(m)> <searchRadius(m)> <PathtoTheInputFile.txt>\n");
		PRINTDEBUGMODE0("argv[1]:%s\n",argv[1]);
		PRINTDEBUGMODE0("argv[2]:%s\n",argv[2]);
		PRINTDEBUGMODE0("argv[3]:%s\n",argv[3]);
		exit(0);
	}

	long temp_gridsize = atol(argv[1]);

	double GRID_SIZE = (double) temp_gridsize ;
	if(GRID_SIZE<1) GRID_SIZE = 0.5; //hard code for parsing args < 1
	PRINTDEBUGMODE1("tempgrid:%lu\n",temp_gridsize);
	PRINTDEBUGMODE1("GRIDSIZE:%2.2f\n",GRID_SIZE);
	int searchRadius = strtol(argv[2],NULL,10);//for radius
	char *filename = argv[3];

	char path_p[50]="/nfs/code/mata/output/PredictionPerGrid";

	int rankId, numProcess;
	int bufflen = 512;
	char hostname[bufflen];
	int i, j, k, p, q;
	int flag=0;
	int dsize=0;
	int nrbins = 50;
	double *x=NULL, *y=NULL, *z=NULL, **ptopDist;
	//double maxD;
	int minX_inputData, minY_inputData, maxX_inputData, maxY_inputData, gridXrange, gridYrange;
	int numberofGrids_X, numberofGrids_Y;
	double maxDistance;
	double startTime, endTime;
	double  totalTime=0.0;

	//For variogram
	double sum_SqurZ[nrbins+2], distDelta[nrbins+2];


	char fileType[] = ".txt";
	FILE *fpdata=NULL;
	FILE *fPrediction=NULL;

	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rankId);
	MPI_Comm_size(MPI_COMM_WORLD, &numProcess);
	if(numProcess > NUM_MAX_PROCESS){
		printf("[ERROR] numProcess > NUM_MAX_PROCESS\n");
		exit(0);
	}

	startTime=MPI_Wtime();

	/*===================== Read Data =============================*/
	FILE *file = fopen ( filename, "r" );
	int inputsize=0;
	if ( file != NULL )
	{
		char line [ 128 ]; /* or other suitable maximum line size */
		while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
		{
			//fputs ( line, stdout ); /* write the line */
			inputsize++;
		}
		fclose ( file );
	}
	else
	{
		printf("[ERROR] Invalid input Path\n");
		perror ( filename ); /* why didn't the file open? */
	}

	dsize = inputsize;
	i=0; 

	fpdata = fopen(filename,"r");
	x = (double*)malloc(sizeof(double)*dsize);
	y = (double*)malloc(sizeof(double)*dsize);
	z = (double*)malloc(sizeof(double)*dsize);
	if(x==NULL | y==NULL | z==NULL){
		printf("[error malloc] X Y Z\n");
		exit(0);
	}

	fseek(fpdata,0,SEEK_SET);
	gethostname(hostname, bufflen);
	PRINTDEBUGMODE1( "Start process %d at %s\n", rankId, hostname );

	//Preprocessing steps is here
	while(!feof(fpdata)){
		fscanf(fpdata, "%lf %lf %lf", &x[i], &y[i], &z[i]);
		findMinMax(x[i], y[i]);
		//fprintf(ferr,"data: %lf %lf %lf\n", x[i], y[i], z[i]);
		i++;
	}
	minX_inputData = (int)floor(minX);	maxX_inputData = (int)ceil(maxX);	minY_inputData = (int)floor(minY);	maxY_inputData = (int)ceil(maxY);
	gridXrange = maxX_inputData-minX_inputData; gridYrange = maxY_inputData-minY_inputData;
	numberofGrids_X = gridXrange / GRID_SIZE; numberofGrids_Y = gridYrange / GRID_SIZE;
	int totalGrids = numberofGrids_X * numberofGrids_Y;
	int numGridPerNode = ceil(totalGrids/numProcess);

	if(rankId==0) {//choose the faster processor
		PRINTDEBUGMODE0("-----------------------------------------------\n");
		PRINTDEBUGMODE0(" Total processors (workers)  : %d\n", numProcess);
		PRINTDEBUGMODE0(" Number of Input LiDAR data  : %d\n",dsize);
		PRINTDEBUGMODE0("  min (%d,%d)\n  max (%d,%d)\n", minX_inputData, minY_inputData,maxX_inputData, maxY_inputData);
		PRINTDEBUGMODE0(" GRID_SIZE                   : %2.2f meter(s)\n",(double)GRID_SIZE);
		PRINTDEBUGMODE0(" SearchRadius                : %d meter(s)\n",searchRadius);
		PRINTDEBUGMODE0(" GRIDrange (X,Y)             : (%d,%d)\n", gridXrange, gridYrange);
		PRINTDEBUGMODE0(" numberofGrids (X,Y)         : (%d,%d)\n", numberofGrids_X, numberofGrids_Y);
		PRINTDEBUGMODE0(" Total available Grids       : %d\n",totalGrids);
		PRINTDEBUGMODE0(" NumGridsPerNode             : %d\n",numGridPerNode);
		PRINTDEBUGMODE0("-----------------------------------------------\n");
	}
	PRINTDEBUGMODE1("grid_index[%d]:%d\n",rankId,grid_index[rankId]);
	PRINTDEBUGMODE1("startGrid[%d]:(%2.2f,%2.2f)\n",rankId,startGrid_X[rankId],startGrid_Y[rankId]);

	// Prepare buffer to store nodes in a grid within searchRange
	buffNodes_inOneGrid = (PointerOfGrid**)malloc(sizeof(PointerOfGrid*)*(numberofGrids_X+1)); // assume that boundary X axis in also grid point
	if(buffNodes_inOneGrid== NULL){
		printf("[malloc error] cannot allocate %d buffNodes_inOneGrid_X\n", numberofGrids_X+1);
		exit(0);
	}

	PRINTDEBUGMODE1("malloc buffNodes_inOneGrid %d ...\n", rankId);
	for(i=0;i<=numberofGrids_X;i++){
		buffNodes_inOneGrid[i] = (PointerOfGrid*)malloc(sizeof(PointerOfGrid)*(numberofGrids_Y+1)); // assume that boundary Y axis in also grid point
		if(buffNodes_inOneGrid[i] == NULL){
			printf("[malloc error] cannot allocate %d buffNodes_inOneGrid_Y  \n", numberofGrids_Y+1);
			exit(0);
		}
		for(j=0;j<=numberofGrids_Y;j++){
			buffNodes_inOneGrid[i][j].next=NULL;
		}
		//FOR_DEBUG_PRINT("row_num:%d\n",i);FOR_DEBUG_PRINT("Load grid on memory\n");
	}

	//optimation per process
	int tempsize = dsize;
	while((tempsize%numProcess)!=0){
		tempsize--;
	}

	PRINTDEBUGMODE1("numProcess: %d\n",numProcess);
	PRINTDEBUGMODE1("tempsize: %d\n",tempsize);

	/* lets process data input one by one :
	 * hint :  One input point will be places to only one closest grid point
	 * */

	int numInputdataPerProcessor = tempsize/numProcess; //equally divide jobs from each worker
	PRINTDEBUGMODE1("numInputdataPerProcessor: %d\n",numInputdataPerProcessor);
	for(i=0;i<dsize;i++){ //148355
		//divide input data based on rankId on each processor(worker)
		int idx_datainput = i;//+rankId*numInputdataPerProcessor;
		if(idx_datainput<dsize){
			//find a closest grid point from an input data
			int lower_gridX = (int)floor(x[idx_datainput]);
			int upper_gridX = (int)ceil(x[idx_datainput]);
			int lower_gridY = (int)floor(y[idx_datainput]);
			int upper_gridY = (int)ceil(y[idx_datainput]);
			double closest_gridpointX;
			double closest_gridpointY;

			if(GRID_SIZE >= 1){
				int gridsize_var= GRID_SIZE;
				while((int)(lower_gridX%gridsize_var)!=0){
					lower_gridX--;
				}

				while((int)(upper_gridX%gridsize_var)!=0){
					upper_gridX++;
				}

				while((int)(lower_gridY%gridsize_var)!=0){
					lower_gridY--;
				}

				while((int)(upper_gridY%gridsize_var)!=0){
					upper_gridY++;
				}
			}

			if((sqrt(pow(x[idx_datainput]-lower_gridX,2)+pow(y[idx_datainput]-lower_gridY,2)))<
					(sqrt(pow(x[idx_datainput]-upper_gridX,2)+pow(y[idx_datainput]-upper_gridY,2))) ){
				closest_gridpointX = lower_gridX;
				closest_gridpointY = lower_gridY;
			}else{
				closest_gridpointX = upper_gridX;
				closest_gridpointY = upper_gridY;
			}

			//TODO iterate this closest grid point within a searchRange
			PRINTDEBUGMODE1("closest_gridpointX:%lf\n",closest_gridpointX);
			PRINTDEBUGMODE1("closest_gridpointY:%lf\n",closest_gridpointY);

			//ensure that still inside boundary area
			if((closest_gridpointX>=minX_inputData)&&(closest_gridpointY>=minY_inputData)&&(closest_gridpointX<=maxX_inputData)&&(closest_gridpointY<=maxY_inputData)){

				if(((closest_gridpointX-minX_inputData)/GRID_SIZE)>= numberofGrids_X){
					PRINTDEBUGMODE1("HOREWWWW X\n");
				}
				if(((closest_gridpointY-minY_inputData)/GRID_SIZE)>= numberofGrids_Y){
					PRINTDEBUGMODE1("HOREWWWW Y\n");
				}

				if((abs(closest_gridpointX-x[idx_datainput])<searchRadius) && (abs(closest_gridpointY-y[idx_datainput])<searchRadius)){
					int idx_x = (int)(closest_gridpointX-minX_inputData)/GRID_SIZE;
					int idx_y = (int)(closest_gridpointY-minY_inputData)/GRID_SIZE;
					PRINTDEBUGMODE1("numberofGrids_X:%d; numberofGrids_Y:%d\n", numberofGrids_X, numberofGrids_Y);

					if(buffNodes_inOneGrid[idx_x]!=NULL){

						cur = buffNodes_inOneGrid[idx_x][idx_y].next;

						if(cur==NULL){
							PRINTDEBUGMODE1("cur next NULL\n");
							new_list = (Info_Grid*)malloc(sizeof(Info_Grid));
							new_list->x = x[idx_datainput];
							new_list->y = y[idx_datainput];
							new_list->z = z[idx_datainput];
							new_list->next=NULL;

							buffNodes_inOneGrid[idx_x][idx_y].next = new_list;
						} else {
							PRINTDEBUGMODE1("cur next NOT NULL\n");
							while(cur->next!=NULL) {
								cur = cur->next;
							}
							new_list = (Info_Grid*)malloc(sizeof(Info_Grid));
							new_list->x = x[idx_datainput];
							new_list->y = y[idx_datainput];
							new_list->z = z[idx_datainput];

							new_list->next=NULL;
							cur->next = new_list;
						}
					}else{
						//there must be some bug if this happened --> ussually malloc failed
						PRINTDEBUGMODE0("[ERROR] ANOTHER BUG\n");
						PRINTDEBUGMODE0("X:%d; Y:%d\n",idx_x,idx_y);
						PRINTDEBUGMODE0("numberofGrids_X:%d; numberofGrids_Y:%d\n", numberofGrids_X, numberofGrids_Y);
					}
				}


			}
		}
		else{
			PRINTDEBUGMODE0("idx_datainput:%d\n",idx_datainput);
		}
	}

	free(x);
	free(y);
	free(z);

	/**
	 * Gridding, Semi-Variogram, Prediction Process is here
	 */
	strcat(path_p,itoa(rankId,10));
	strcat(path_p,fileType);
	fPrediction = fopen(path_p,"w");

	PRINTDEBUGMODE1("Start Gridding Process ... \n");
	// Divide number of grids with the available process/workers
	for(p=0;p< numGridPerNode;p++){
		int idx_grid =p+rankId*numGridPerNode;
		if(idx_grid<totalGrids){
			int idx_x = idx_grid%numberofGrids_X;
			int idx_y = (int) floor(idx_grid/numberofGrids_X);
			int temp_idx_x = idx_x;
			int temp_idx_y = idx_y;

			//iterate based on search range & collect in a linked list
			int points_counter = 0;
			minX=0.0, minY=0.0, maxX=0.0, maxY=0.0;
			if(GRID_SIZE<searchRadius){
				//TODO FIX this bug
				int max_loop = (int)ceil(searchRadius/GRID_SIZE);
				idx_x = idx_x-max_loop;
				idx_y = idx_y-max_loop;
				for(i=0;i<2*max_loop;i++){
					for(j=0;j<2*max_loop;j++){
						if((idx_x+i)>=0 && ((idx_x+i) < numberofGrids_X) && (idx_y+j)>=0 && (idx_y+j) < numberofGrids_Y) { //while still inside boundary of grids
							CalDistPointfromGrid(idx_x+i,idx_y+j, &points_counter);
						}
					}
				}

			}else{
					CalDistPointfromGrid(idx_x,idx_y, &points_counter);
			}

			PRINTDEBUGMODE1("point_counter :%d\n",points_counter);

			//calculate variogram
			maxDistance = sqrt(pow(maxX-minX,2)+pow(maxY-minY,2));
			maxDistance = maxDistance/2;

			points_counter = points_counter+1;
			ptopDist = (double**)malloc(sizeof(double*)*points_counter);
			for(k=0;k<points_counter;k++) {
				ptopDist[k] = (double*)malloc(sizeof(double)*points_counter);
			}
			//initialize with 0 value
			for(k=0;k<points_counter;k++) {
				for(q=0;q<points_counter;q++) {
					ptopDist[k][q] = 0.0;
				}
			}
			//calculate semivariogram
			FindSemivar(Head_distfromGrid, nrbins, sum_SqurZ, maxDistance, distDelta, ptopDist);

			double range, sill;
			//Fitting process with model
			FitSemivariogram(sum_SqurZ, distDelta, nrbins, &range, &sill);

			//Prediction
			double coord_gridX = minX_inputData + temp_idx_x*GRID_SIZE;
			double coord_gridY = minY_inputData + temp_idx_y*GRID_SIZE;
			Prediction(Head_distfromGrid, points_counter, range, sill, rankId, ptopDist, coord_gridX, coord_gridY, fPrediction);

			//free memory
			for(k=0;k<points_counter;k++) {
				free(ptopDist[k]);
			}
			free(ptopDist);

			Cur_DistfromGrid = Head_distfromGrid;
			while(Cur_DistfromGrid!=NULL) {
				ForFree_DistfromGrid = Cur_DistfromGrid;
				Cur_DistfromGrid = Cur_DistfromGrid -> next;
				free(ForFree_DistfromGrid);
			}
			Head_distfromGrid=NULL;
			Tail_DistfromGrid=NULL;

		}
	}


	endTime = MPI_Wtime();
	totalTime = endTime-startTime;
	MPI_Finalize();

	PRINTDEBUGMODE0( "Finished process %d at %s in %lf seconds\n", rankId, hostname, totalTime );

	int temp_numProc=0;
	for(i=0;i<numProcess;i++){
		temp_numProc = temp_numProc+i;
	}

	flag = flag + rankId;
	if(flag == temp_numProc){
		char path_output[]="cat ../../mata/output/* > ";
		strcat(path_output,"result.txt");
		system(path_output);
	}
	return 0;

}
Exemple #17
0
bool LinkedNode::triangleIntersect(Triangle p_tri)
{
	DirectX::XMFLOAT3 boxCenter	  = div(add(m_max, m_min), 2);
	DirectX::XMFLOAT3 boxHalfSize = div(sub(m_max, m_min), 2);
	
	//Move everything so that boxCenter is in (0, 0, 0)
	DirectX::XMFLOAT3 vertex0 = sub(p_tri.vertices[0].m_position, boxCenter);
	DirectX::XMFLOAT3 vertex1 = sub(p_tri.vertices[1].m_position, boxCenter);
	DirectX::XMFLOAT3 vertex2 = sub(p_tri.vertices[2].m_position, boxCenter);
	
	//Compute triangle edges
	DirectX::XMFLOAT3 edge0 = sub(vertex1, vertex0);
	DirectX::XMFLOAT3 edge1 = sub(vertex2, vertex1);
	DirectX::XMFLOAT3 edge2 = sub(vertex0, vertex2);

	float fex = fabsf(edge0.x);
	float fey = fabsf(edge0.y);
	float fez = fabsf(edge0.z);
	if(axisTestX(edge0.z, edge0.y, fez, fey, vertex0, vertex2, boxHalfSize) == false)
		return false;
	if(axisTestY(edge0.z, edge0.x, fez, fex, vertex0, vertex2, boxHalfSize) == false)
		return false;
	if(axisTestZ(edge0.y, edge0.x, fey, fex, vertex1, vertex2, boxHalfSize) == false)
		return false;

	fex = fabsf(edge1.x);
	fey = fabsf(edge1.y);
	fez = fabsf(edge1.z);
	if(axisTestX(edge1.z, edge1.y, fez, fey, vertex0, vertex2, boxHalfSize) == false)
		return false;
	if(axisTestY(edge1.z, edge1.x, fez, fex, vertex0, vertex2, boxHalfSize) == false)
		return false;
	if(axisTestZ(edge1.y, edge1.x, fey, fex, vertex0, vertex1, boxHalfSize) == false)
		return false;

	fex = fabsf(edge2.x);
	fey = fabsf(edge2.y);
	fez = fabsf(edge2.z);
	if(axisTestX(edge2.z, edge2.y, fez, fey, vertex0, vertex1, boxHalfSize) == false)
		return false;
	if(axisTestY(edge2.z, edge2.x, fez, fex, vertex0, vertex1, boxHalfSize) == false)
		return false;
	if(axisTestZ(edge2.y, edge2.x, fey, fex, vertex1, vertex2, boxHalfSize) == false)
		return false;

	float min, max;
	findMinMax(vertex0.x, vertex1.x, vertex2.x, min, max);
	if(min > boxHalfSize.x || max < -boxHalfSize.x)
		return false;

	findMinMax(vertex0.y, vertex1.y, vertex2.y, min, max);
	if(min > boxHalfSize.y || max < -boxHalfSize.y)
		return false;

	findMinMax(vertex0.z, vertex1.z, vertex2.z, min, max);
	if(min > boxHalfSize.z || max < -boxHalfSize.z)
		return false;

	DirectX::XMFLOAT3 normal = cross(edge0, edge1);
	if(planeBoxOverlap(normal, vertex0, boxHalfSize) == false)
		return false;

	return true;
}
Exemple #18
0
	AABB::AABB(Vector location, std::vector<Vector> vertices)
	{
		position = location;
		findMinMax(vertices);
	}
Exemple #19
0
void ImageWidget::update(Cairo::RefPtr<Cairo::Context> cairo, unsigned width, unsigned height)
{
	Image2DCPtr image = _image;
	Mask2DCPtr mask = GetActiveMask(), originalMask = _originalMask, alternativeMask = _alternativeMask;
	
	unsigned int
		startX = (unsigned int) round(_startHorizontal * image->Width()),
		startY = (unsigned int) round(_startVertical * image->Height()),
		endX = (unsigned int) round(_endHorizontal * image->Width()),
		endY = (unsigned int) round(_endVertical * image->Height());
	size_t
		imageWidth = endX - startX,
		imageHeight = endY - startY;
		
	if(imageWidth > 30000)
	{
		int shrinkFactor = (imageWidth + 29999) / 30000;
		image = image->ShrinkHorizontally(shrinkFactor);
		mask = mask->ShrinkHorizontally(shrinkFactor);
		if(originalMask != 0)
			originalMask = originalMask->ShrinkHorizontally(shrinkFactor);
		if(alternativeMask != 0)
			alternativeMask = alternativeMask->ShrinkHorizontally(shrinkFactor);
		startX /= shrinkFactor;
		endX /= shrinkFactor;
		imageWidth = endX - startX;
	}

	num_t min, max;
	findMinMax(image, mask, min, max);
	
	// If these are not yet created, they are 0, so ok to delete.
	delete _horiScale;
	delete _vertScale;
	delete _colorScale;
	delete _plotTitle;
		
	if(_showXYAxes)
	{
		_vertScale = new VerticalPlotScale();
		_vertScale->SetDrawWithDescription(_showYAxisDescription);
		_horiScale = new HorizontalPlotScale();
		_horiScale->SetDrawWithDescription(_showXAxisDescription);
	} else {
		_vertScale = 0;
		_horiScale = 0;
	}
	if(_showColorScale)
	{
		_colorScale = new ColorScale();
		_colorScale->SetDrawWithDescription(_showZAxisDescription);
	} else {
		_colorScale = 0;
	}
	if(_showXYAxes)
	{
		if(_metaData != 0 && _metaData->HasBand()) {
			_vertScale->InitializeNumericTicks(_metaData->Band().channels[startY].frequencyHz / 1e6, _metaData->Band().channels[endY-1].frequencyHz / 1e6);
			_vertScale->SetUnitsCaption("Frequency (MHz)");
		} else {
			_vertScale->InitializeNumericTicks(-0.5 + startY, 0.5 + endY - 1.0);
		}
		if(_metaData != 0 && _metaData->HasObservationTimes())
		{
			_horiScale->InitializeTimeTicks(_metaData->ObservationTimes()[startX], _metaData->ObservationTimes()[endX-1]);
			_horiScale->SetUnitsCaption("Time");
		} else {
			_horiScale->InitializeNumericTicks(-0.5 + startX, 0.5 + endX - 1.0);
		}
		if(_manualXAxisDescription)
			_horiScale->SetUnitsCaption(_xAxisDescription);
		if(_manualYAxisDescription)
			_vertScale->SetUnitsCaption(_yAxisDescription);
	}
	if(_metaData != 0) {
		if(_showColorScale && _metaData->ValueDescription()!="")
		{
			if(_metaData->ValueUnits()!="")
				_colorScale->SetUnitsCaption(_metaData->ValueDescription() + " (" + _metaData->ValueUnits() + ")");
			else
				_colorScale->SetUnitsCaption(_metaData->ValueDescription());
		}
	}
	if(_showColorScale)
	{
		if(_scaleOption == LogScale)
			_colorScale->InitializeLogarithmicTicks(min, max);
		else
			_colorScale->InitializeNumericTicks(min, max);
		if(_manualZAxisDescription)
			_colorScale->SetUnitsCaption(_zAxisDescription);
	}

	if(_showTitle && !actualTitleText().empty())
	{
		_plotTitle = new Title();
		_plotTitle->SetText(actualTitleText());
		_plotTitle->SetPlotDimensions(width, height, 0.0);
		_topBorderSize = _plotTitle->GetHeight(cairo);
	} else {
		_plotTitle = 0;
		_topBorderSize = 10.0;
	}
	// The scale dimensions are depending on each other. However, since the height of the horizontal scale is practically
	// not dependent on other dimensions, we give the horizontal scale temporary width/height, so that we can calculate its height:
	if(_showXYAxes)
	{
		_horiScale->SetPlotDimensions(width, height, 0.0, 0.0);
		_bottomBorderSize = _horiScale->GetHeight(cairo);
		_rightBorderSize = _horiScale->GetRightMargin(cairo);
	
		_vertScale->SetPlotDimensions(width - _rightBorderSize + 5.0, height - _topBorderSize - _bottomBorderSize, _topBorderSize);
		_leftBorderSize = _vertScale->GetWidth(cairo);
	} else {
		_bottomBorderSize = 0.0;
		_rightBorderSize = 0.0;
		_leftBorderSize = 0.0;
	}
	if(_showColorScale)
	{
		_colorScale->SetPlotDimensions(width - _rightBorderSize, height - _topBorderSize, _topBorderSize);
		_rightBorderSize += _colorScale->GetWidth(cairo) + 5.0;
	}
	if(_showXYAxes)
	{
		_horiScale->SetPlotDimensions(width - _rightBorderSize + 5.0, height -_topBorderSize - _bottomBorderSize, _topBorderSize, 	_vertScale->GetWidth(cairo));
	}

	class ColorMap *colorMap = createColorMap();
	
	const double
		minLog10 = min>0.0 ? log10(min) : 0.0,
		maxLog10 = max>0.0 ? log10(max) : 0.0;
	if(_showColorScale)
	{
		for(unsigned x=0;x<256;++x)
		{
			num_t colorVal = (2.0 / 256.0) * x - 1.0;
			num_t imageVal;
			if(_scaleOption == LogScale)
				imageVal = exp10((x / 256.0) * (log10(max) - minLog10) + minLog10);
			else 
				imageVal = (max-min) * x / 256.0 + min;
			double
				r = colorMap->ValueToColorR(colorVal),
				g = colorMap->ValueToColorG(colorVal),
				b = colorMap->ValueToColorB(colorVal);
			_colorScale->SetColorValue(imageVal, r/255.0, g/255.0, b/255.0);
		}
	}
	
	_imageSurface.clear();
	_imageSurface =
		Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32, imageWidth, imageHeight);

	_imageSurface->flush();
	unsigned char *data = _imageSurface->get_data();
	size_t rowStride = _imageSurface->get_stride();

	Mask2DPtr highlightMask;
	if(_highlighting)
	{
		highlightMask = Mask2D::CreateSetMaskPtr<false>(image->Width(), image->Height());
		_highlightConfig->Execute(image, highlightMask, true, 10.0);
	}
	const bool
		originalActive = _showOriginalMask && originalMask != 0,
		altActive = _showAlternativeMask && alternativeMask != 0;
	for(unsigned long y=startY;y<endY;++y) {
		guint8* rowpointer = data + rowStride * (endY - y - 1);
		for(unsigned long x=startX;x<endX;++x) {
			int xa = (x-startX) * 4;
			unsigned char r,g,b,a;
			if(_highlighting && highlightMask->Value(x, y) != 0) {
				r = 255; g = 0; b = 0; a = 255;
			} else if(originalActive && originalMask->Value(x, y)) {
				r = 255; g = 0; b = 255; a = 255;
			} else if(altActive && alternativeMask->Value(x, y)) {
				r = 255; g = 255; b = 0; a = 255;
			} else {
				num_t val = image->Value(x, y);
				if(val > max) val = max;
				else if(val < min) val = min;

				if(_scaleOption == LogScale)
				{
					if(image->Value(x, y) <= 0.0)
						val = -1.0;
					else
						val = (log10(image->Value(x, y)) - minLog10) * 2.0 / (maxLog10 - minLog10) - 1.0;
				}
				else
					val = (image->Value(x, y) - min) * 2.0 / (max - min) - 1.0;
				if(val < -1.0) val = -1.0;
				else if(val > 1.0) val = 1.0;
				r = colorMap->ValueToColorR(val);
				g = colorMap->ValueToColorG(val);
				b = colorMap->ValueToColorB(val);
				a = colorMap->ValueToColorA(val);
			}
			rowpointer[xa]=b;
			rowpointer[xa+1]=g;
			rowpointer[xa+2]=r;
			rowpointer[xa+3]=a;
		}
	}
	delete colorMap;

	if(_segmentedImage != 0)
	{
		for(unsigned long y=startY;y<endY;++y) {
			guint8* rowpointer = data + rowStride * (y - startY);
			for(unsigned long x=startX;x<endX;++x) {
				if(_segmentedImage->Value(x,y) != 0)
				{
					int xa = (x-startX) * 4;
					rowpointer[xa]=IntMap::R(_segmentedImage->Value(x,y));
					rowpointer[xa+1]=IntMap::G(_segmentedImage->Value(x,y));
					rowpointer[xa+2]=IntMap::B(_segmentedImage->Value(x,y));
					rowpointer[xa+3]=IntMap::A(_segmentedImage->Value(x,y));
				}
			}
		}
	}
	_imageSurface->mark_dirty();

	while(_imageSurface->get_width() > (int) width || _imageSurface->get_height() > (int) height)
	{
		unsigned
			newWidth = _imageSurface->get_width(),
			newHeight = _imageSurface->get_height();
		if(newWidth > width)
			newWidth = width;
		if(newHeight > height)
			newHeight = height;
		downsampleImageBuffer(newWidth, newHeight);
	}

	_isInitialized = true;
	_initializedWidth = width;
	_initializedHeight = height;
	redrawWithoutChanges(cairo, width, height);
} 
Exemple #20
0
/**
* copied from hpaStar.cpp
 *
 * smoothen the path by replacing parts of the path by 
 * straight lines.
 */
path* craStar::smoothPath(graphAbstraction *m,path* p)
{
	findMinMax(p);
	
	if (verbose) std::cout<<"Smoothing the path\n";
	
	// put the path nodes in a vector
	lookup.clear();
//	path* pcopy = p->clone();
//	path* ptr = pcopy;
	int tempLabel=0; 
	
	for (path *tmp = p; tmp != 0; tmp = tmp->next)
	{
		lookup.push_back(tmp->n);
		// set key = index in lookup
		tmp->n->setLabelL(kTemporaryLabel,tempLabel);
		tempLabel++;
	}
	unsigned int n = 0; 
	path* smooth = 0;
	
	while(true)
	{
		
		//Skip blanks
		while(lookup[n]==0 && n<lookup.size()-1)
			n++;
		
		if (n>=lookup.size()-1)
		{
			
			break;
		}
		
		unsigned int last = lookup[n]->getLabelL(kTemporaryLabel);
		
		if (last!=n)
		{
			
			for (unsigned int i=n; i<last && i<lookup.size(); i++)
			{
				
				lookup[i]=0;
			}
			n = last;
			continue;
		}
		
		int dir;
		for (dir = NORTH; dir <= NW; dir++)
		{
			
			// get a shortcut if it exists
			path* pathToNode = nextPathNode(m,lookup[n],dir);
			
			// paste the shortcut into our current path
			if (pathToNode)
			{
				int lastNode = pathToNode->tail()->n->getLabelL(kTemporaryLabel);
				int curr = pathToNode->n->getLabelL(kTemporaryLabel);
				
				if (lastNode > curr && !nextInLookup(lastNode, curr,lookup))
				{
					// make sure it's not the next one 
					
					unsigned int index = n;
					path* pathCopy = pathToNode;
						//path* backup = pathCopy;
					unsigned int end = pathToNode->tail()->n->getLabelL(kTemporaryLabel);
						
					while(pathCopy->next)
					{
						
						//make sure we're not overwriting anything
						assert(index <= end);
						
						lookup[index]=pathCopy->n;
						pathCopy->n->setLabelL(kTemporaryLabel,index);
						pathCopy = pathCopy->next;
						index++;
					}
					assert(index <= end);
					
					lookup[index]=pathCopy->n;
					pathCopy->n->setLabelL(kTemporaryLabel,index);			
					
					index++;	
					
					while(index<=end)
					{
						
						lookup[index]= 0;
						index++;
					}
					
					if (smType==END)
					{
						
						n = end;
					}
					else if (smType==TWO_BACK)
						n = backTwoNodes(end,lookup);
					else		
						n++; 
					
					delete pathToNode; pathToNode = 0;
					//delete backup;
					break;
					
				}
				else if (dir==NW)
				{
					
					n++;
				}
				
				delete pathToNode;
			} 
			else if (dir==NW)
			{
				
				n++;
			}
		} //end for every direction
		
		
	}
	
	//Create smoothed path from lookup table
	for (unsigned int i=0; i<lookup.size(); i++)
	{
		
		if (lookup[i]!=0)
		{
			
			if (!smooth)
				smooth = new path(lookup[i],0);
			else
				smooth->tail()->next = new path(lookup[i],0);
		}
	}
	return smooth;
}
Exemple #21
0
static void print_debug_maps_ascii_art(RDebug *dbg, RList *maps, ut64 addr, int colors) {
	ut64 mul; // The amount of address space a single console column will represent in bar graph
	ut64 min = -1, max = 0;
	int width = r_cons_get_size (NULL) - 90;
	RListIter *iter;
	RDebugMap *map;
	if (width < 1) {
		width = 30;
	}
	r_list_sort (maps, cmp);
	mul = findMinMax (maps, &min, &max, 0, width);
	ut64 last = min;
	if (min != -1 && mul != 0) {
		const char *color_prefix = ""; // Color escape code prefixed to string (address coloring)
		const char *color_suffix = ""; // Color escape code appended to end of string
		const char *fmtstr;
		char size_buf[56]; // Holds the human formatted size string [124K]
		int skip = 0; // Number of maps to skip when re-calculating the minmax
		r_list_foreach (maps, iter, map) {
			r_num_units (size_buf, map->size); // Convert map size to human readable string
			if (colors) {
				color_suffix = Color_RESET;
				if (map->perm & 2) { // Writable maps are red
					color_prefix = Color_RED;
				} else if (map->perm & 1) { // Executable maps are green
					color_prefix = Color_GREEN;
				} else {
					color_prefix = "";
					color_suffix = "";
				}
			} else {
				color_prefix = "";
				color_suffix = "";
			}
			if ((map->addr - last) > UT32_MAX) { // TODO: Comment what this is for
				mul = findMinMax (maps, &min, &max, skip, width); //  Recalculate minmax
			}
			skip++;
			fmtstr = dbg->bits & R_SYS_BITS_64 ? // Prefix formatting string (before bar)
				"map %4.8s %c %s0x%016"PFMT64x"%s |" :
				"map %4.8s %c %s0x%08"PFMT64x"%s |";
			dbg->cb_printf (fmtstr, size_buf,
				(addr >= map->addr && \
				addr < map->addr_end) ? '*' : '-',
				color_prefix, map->addr, color_suffix); // * indicates map is within our current seeked offset
			int col;
			for (col = 0; col < width; col++) { // Iterate over the available width/columns for bar graph
				ut64 pos = min + (col * mul); // Current address space to check
				ut64 npos = min + ((col + 1) * mul); // Next address space to check
				if (map->addr < npos && map->addr_end > pos) {
					dbg->cb_printf ("#"); // TODO: Comment what a # represents
				} else {
					dbg->cb_printf ("-");
				}
			}
			fmtstr = dbg->bits & R_SYS_BITS_64 ? // Suffix formatting string (after bar)
				"| %s0x%016"PFMT64x"%s %s %s\n" :
				"| %s0x%08"PFMT64x"%s %s %s\n";
			dbg->cb_printf (fmtstr, color_prefix, map->addr_end, color_suffix,
				r_str_rwx_i (map->perm), map->name);
			last = map->addr;
		}
	}
  void callback(const sensor_msgs::Image::ConstPtr imageColor, const sensor_msgs::Image::ConstPtr imageIr, const sensor_msgs::Image::ConstPtr imageDepth)
  {
    std::vector<cv::Point2f> pointsColor, pointsIr;
    cv::Mat color, ir, irGrey, irScaled, depth;
    bool foundColor = false;
    bool foundIr = false;

    if(mode == COLOR || mode == SYNC)
    {
      readImage(imageColor, color);
    }
    if(mode == IR || mode == SYNC)
    {
      readImage(imageIr, ir);
      readImage(imageDepth, depth);
      cv::resize(ir, irScaled, cv::Size(), 2.0, 2.0, cv::INTER_CUBIC);

      convertIr(irScaled, irGrey);
    }

    if(circleBoard)
    {
      switch(mode)
      {
      case COLOR:
        foundColor = cv::findCirclesGrid(color, boardDims, pointsColor, circleFlags);
        break;
      case IR:
        foundIr = cv::findCirclesGrid(irGrey, boardDims, pointsIr, circleFlags);
        break;
      case SYNC:
        foundColor = cv::findCirclesGrid(color, boardDims, pointsColor, circleFlags);
        foundIr = cv::findCirclesGrid(irGrey, boardDims, pointsIr, circleFlags);
        break;
      }
    }
    else
    {
      const cv::TermCriteria termCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::COUNT, 100, DBL_EPSILON);
      switch(mode)
      {
      case COLOR:
        foundColor = cv::findChessboardCorners(color, boardDims, pointsColor, cv::CALIB_CB_FAST_CHECK);
        break;
      case IR:
        foundIr = cv::findChessboardCorners(irGrey, boardDims, pointsIr, cv::CALIB_CB_ADAPTIVE_THRESH);
        break;
      case SYNC:
        foundColor = cv::findChessboardCorners(color, boardDims, pointsColor, cv::CALIB_CB_FAST_CHECK);
        foundIr = cv::findChessboardCorners(irGrey, boardDims, pointsIr, cv::CALIB_CB_ADAPTIVE_THRESH);
        break;
      }
      if(foundColor)
      {
        cv::cornerSubPix(color, pointsColor, cv::Size(11, 11), cv::Size(-1, -1), termCriteria);
      }
      if(foundIr)
      {
        cv::cornerSubPix(irGrey, pointsIr, cv::Size(11, 11), cv::Size(-1, -1), termCriteria);
      }
    }

    if(foundIr)
    {
      // Update min and max ir value based on checkerboard values
      findMinMax(irScaled, pointsIr);
    }

    lock.lock();
    this->color = color;
    this->ir = ir;
    this->irGrey = irGrey;
    this->depth = depth;
    this->foundColor = foundColor;
    this->foundIr = foundIr;
    this->pointsColor = pointsColor;
    this->pointsIr = pointsIr;
    update = true;
    lock.unlock();
  }
void IntensityGenerator::createScenes()
{
    m_odd = new Scene(m_doc);
    m_odd->setName("Intensity - Odd");

    m_even = new Scene(m_doc);
    m_even->setName("Intensity - Even");

    m_full = new Scene(m_doc);
    m_full->setName("Intensity - Full");

    m_zero = new Scene(m_doc);
    m_zero->setName("Intensity - Zero");

    // Create sequence & random scene lists
    int i = 0;
    QListIterator <Fixture*> it(m_fixtures);
    while (it.hasNext() == true)
    {
        Fixture* fxi(it.next());
        Q_ASSERT(fxi != NULL);

        Scene* sq = new Scene(m_doc);
        sq->setName(QString("Intensity - ") + fxi->name());
        m_sequence << sq;

        sq = new Scene(m_doc);
        sq->setName(QString("Intensity - Random - %1").arg(++i));
        m_random << sq;
    }

    // Go thru all fixtures
    for (int i = 0; i < m_fixtures.size(); i++)
    {
        Fixture* fxi = m_fixtures[i];
        Q_ASSERT(fxi != NULL);

        // Find such channels from the fixture that belong to the
        // given channel group.
        QList <quint32> channels = findChannels(fxi, QLCChannel::Intensity);

        // Insert values to member scenes for each found channel
        for (int j = 0; j < channels.size(); j++)
        {
            quint32 ch = channels.at(j);
            const QLCChannel* channel = fxi->channel(ch);
            Q_ASSERT(channel != NULL);

            uchar min = 0;
            uchar max = UCHAR_MAX;
            int modulo = i;

            // Find the minimum and maximum intensity values for
            // the current channel
            findMinMax(channel, &min, &max);

            // Set all intensity channels to max in the $full scene
            m_full->setValue(fxi->id(), ch, max);

            // Set all intensity channels to min in the $zero scene
            m_zero->setValue(fxi->id(), ch, min);

            // Create even & odd values
            if (fxi->isDimmer() == false)
                modulo = i; // For each intelligent fixture
            else
                modulo = j; // For each dimmer channel

            if ((modulo % 2) == 0)
            {
                m_even->setValue(fxi->id(), ch, max);
                m_odd->setValue(fxi->id(), ch, min);
            }
            else
            {
                m_even->setValue(fxi->id(), ch, min);
                m_odd->setValue(fxi->id(), ch, max);
            }

            // Create sequence and random values
            for (int s = 0; s < m_sequence.size(); s++)
            {
                if (s == i)
                    m_sequence[s]->setValue(fxi->id(), ch, max);
                else
                    m_sequence[s]->setValue(fxi->id(), ch, min);

                if ((rand() % 2) == 0)
                    m_random[s]->setValue(fxi->id(), ch, max);
                else
                    m_random[s]->setValue(fxi->id(), ch, min);
            }
        }
    }
}
std::vector<PotentialStar*> StarFinder::findStars(
    std::vector<PotentialStar*>& allobj)
{
    dbg<<"starting FindStars, allobj.size() = "<<allobj.size()<<std::endl;

    // sort allobj by magnitude
    std::sort(allobj.begin(),allobj.end(),std::mem_fun(
            &PotentialStar::isBrighterThan));
    dbg<<"sorted allobj\n";


    // First stage:
    // Split area into sections
    // For each secion find as many stars as possible.
    // Use these stars to fit the variation in rsq across the image.

    // Make bounds of whole region called total_bounds
    Bounds total_bounds;
    const int nobj = allobj.size();
    for(int k=0;k<nobj;++k) total_bounds += allobj[k]->getPos();
    dbg<<"totalbounds = \n"<<total_bounds<<std::endl;

    // boundsar is the 3x3 (ndivx x ndivy) array of quadrant bounds
    // call it qbounds even though it won't be quadrants unless 2x2
    std::vector<Bounds> qbounds = total_bounds.divide(_ndivx,_ndivy);
    xdbg<<"made qbounds\n";

    // probstars will be our first pass list of probable stars
    std::vector<PotentialStar*> probstars;

    // For each section, find the stars and add to probstars
    const int nsection = qbounds.size();

    double frac_nobj=0;
    for (int i=0; i<nobj; ++i) {
        if(isOkSg(allobj[i]->getSg()) && 
           isOkSgMag(allobj[i]->getMag())) frac_nobj++;
    }
    dbg<<"  Found "<<frac_nobj<<" with star-galaxy cuts  "<<std::endl;
    frac_nobj/=nobj;

    bool ignore_sg_cut=false;
    if( frac_nobj < _min_sg_frac ) {
        dbg<<"  Fraction of objects in star-galaxy range too small: "<<
            frac_nobj<<std::endl;
        dbg<<"  Ignoring star-galaxy cut selection"<<std::endl;
        ignore_sg_cut=true;
    }


    if(!ignore_sg_cut) {   
        for(int k=0;k<nobj;++k) {
            if (isOkSg(allobj[k]->getSg()) && isOkSgMag(allobj[k]->getMag())) {
                probstars.insert(probstars.end(),allobj[k]);
            }
        }

        // dummy fit to pass to rejection function
        Legendre2D fit(total_bounds);

        rejectOutliersIter(probstars,_reject1,0.1,fit,true,1e-4,8);
        dbg<<"rejected outliers, now have "<<probstars.size()<<" stars\n";
        std::sort(probstars.begin(),probstars.end(),
            std::mem_fun(&PotentialStar::isBrighterThan));

        dbg<<"Current stars mag/size:"<<std::endl;
        for(size_t k=0;k<probstars.size();++k) {
            dbg<<probstars[k]->getMag()<<" "<<probstars[k]->getSize()<<std::endl;
        }
    } else {
        for(int i=0;i<nsection;++i) {
            dbg<<"i = "<<i<<": bounds = "<<qbounds[i]<<std::endl;

            // someobj are the objects in this section
            // Note that someobj is automatically sorted by magnitude, since
            // allobj was sorted.
            std::vector<PotentialStar*> someobj;
            for(int k=0;k<nobj;++k) {
                if (qbounds[i].includes(allobj[k]->getPos())) 
                    someobj.push_back(allobj[k]);
            }
            dbg<<"added "<<someobj.size()<<" obj\n";

            // Does a really quick and dirty fit to the bright stars
            // Basically it takes the 10 smallest of the 50 brightest objects,
            // finds the peakiest 5, then fits their sizes to a 1st order function.
            // It also gives us a rough value for the sigma
            Legendre2D flinear(qbounds[i]);
            double sigma;
            roughlyFitBrightStars(someobj,&flinear,&sigma);
            dbg<<"fit bright stars: sigma = "<<sigma<<std::endl;

            // Calculate the min and max values of the (adjusted) sizes
            double min_size,max_size;
            findMinMax(someobj,&min_size,&max_size,flinear);
            dbg<<"min,max = "<<min_size<<','<<max_size<<std::endl;

            // Find the objects clustered around the stellar peak.
            std::vector<PotentialStar*> qpeak_list =
                getPeakList(
                    someobj,_bin_size1,min_size,max_size,
                    int(_nstart1*someobj.size()),_min_iter1,_mag_step1,_max_ratio1,
                    true,flinear);
            const int npeak = qpeak_list.size();
            dbg<<"peaklist has "<<npeak<<" stars\n";

            // Remove outliers using a median,percentile rejection scheme.
            // _bin_size1/2. is the minimum value of "sigma".
            rejectOutliers(qpeak_list,_reject1,_bin_size1/2.,flinear);
            dbg<<"rejected outliers, now have "<<npeak<<" stars\n";

            // Use at most 10 (stars_per_bin) stars per region to prevent one region 
            // from dominating the fit.  Use the 10 brightest stars to prevent being
            // position biased (as one would if it were based on size
            int nstars_expected = int(_star_frac * someobj.size());
            if (npeak < nstars_expected) {
                if (npeak < int(0.2 * nstars_expected)) {
                    if (_des_qa) {
                        std::cout<<"STATUS3BEG Warning: Only "<<
                            qpeak_list.size()<<" stars found in section "<<
                            i<<". STATUS3END"<<std::endl;
                    }
                    dbg<<"Warning: only "<<qpeak_list.size()<<
                        " stars found in section "<<i<<
                        "  "<<qbounds[i]<<std::endl;
                }
                probstars.insert(probstars.end(),qpeak_list.begin(),qpeak_list.end());
            } else {
                std::sort(qpeak_list.begin(),qpeak_list.end(),
                          std::mem_fun(&PotentialStar::isBrighterThan));
                probstars.insert(probstars.end(),qpeak_list.begin(),
                                 qpeak_list.begin()+nstars_expected);
            }
            dbg<<"added to probstars\n";
        }
        xdbg<<"done qbounds loop\n";
    }
    int nstars = probstars.size();
    dbg<<"nstars = "<<nstars<<std::endl;

    // Now we have a first estimate of which objects are stars.
    // Fit a quadratic function to them to characterize the variation in size
    Legendre2D f(total_bounds);
    double sigma;
    fitStellarSizes(&f,_fit_order,_fit_sig_clip,probstars,&sigma);

    // Second stage:
    // Use the fitted function for the size we just got to adjust
    // the measured sizes according to their position in the image.
    // Make the histogram using measured - predicted sizes (still log
    // size actually) which should then have the peak very close to 0.
    // Set the bin size for this new histogram to be the rms scatter of the
    // stellar peak from pass 1.
    // This time step by 0.25 mag (mag_step2).

    // Find the values of min_size,max_size for the whole thing with the new f
    double min_size,max_size;
    findMinMax(allobj,&min_size,&max_size,f);
    dbg<<"new minmax = "<<min_size<<','<<max_size<<std::endl;

    // Find the objects clustered around the stellar peak.
    // Note that the bin_size is a set fraction of sigma (0.5), so this
    // should make the stellar peak clearer.
    // Also, the f at the end means the functional fitted size will be
    // subtracted off before adding to the histogram.
    probstars = getPeakList(
        allobj,0.5*sigma,min_size,max_size,
        int(_nstart2*allobj.size()),_min_iter2,_mag_step2,_purity_ratio,false,f);
    nstars = probstars.size();
    dbg<<"probstars has "<<nstars<<" stars\n";

    // Remove outliers using a iterative median,percentile rejection scheme.
    rejectOutliersIter(probstars,_reject2,0.1,f,false);
    dbg<<"rejected outliers, now have "<<probstars.size()<<" stars\n";
    std::sort(probstars.begin(),probstars.end(),
              std::mem_fun(&PotentialStar::isBrighterThan));
    

    // If you get a bad fit the first time through, it can take a 
    // few passes to fix it.
    // And always do at least one refit.
    bool refit = true;
    for(int iter=0;refit && iter<_max_refit_iter;++iter) {
        dbg<<"starting refit\n"<<std::endl;
        refit = false;
        std::vector<std::vector<PotentialStar*> > stars_list(nsection);

        // Add each star to the appropriate sublist
        for(int k=0;k<nstars;++k) {
            for(int i=0;i<nsection;++i) {
                if(qbounds[i].includes(probstars[k]->getPos()))
                    stars_list[i].push_back(probstars[k]);
            }
        }

        // Make fit_list, use sg cuts if enough objects otherwise use the 
        // list of the 10 brightest stars per section
        std::vector<PotentialStar*> fit_list;

        if(!ignore_sg_cut) {
            for(int k=0;k<nobj;++k) {

                if (isOkSg(allobj[k]->getSg()) && isOkSgMag(allobj[k]->getMag())) {
                    fit_list.insert(fit_list.end(),allobj[k]);
                }
            }
            rejectOutliersIter(fit_list,_reject1,0.1,f,false);
            dbg<<"rejected outliers, now have "<<fit_list.size()<<" stars\n";
            std::sort(fit_list.begin(),fit_list.end(),
                      std::mem_fun(&PotentialStar::isBrighterThan));
            


        } else {

            dbg<<"  Fraction of objects in star-galaxy range too small "<<std::endl;
            for(int i=0;i<nsection;++i) {
                // if there are still < 10 stars, give a warning, and
                // just add all the stars to fit_list
                if (int(stars_list[i].size()) < _stars_per_bin) {
                    if (_des_qa) {
                        std::cout<<"STATUS3BEG Warning: Only "<<
                            stars_list[i].size()<<" stars in section "<<i<<
                            ". STATUS3END"<<std::endl;
                    }
                    dbg<<"Warning: only "<<stars_list[i].size()<<
                        " stars in section ";
                    dbg<<i<<"  "<<qbounds[i]<<std::endl;
                    fit_list.insert(fit_list.end(),stars_list[i].begin(),
                                    stars_list[i].end());
                    refit = true;
                } else {
                    // sort the sublist by magnitude
                    std::sort(stars_list[i].begin(),stars_list[i].end(),
                              std::mem_fun(&PotentialStar::isBrighterThan));

                    // add the brightest 10 to fit_list
                    fit_list.insert(fit_list.end(),stars_list[i].begin(),
                                    stars_list[i].begin()+_stars_per_bin);
                }
            }
        }

        // Do all the same stuff as before (refit f, get new min,max,
        // find the peak_list again, and reject the outliers)
        nstars = fit_list.size();
        fitStellarSizes(&f,_fit_order,_fit_sig_clip,fit_list,&sigma);
        findMinMax(allobj,&min_size,&max_size,f);
        dbg<<"new minmax = "<<min_size<<','<<max_size<<std::endl;
        probstars = getPeakList(
            allobj,0.5*sigma,min_size,max_size,
            int(_nstart2*allobj.size()),_min_iter2,_mag_step2,
            _purity_ratio,false,f);
        dbg<<"probstars has "<<probstars.size()<<" stars\n";
        rejectOutliersIter(probstars,_reject2,0.1,f,false);
        dbg<<"rejected outliers, now have "<<probstars.size()<<" stars\n";
        if (int(probstars.size()) < nstars) {
            refit = true;
            dbg<<"fewer than "<<nstars<<" - so refit\n";
        }
        nstars = probstars.size();
    }

    dbg<<"done FindStars\n";

    for(int i=0;i<nstars;++i) {
        xdbg<<"stars["<<i<<"]: size = "<<probstars[i]->getSize();
        xdbg<<", size - f(pos) = ";
        xdbg<<probstars[i]->getSize()-f(probstars[i]->getPos())<<std::endl;
        xdbg<<probstars[i]->getLine()<<std::endl;
    }
    return probstars;
}
Exemple #25
0
bool
GrdPlugin::setFile(QStringList files)
{
  m_fileName = files;

  m_imageList.clear();

  QFileInfo f(m_fileName[0]);
  if (f.isDir())
    {
      // list all image files in the directory
      QStringList imageNameFilter;
      imageNameFilter << "*";
      QStringList imgfiles= QDir(m_fileName[0]).entryList(imageNameFilter,
							  QDir::NoSymLinks|
							  QDir::NoDotAndDotDot|
							  QDir::Readable|
							  QDir::Files);


      m_imageList.clear();
      for(uint i=0; i<imgfiles.size(); i++)
	{
	  QFileInfo fileInfo(m_fileName[0], imgfiles[i]);
	  QString imgfl = fileInfo.absoluteFilePath();
	  m_imageList.append(imgfl);
	}
    }
  else
    m_imageList = files;

  // --- load various parameters from the raw file ---
  LoadRawDialog loadRawDialog(0,
			      (char *)m_imageList[0].toAscii().data());
  //(char *)m_fileName[0].toAscii().data());

  loadRawDialog.exec();
  if (loadRawDialog.result() == QDialog::Rejected)
    return false;
  
  m_voxelType = loadRawDialog.voxelType();
  m_headerBytes = loadRawDialog.skipHeaderBytes();

  int nX, nY, nZ;
  loadRawDialog.gridSize(nX, nY, nZ);

  m_depth = m_imageList.size();
  m_width = nX;
  m_height = nY;


  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  return true;
}
bool
RemapHDF4::setFile(QList<QString> fl)
{
  m_fileName = fl;
  
  // list all image files in the directory
  QStringList imageNameFilter;
  imageNameFilter << "*.hdf";
  QStringList files= QDir(m_fileName[0]).entryList(imageNameFilter,
						   QDir::NoSymLinks|
						   QDir::NoDotAndDotDot|
						   QDir::Readable|
						   QDir::Files);
  m_imageList.clear();
  for(uint i=0; i<files.size(); i++)
    {
      QFileInfo fileInfo(m_fileName[0], files[i]);
      QString imgfl = fileInfo.absoluteFilePath();
      m_imageList.append(imgfl);
    }

  m_depth = m_imageList.size();


  /* Open the file and initiate the SD interface. */
  int32 sd_id = SDstart(strdup(m_imageList[0].toAscii().data()),
		  DFACC_READ);
  if (sd_id < 0) {
    QMessageBox::information(0, 
			     "Error",
			     QString("Failed to open %1").arg(m_imageList[0]));
    return false;
  }
    
  /* Determine the contents of the file. */
  int32 dim_sizes[MAX_VAR_DIMS];
  int32 rank, num_type, attributes, istat;
  char name[64];
  int32 n_datasets, n_file_attrs;

  istat = SDfileinfo(sd_id, &n_datasets, &n_file_attrs);

  /* Access the name of every data set in the file. */
  QStringList varNames;
  for (int32 index = 0; index < n_datasets; index++)
    {
      int32 sds_id = SDselect(sd_id, index);
      
      istat = SDgetinfo(sds_id, name, &rank, dim_sizes,	\
			&num_type, &attributes);
            
      istat = SDendaccess(sds_id);

      if (rank == 2)
	varNames.append(name);
    }
  
  QString var;
  if (varNames.size() == 0) {
    QMessageBox::information(0, 
			     "Error",
			     QString("No variables in file with rank of 2"));
    return false;
  } else if (varNames.size() == 1)
    {
      var = varNames[0];
    }
  else
    {
      var = QInputDialog::getItem(0,
				  "Select Variable to Extract",
				  "Variable Names",
				  varNames,
				  0,
				  false);
    }
  
  m_Index = 0;
  for (int32 index = 0; index < n_datasets; index++)
    {
      int32 sds_id = SDselect(sd_id, index);
      
      istat = SDgetinfo(sds_id, name, &rank, dim_sizes,	\
			&num_type, &attributes);
      
      istat = SDendaccess(sds_id);
      
      if (var == QString(name))
	{
	  m_Index = index;
	  break;
	}
    }

  {    
    int32 sds_id = SDselect(sd_id, m_Index);
    
    istat = SDgetinfo(sds_id,
		      name,
		      &rank,
		      dim_sizes,
		      &num_type,
		      &attributes);
    
    istat = SDendaccess(sds_id);
  }

  /* Terminate access to the SD interface and close the file. */
  istat = SDend(sd_id);


  if (num_type == DFNT_CHAR8)
    m_voxelType = _Char;
  else if (num_type == DFNT_UCHAR8)
    m_voxelType = _UChar;
  else if (num_type == DFNT_INT8)
    m_voxelType = _Char;
  else if (num_type == DFNT_UINT8)
    m_voxelType = _UChar;
  else if (num_type == DFNT_INT16)
    m_voxelType = _Short;
  else if (num_type == DFNT_UINT16)
    m_voxelType = _UShort;
  else if (num_type == DFNT_INT32)
    m_voxelType = _Int;
  else if (num_type == DFNT_FLOAT32)
    m_voxelType = _Float;
  else
    {
      QMessageBox::information(0, "Error",
			       QString("Cannot handle datatype %1").arg(num_type));
      return false;
    }

  m_width = dim_sizes[0];
  m_height = dim_sizes[1];

  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  m_headerBytes = 0;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  m_rawMap.append(m_rawMin);
  m_rawMap.append(m_rawMax);
  m_pvlMap.append(0);
  m_pvlMap.append(255);

  return true;
}
Exemple #27
0
bool
NrrdPlugin::setFile(QStringList files)
{
  m_fileName = files;
 
  typedef itk::Image<unsigned char, 3> ImageType;
  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(m_fileName[0].toAscii().data());

  typedef itk::NrrdImageIO NrrdIOType;
  NrrdIOType::Pointer nrrdIO = NrrdIOType::New();
  reader->SetImageIO(nrrdIO);
  reader->Update();

  itk::ImageIOBase::Pointer imageIO = reader->GetImageIO();

  m_height = imageIO->GetDimensions(0);
  m_width = imageIO->GetDimensions(1);
  m_depth = imageIO->GetDimensions(2);

  m_voxelSizeX = imageIO->GetSpacing(0);
  m_voxelSizeY = imageIO->GetSpacing(1);
  m_voxelSizeZ = imageIO->GetSpacing(2);

  int et = imageIO->GetComponentType();
  if (et == itk::ImageIOBase::UCHAR) m_voxelType = _UChar;
  if (et == itk::ImageIOBase::CHAR) m_voxelType = _Char;
  if (et == itk::ImageIOBase::USHORT) m_voxelType = _UShort;
  if (et == itk::ImageIOBase::SHORT) m_voxelType = _Short;
  if (et == itk::ImageIOBase::INT) m_voxelType = _Int;
  if (et == itk::ImageIOBase::FLOAT) m_voxelType = _Float;

  m_skipBytes = m_headerBytes = 0;

  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  if (m_4dvol) // do not perform further calculations.
    return true;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  return true;
}
int TfceScore::CalculateTFCE(float E, float H, float dh, int pos_or_neg)
{
	char buffer[100];
	float **vmp;
	float * vv = NULL;
	bool log = 1;
	int overlayed_vmp_index = 0;
	float min, max, range;
	struct VMR_Header vmr_header;
	struct NR_VMPs_Header vmps_header;
	struct NR_VMP_Header vmp_header;
	int dim;

	if (!qxGetMainHeaderOfCurrentVMR(&vmr_header)){
		qxLogText("Plugin>  Problem Get resolution voxel");
		return false;
	}

	if ((vmp = qxGetNRVMPsOfCurrentVMR(&vmps_header)) != NULL) {
		int dimX = (vmps_header.XEnd - vmps_header.XStart) / vmps_header.Resolution;
		int dimY = (vmps_header.YEnd - vmps_header.YStart) / vmps_header.Resolution;
		int dimZ = (vmps_header.ZEnd - vmps_header.ZStart) / vmps_header.Resolution;

		dim = dimX*dimY*dimZ;

		//this for loop should select currently overlayed vmp sub map
		int num_of_maps = vmps_header.NrOfMaps;
		
		for (overlayed_vmp_index = 0; overlayed_vmp_index < num_of_maps; overlayed_vmp_index++){
			vv = qxGetNRVMPOfCurrentVMR(overlayed_vmp_index, &vmp_header);
			if (vmp_header.OverlayMap)
				break;
		}

		//pos_or_neg check and action here
		if (pos_or_neg){//positives only
			for (int i = 0; i < dim; i++){
				if (vv[i] < 0){
					vv[i] = 0;
				}
			}
		}
		else{ // negatives only
			for (int i = 0; i < dim; i++){
				if (vv[i] > 0){
					vv[i] = 0;
				}
				if (vv[i] < 0){
					vv[i] = -vv[i];
				}
			}
		}
		
		//vv = qxGetNRVMPOfCurrentVMR(0, &vmp_header);
		qxLogText("Plugin> Starting to calculate TFCE...");
		omp_set_num_threads(omp_get_num_procs());
		float * scores = tfce_score(vv, dimX, dimY, dimZ, E, H, dh);
		findMinMax(scores, dim, &min, &max, &range);
		sprintf(buffer, "Score minimo: %f Score massimo: %f\n", min, max);
		qxLogText(buffer);
		
		/*
		float f = Fwhm(vv, dimX, dimY, dimZ);
		//f *= 2.355;
		sprintf(buffer, "Plugin> Estimated FWHM %f", f);
		qxLogText(buffer);
		*/
		
		/*if (check){
			qxLogText("Plugin> Finished TFCE, starting permutation test...");
			applicaPermutazioni(vv, dimX, dimY, dimZ, E, H, dh, rep, scores);
		}*/
		
		//threshold_matrix(scores, dim, min, max);
		memcpy(vv, scores, sizeof(float)* dimX*dimY*dimZ);
		findMinMax(scores, dimX*dimY*dimZ, &min, &max, &range);
		delete[] scores;
		//sprintf(buffer, "Score minimo sogliato: %f Score massimo sogliato: %f\n", min, max);
		//qxLogText(buffer);
		//Computing visualization bounds
		
		float max_t = max;
		float min_t = max - (max*50) / 100;

		//sprintf(buffer, "Score minimo visualizzato: %f Score massimo visualizzato: %f", min_t, max_t);
		//qxLogText(buffer);

		//Refreshing vmp header
		vmp_header.ThreshMax = max_t;
		vmp_header.ThreshMin = min_t;
		vmp_header.UseClusterSize = 0;
		vmp_header.ShowPosOrNegOrBoth = 1;
		qxSetNRVMPParametersOfCurrentVMR(overlayed_vmp_index, &vmp_header);
		//Refresh
		qxUpdateActiveWindow();
		sprintf(buffer, "Finished calculation");
		qxLogText(buffer);
		return true;
	}
	else{
		qxLogText("Plugin>  VMP not found");
	}
	return false;
}